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 |
|---|---|---|---|---|---|---|---|---|---|---|
dfbebf26f52db94c9fc8e1056c39013d8cdb2656 | name/context_processors.py | name/context_processors.py | def baseurl(request):
"""
Return a BASE_URL template context for the current request
"""
if request.is_secure():
scheme = 'https://'
else:
scheme = 'http://'
return {
'BASE_URL': scheme + request.get_host(),
}
| from name.models import NAME_TYPE_CHOICES
def baseurl(request):
"""
Return a BASE_URL template context for the current request
"""
if request.is_secure():
scheme = 'https://'
else:
scheme = 'http://'
return {
'BASE_URL': scheme + request.get_host(),
}
def name_types(request):
return {'name_types': dict(NAME_TYPE_CHOICES)}
| Add a new context processor to include the NAME_TYPE_CHOICES in every request context. | Add a new context processor to include the NAME_TYPE_CHOICES in every request context.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name | ---
+++
@@ -1,3 +1,6 @@
+from name.models import NAME_TYPE_CHOICES
+
+
def baseurl(request):
"""
Return a BASE_URL template context for the current request
@@ -10,3 +13,7 @@
return {
'BASE_URL': scheme + request.get_host(),
}
+
+
+def name_types(request):
+ return {'name_types': dict(NAME_TYPE_CHOICES)} |
f33bf5a99b9bb814fe6da6b7713e87014aae5fdf | src/journal/migrations/0035_journal_xsl.py | src/journal/migrations/0035_journal_xsl.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'),
]
operations = [
migrations.AddField(
model_name='journal',
name='xsl',
field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'),
preserve_default=False,
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'),
('core', '0037_journal_xsl_files'),
]
operations = [
migrations.AddField(
model_name='journal',
name='xsl',
field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'),
preserve_default=False,
),
]
| Fix migration tree for journal 0035 | Fix migration tree for journal 0035
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -11,6 +11,9 @@
dependencies = [
('journal', '0034_migrate_issue_types'),
+ ('core', '0037_journal_xsl_files'),
+
+
]
operations = [ |
0904d8f5ca4f10b4cc7121e60c35f7560e37019c | boardinghouse/templatetags/boardinghouse.py | boardinghouse/templatetags/boardinghouse.py | from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import get_schema_model
Schema = get_schema_model()
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(pk):
try:
return Schema.objects.get(pk=pk).name
except Schema.DoesNotExist:
return "no schema"
| from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import _get_schema
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(schema):
try:
return _get_schema(schema).name
except AttributeError:
return "no schema"
| Remove a database access from the template tag. | Remove a database access from the template tag.
| Python | bsd-3-clause | luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse | ---
+++
@@ -1,9 +1,7 @@
from django import template
from ..schema import is_shared_model as _is_shared_model
-from ..schema import get_schema_model
-
-Schema = get_schema_model()
+from ..schema import _get_schema
register = template.Library()
@@ -16,8 +14,8 @@
return obj and _is_shared_model(obj)
@register.filter
-def schema_name(pk):
+def schema_name(schema):
try:
- return Schema.objects.get(pk=pk).name
- except Schema.DoesNotExist:
+ return _get_schema(schema).name
+ except AttributeError:
return "no schema" |
4b448c704f69b951d19229c85debfdb5a2e122c1 | citeproc/py2compat.py | citeproc/py2compat.py |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import locale
import sys
__all__ = ['PY2']
PY2 = sys.version_info < (3, 0)
if PY2:
__all__ += ['str', 'print', 'open']
from io import open
str = unicode
std_print = print
def print(*objects, **kwargs):
if kwargs.get('file', sys.stdout) == sys.stdout:
objects = (unicode(obj) for obj in objects)
if not sys.stdout.encoding:
objects = (obj.encode(locale.getpreferredencoding())
for obj in objects)
std_print(*objects, **kwargs)
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import locale
import sys
__all__ = ['PY2']
PY2 = sys.version_info < (3, 0)
if PY2:
__all__ += ['str', 'print', 'open']
from io import open
str = unicode
std_print = print
def print(*objects, **kwargs):
if kwargs.get('file', sys.stdout) == sys.stdout:
objects = (unicode(obj) for obj in objects)
if not getattr(sys.stdout, 'encoding', None):
objects = (obj.encode(locale.getpreferredencoding())
for obj in objects)
std_print(*objects, **kwargs)
| Fix Tox/Travis testing on Python 2.7 | Fix Tox/Travis testing on Python 2.7 | Python | bsd-2-clause | jayvdb/citeproc-py | ---
+++
@@ -20,7 +20,7 @@
def print(*objects, **kwargs):
if kwargs.get('file', sys.stdout) == sys.stdout:
objects = (unicode(obj) for obj in objects)
- if not sys.stdout.encoding:
+ if not getattr(sys.stdout, 'encoding', None):
objects = (obj.encode(locale.getpreferredencoding())
for obj in objects)
std_print(*objects, **kwargs) |
2436f1a00021baa39f3d3dfece1d44a2d3351dfd | bin/create_test_user.py | bin/create_test_user.py | # Create a dummy user for the app store review testing
# This needs to be done every time we switch to a new database
import sys
from dao.user import User
def create_fake_JWT_token(userEmail):
"""
Creates a fake JWT token for the specified user. This has two major benefits.
1. It allows us to finally write some tests for the api layer
2. It allows the utility functions to communicate with the server via the
API layer, making it easier to unify the implementation. But on the
other hand, then it is hard to ensure proper separation between the API layer
and the implementations, which makes it harder to replace bottle with something else later.
"""
pass
def register_user(userEmail):
"""
Does some sanity checking and then registers the user with the specified email address.
This is useful for testing.
"""
if User.fromEmail(userEmail) is not None:
raise RuntimeError("User with email %s already exists" % userEmail)
userObj = User.register(userEmail)
print "Registration successful!"
print "User profile is %s" % userObj.getProfile();
if __name__ == '__main__':
if len(sys.argv) < 2:
print "USAGE: %s userEmail\n" % sys.argv[0]
exit(0)
register_user(sys.argv[1])
| # Create a dummy user for the app store review testing
# This needs to be done every time we switch to a new database
import sys
from emission.core.wrapper.user import User
def create_fake_JWT_token(userEmail):
"""
Creates a fake JWT token for the specified user. This has two major benefits.
1. It allows us to finally write some tests for the api layer
2. It allows the utility functions to communicate with the server via the
API layer, making it easier to unify the implementation. But on the
other hand, then it is hard to ensure proper separation between the API layer
and the implementations, which makes it harder to replace bottle with something else later.
"""
pass
def register_user(userEmail):
"""
Does some sanity checking and then registers the user with the specified email address.
This is useful for testing.
"""
if User.fromEmail(userEmail) is not None:
raise RuntimeError("User with email %s already exists" % userEmail)
userObj = User.register(userEmail)
print "Registration successful!"
print "User profile is %s" % userObj.getProfile();
if __name__ == '__main__':
if len(sys.argv) < 2:
print "USAGE: %s userEmail\n" % sys.argv[0]
exit(0)
register_user(sys.argv[1])
| Fix import to match the new directory structure | Fix import to match the new directory structure
| Python | bsd-3-clause | yw374cornell/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server | ---
+++
@@ -2,7 +2,7 @@
# This needs to be done every time we switch to a new database
import sys
-from dao.user import User
+from emission.core.wrapper.user import User
def create_fake_JWT_token(userEmail):
""" |
6e3d24b0594434577de6950190f0f103e08a2fbe | Source/Perforce/wb_p4_credential_dialogs.py | Source/Perforce/wb_p4_credential_dialogs.py | '''
====================================================================
Copyright (c) 2018 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
====================================================================
wb_p4_credential_dialogs.py
'''
from PyQt5 import QtWidgets
import wb_dialog_bases
class WbP4GetLoginDialog(wb_dialog_bases.WbDialog):
def __init__( self, app, parent, url, realm ):
super().__init__( parent )
self.setWindowTitle( T_('Perforce Credentials - %s') % (' '.join( app.app_name_parts ),) )
self.username = QtWidgets.QLineEdit( '' )
self.password = QtWidgets.QLineEdit()
self.password.setEchoMode( self.password.Password )
self.username.textChanged.connect( self.nameTextChanged )
self.password.textChanged.connect( self.nameTextChanged )
em = self.fontMetrics().width( 'M' )
self.addRow( T_('URL'), url )
self.addRow( T_('Realm'), realm )
self.addRow( T_('Username'), self.username, min_width=50*em )
self.addRow( T_('Password'), self.password )
self.addButtons()
def completeInit( self ):
# set focus
self.username.setFocus()
def nameTextChanged( self, text ):
self.ok_button.setEnabled( self.getUsername() != '' and self.getPassword() != '' )
def getUsername( self ):
return self.username.text().strip()
def getPassword( self ):
return self.password.text().strip()
| '''
====================================================================
Copyright (c) 2018 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
====================================================================
wb_p4_credential_dialogs.py
'''
from PyQt5 import QtWidgets
import wb_dialog_bases
class WbP4GetLoginDialog(wb_dialog_bases.WbDialog):
def __init__( self, app, parent, username ):
super().__init__( parent )
self.setWindowTitle( T_('Perforce Credentials - %s') % (' '.join( app.app_name_parts ),) )
self.password = QtWidgets.QLineEdit()
self.password.setEchoMode( self.password.Password )
self.password.textChanged.connect( self.passwordTextChanged )
em = self.fontMetrics().width( 'M' )
self.addRow( T_('Username'), username, min_width=50*em )
self.addRow( T_('Password'), self.password )
self.addButtons()
def completeInit( self ):
# set focus
self.password.setFocus()
def passwordTextChanged( self, text ):
self.ok_button.setEnabled( self.getPassword() != '' )
def getPassword( self ):
return self.password.text().strip()
| Update the crential dialog for perforce - untested | Update the crential dialog for perforce - untested | Python | apache-2.0 | barry-scott/git-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/git-workbench | ---
+++
@@ -15,37 +15,29 @@
import wb_dialog_bases
class WbP4GetLoginDialog(wb_dialog_bases.WbDialog):
- def __init__( self, app, parent, url, realm ):
+ def __init__( self, app, parent, username ):
super().__init__( parent )
self.setWindowTitle( T_('Perforce Credentials - %s') % (' '.join( app.app_name_parts ),) )
- self.username = QtWidgets.QLineEdit( '' )
self.password = QtWidgets.QLineEdit()
self.password.setEchoMode( self.password.Password )
- self.username.textChanged.connect( self.nameTextChanged )
- self.password.textChanged.connect( self.nameTextChanged )
+ self.password.textChanged.connect( self.passwordTextChanged )
em = self.fontMetrics().width( 'M' )
- self.addRow( T_('URL'), url )
- self.addRow( T_('Realm'), realm )
- self.addRow( T_('Username'), self.username, min_width=50*em )
+ self.addRow( T_('Username'), username, min_width=50*em )
self.addRow( T_('Password'), self.password )
self.addButtons()
def completeInit( self ):
# set focus
- self.username.setFocus()
+ self.password.setFocus()
-
- def nameTextChanged( self, text ):
- self.ok_button.setEnabled( self.getUsername() != '' and self.getPassword() != '' )
-
- def getUsername( self ):
- return self.username.text().strip()
+ def passwordTextChanged( self, text ):
+ self.ok_button.setEnabled( self.getPassword() != '' )
def getPassword( self ):
return self.password.text().strip() |
2e6267c7b283fd579395fc3faac2b253ddb032fe | src/midonet/auth/keystone.py | src/midonet/auth/keystone.py |
from keystoneclient.v2_0 import client as keystone_client
from datetime import datetime
from datetime import timedelta
class KeystoneAuth:
def __init__(self, uri, username, password, tenant_id=None,
tenant_name=None):
self.uri = uri
self.username = username
self.password = password
self.tenant_id = tenant_id
self.tenant_name = tenant_name
self.token = None
self.token_expires = None
self.headers = {}
def generate_auth_header(self):
if (self.token_expires == None or
self.token_expires - datetime.now() < timedelta(seconds=60*60)):
try:
self.token = self._generate_token()
except Exception as e:
print 'failed ', e
self.headers["X-Auth-Token"] = self.token
return self.headers
def _generate_token(self):
ks_conn = keystone_client.Client(endpoint=self.uri)
token = ks_conn.tokens.authenticate(
username=self.username, password=self.password,
tenant_id=self.tenant_id, tenant_name=self.tenant_name)
self.token_expires = datetime.strptime(token.expires, '%Y-%m-%dT%H:%M:%SZ')
return token.id
|
from keystoneclient.v2_0 import client as keystone_client
from datetime import datetime
from datetime import timedelta
class KeystoneAuth:
def __init__(self, uri, username, password, tenant_id=None,
tenant_name=None):
self.uri = uri
self.username = username
self.password = password
self.tenant_id = tenant_id
self.tenant_name = tenant_name
self.token = None
self.token_expires = None
self.headers = {}
def generate_auth_header(self):
if (self.token_expires == None or
self.token_expires - datetime.now() < timedelta(seconds=60*60)):
try:
self.token = self.get_token()
self.token_expires = datetime.strptime(self.token.expires,
'%Y-%m-%dT%H:%M:%SZ')
except Exception as e:
print 'failed ', e
self.headers["X-Auth-Token"] = self.token.id
return self.headers
def get_token(self):
if (self.token_expires == None or
self.token_expires - datetime.now() < timedelta(seconds=60*60)):
ks_conn = keystone_client.Client(endpoint=self.uri)
self.token = ks_conn.tokens.authenticate(
username=self.username, password=self.password,
tenant_id=self.tenant_id, tenant_name=self.tenant_name)
return self.token
| Add public method to get token. | Add public method to get token.
Signed-off-by: Tomoe Sugihara <6015414ca332492cf0bb4dbbac212276d1c110a7@midokura.com>
| Python | apache-2.0 | midonet/python-midonetclient,midonet/python-midonetclient,midokura/python-midonetclient,midokura/python-midonetclient | ---
+++
@@ -22,22 +22,21 @@
if (self.token_expires == None or
self.token_expires - datetime.now() < timedelta(seconds=60*60)):
try:
- self.token = self._generate_token()
+ self.token = self.get_token()
+ self.token_expires = datetime.strptime(self.token.expires,
+ '%Y-%m-%dT%H:%M:%SZ')
except Exception as e:
print 'failed ', e
- self.headers["X-Auth-Token"] = self.token
+ self.headers["X-Auth-Token"] = self.token.id
return self.headers
- def _generate_token(self):
- ks_conn = keystone_client.Client(endpoint=self.uri)
- token = ks_conn.tokens.authenticate(
- username=self.username, password=self.password,
- tenant_id=self.tenant_id, tenant_name=self.tenant_name)
+ def get_token(self):
+ if (self.token_expires == None or
+ self.token_expires - datetime.now() < timedelta(seconds=60*60)):
+ ks_conn = keystone_client.Client(endpoint=self.uri)
+ self.token = ks_conn.tokens.authenticate(
+ username=self.username, password=self.password,
+ tenant_id=self.tenant_id, tenant_name=self.tenant_name)
+ return self.token
-
- self.token_expires = datetime.strptime(token.expires, '%Y-%m-%dT%H:%M:%SZ')
- return token.id
-
-
- |
7895b0a39694e88ed1bdd425c69fb747b7531c59 | indico/testing/mocks.py | indico/testing/mocks.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 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/>.
class MockConferenceHolder:
# This class is monkeypatched on top of the real conferenceholder
_events = {}
def __init__(self):
pass
@classmethod
def add(cls, event):
if event.id in cls._events:
__tracebackhide__ = True
raise Exception("Event '{}' already exists".format(event.id))
cls._events[event.id] = event
@classmethod
def remove(cls, event):
del cls._events[event.id]
@classmethod
def getById(cls, id_):
return cls._events.get(id_)
class MockConference(object):
def __repr__(self):
return '<MockConference({})>'.format(self.id)
def getId(self):
return self.id
| # This file is part of Indico.
# Copyright (C) 2002 - 2015 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/>.
class MockConferenceHolder:
# This class is monkeypatched on top of the real conferenceholder
_events = {}
def __init__(self):
pass
@classmethod
def add(cls, event):
if event.id in cls._events:
__tracebackhide__ = True
raise Exception("Event '{}' already exists".format(event.id))
cls._events[int(event.id)] = event
@classmethod
def remove(cls, event):
del cls._events[int(event.id)]
@classmethod
def getById(cls, id_, quiet=None):
return cls._events.get(int(id_))
class MockConference(object):
def __repr__(self):
return '<MockConference({})>'.format(self.id)
def getId(self):
return self.id
| Fix str/int usage in MockConferenceHolder | Fix str/int usage in MockConferenceHolder
| Python | mit | indico/indico,ThiefMaster/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,indico/indico,mvidalgarcia/indico,pferreir/indico,mic4ael/indico,pferreir/indico,mvidalgarcia/indico,DirkHoffmann/indico,DirkHoffmann/indico,indico/indico | ---
+++
@@ -27,15 +27,15 @@
if event.id in cls._events:
__tracebackhide__ = True
raise Exception("Event '{}' already exists".format(event.id))
- cls._events[event.id] = event
+ cls._events[int(event.id)] = event
@classmethod
def remove(cls, event):
- del cls._events[event.id]
+ del cls._events[int(event.id)]
@classmethod
- def getById(cls, id_):
- return cls._events.get(id_)
+ def getById(cls, id_, quiet=None):
+ return cls._events.get(int(id_))
class MockConference(object): |
06b6b2fa0d8f7d8e4ef35068c3aa32cd39ac04c3 | accountant/functional_tests/test_homepage.py | accountant/functional_tests/test_homepage.py | # -*- coding: utf-8 -*-
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the title of the browser contains '18xx Accountant'
self.assertEqual(self.browser.title, '18xx Accountant')
# There is a button that says "Start new game", she clicks it
page = game.Homepage(self.browser)
self.assertEqual(page.start_button.text, 'Start new game')
page.start_button.click()
# She lands on a new page, it lists a code for the game name
self.assertIn('/en/game/', self.browser.current_url)
housekeeping = game.Housekeeping(self.browser)
self.assertEqual(len(housekeeping.game_name.text), 4)
| # -*- coding: utf-8 -*-
import unittest
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
@unittest.skip
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the title of the browser contains '18xx Accountant'
self.assertEqual(self.browser.title, '18xx Accountant')
# There is a button that says "Start new game", she clicks it
page = game.Homepage(self.browser)
self.assertEqual(page.start_button.text, 'Start new game')
page.start_button.click()
# She lands on a new page, it lists a code for the game name
self.assertIn('/en/game/', self.browser.current_url)
housekeeping = game.Housekeeping(self.browser)
self.assertEqual(len(housekeeping.game_name.text), 4)
def test_loads_angular_application(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the Angular 2 app has loaded
app = self.browser.find_element_by_tag_name('app-root')
self.assertIn('app works!', app.text)
| Add FT to test if angular is loaded | Add FT to test if angular is loaded
| Python | mit | XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant | ---
+++
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
+import unittest
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
+ @unittest.skip
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
@@ -18,3 +20,10 @@
self.assertIn('/en/game/', self.browser.current_url)
housekeeping = game.Housekeeping(self.browser)
self.assertEqual(len(housekeeping.game_name.text), 4)
+
+ def test_loads_angular_application(self):
+ # Alice is a user who visits the website
+ self.browser.get(self.live_server_url)
+ # She sees that the Angular 2 app has loaded
+ app = self.browser.find_element_by_tag_name('app-root')
+ self.assertIn('app works!', app.text) |
ba3544fc18d5c5e827b1c1777b7811201545a8c5 | boto/pyami/scriptbase.py | boto/pyami/scriptbase.py | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
boto.log.error(self.last_command.output)
if notify:
self.notify('Error encountered', self.last_command.output)
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| Add the command that failed to the error log and the error email to help debug problems where the error produces no output. | Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
| Python | mit | appneta/boto,dimdung/boto,j-carl/boto,ekalosak/boto,drbild/boto,acourtney2015/boto,bryx-inc/boto,darjus-amzn/boto,ddzialak/boto,alfredodeza/boto,vijaylbais/boto,clouddocx/boto,israelbenatar/boto,alex/boto,podhmo/boto,cyclecomputing/boto,shipci/boto,kouk/boto,jindongh/boto,felix-d/boto,Timus1712/boto,alex/boto,lochiiconnectivity/boto,Pretio/boto,dablak/boto,weebygames/boto,tpodowd/boto,jamesls/boto,disruptek/boto,dablak/boto,elainexmas/boto,jameslegg/boto,lochiiconnectivity/boto,varunarya10/boto,jamesls/boto,jameslegg/boto,bleib1dj/boto,nikhilraog/boto,pfhayes/boto,yangchaogit/boto,abridgett/boto,serviceagility/boto,tpodowd/boto,campenberger/boto,ryansb/boto,kouk/boto,ocadotechnology/boto,zzzirk/boto,FATruden/boto,revmischa/boto,weka-io/boto,rayluo/boto,shaunbrady/boto,TiVoMaker/boto,rosmo/boto,ric03uec/boto,vishnugonela/boto,lra/boto,drbild/boto,andresriancho/boto,garnaat/boto,awatts/boto,trademob/boto,andresriancho/boto,khagler/boto,nishigori/boto,ramitsurana/boto,SaranyaKarthikeyan/boto,nexusz99/boto,appneta/boto,zachmullen/boto,Asana/boto,rjschwei/boto,s0enke/boto,rjschwei/boto,stevenbrichards/boto,disruptek/boto,jotes/boto,janslow/boto | ---
+++
@@ -30,9 +30,11 @@
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
- boto.log.error(self.last_command.output)
+ boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
- self.notify('Error encountered', self.last_command.output)
+ self.notify('Error encountered', \
+ 'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
+ (command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status |
2872d4f34dbcfe4b212ca7c72a7b9ec725cfcc20 | pyQuantuccia/tests/test_get_holiday_date.py | pyQuantuccia/tests/test_get_holiday_date.py | from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
assert(quantuccia.get_holiday_date() is None)
| # from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
# assert(quantuccia.get_holiday_date() is None)
pass
| Comment out the tests so that the diagnostic test can run. | Comment out the tests so that the diagnostic test can run.
| Python | bsd-3-clause | jwg4/pyQuantuccia,jwg4/pyQuantuccia | ---
+++
@@ -1,8 +1,9 @@
-from pyQuantuccia import quantuccia
+# from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
- assert(quantuccia.get_holiday_date() is None)
+ # assert(quantuccia.get_holiday_date() is None)
+ pass |
d0b56873b40acd3932f450293c363b01b5a709b9 | jinja2_time/__init__.py | jinja2_time/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
from .jinja2_time import TimeExtension
__all__ = ['TimeExtension']
| # -*- coding: utf-8 -*-
from .jinja2_time import TimeExtension
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
__all__ = ['TimeExtension']
| Fix flake8 issue in init | Fix flake8 issue in init
| Python | mit | hackebrot/jinja2-time | ---
+++
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
+
+from .jinja2_time import TimeExtension
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
-from .jinja2_time import TimeExtension
__all__ = ['TimeExtension'] |
810e688e8e896caf5a3c6de1c76a5bc696d918c6 | apps.py | apps.py | import os
import webapp2
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
task_app = webapp2.WSGIApplication([
('/task/index', handlers.IndexTaskHandler),
('/task/torrent', handlers.TorrentTaskHandler),
('/task/update_feeds', handlers.FeedTaskHandler),
('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)
manage_app = webapp2.WSGIApplication([
('/manage/', handlers.DashboardHandler),
], debug=debug)
| import os
import webapp2
import logging
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)
task_app = webapp2.WSGIApplication([
('/task/index', handlers.IndexTaskHandler),
('/task/torrent', handlers.TorrentTaskHandler),
('/task/update_feeds', handlers.FeedTaskHandler),
('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)
manage_app = webapp2.WSGIApplication([
('/manage/', handlers.DashboardHandler),
], debug=debug)
| Set logging level depenging on environment | Set logging level depenging on environment
| Python | apache-2.0 | notapresent/rutracker_rss,notapresent/rutracker_rss,notapresent/rutracker_rss | ---
+++
@@ -1,10 +1,13 @@
import os
import webapp2
+import logging
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
+loglevel = logging.DEBUG if debug else logging.INFO
+logging.getLogger().setLevel(loglevel)
task_app = webapp2.WSGIApplication([
('/task/index', handlers.IndexTaskHandler), |
7e5221a65bd644cc86003f67daa3148f22b4a530 | hash_table.py | hash_table.py | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self):
pass
def set(self):
pass
| #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self):
pass
def set(self):
pass
| Build out hash item class | Build out hash item class
| Python | mit | jwarren116/data-structures-deux | ---
+++
@@ -8,8 +8,9 @@
class HashItem(object):
- def __init__(self):
- pass
+ def __init__(self, key, value):
+ self.key = key
+ self.value = value
class Hash(object): |
ca8556584876adfea9f9f1f1042ebb2704933f34 | addons/product/__terp__.py | addons/product/__terp__.py | {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support variants, different pricing methods, suppliers
information, make to stock/order, different unit of measures,
packagins and properties.
Pricelists supports:
* Multiple-level of discount (by product, category, quantities)
* Compute price based on different criterions:
* Other pricelist,
* Cost price,
* List price,
* Supplier price, ...
Pricelists preferences by product and/or partners.
Print product labels with barcodes.
""",
"update_xml" : ["product_data.xml","product_report.xml",
"product_view.xml", "pricelist_view.xml"],
"active": False,
"installable": True
}
| {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support variants, different pricing methods, suppliers
information, make to stock/order, different unit of measures,
packagins and properties.
Pricelists supports:
* Multiple-level of discount (by product, category, quantities)
* Compute price based on different criterions:
* Other pricelist,
* Cost price,
* List price,
* Supplier price, ...
Pricelists preferences by product and/or partners.
Print product labels with barcodes.
""",
"update_xml" : ["product_data.xml","product_report.xml",
"product_view.xml", "pricelist_view.xml","product_security.xml"],
"active": False,
"installable": True
}
| Add product_security.xml file entry in update_xml section | Add product_security.xml file entry in update_xml section
bzr revid: mga@tinyerp.com-c1c968b6c0a6dd356a1ae7bc971a2daa2356a46d | Python | agpl-3.0 | hbrunn/OpenUpgrade,jeasoft/odoo,FlorianLudwig/odoo,colinnewell/odoo,alhashash/odoo,jesramirez/odoo,lsinfo/odoo,rowemoore/odoo,sysadminmatmoz/OCB,JGarcia-Panach/odoo,dariemp/odoo,fgesora/odoo,takis/odoo,kirca/OpenUpgrade,tinkerthaler/odoo,Antiun/odoo,factorlibre/OCB,stonegithubs/odoo,matrixise/odoo,dllsf/odootest,Endika/odoo,alqfahad/odoo,chiragjogi/odoo,datenbetrieb/odoo,Adel-Magebinary/odoo,doomsterinc/odoo,markeTIC/OCB,mszewczy/odoo,hassoon3/odoo,ecosoft-odoo/odoo,tvtsoft/odoo8,thanhacun/odoo,idncom/odoo,hip-odoo/odoo,n0m4dz/odoo,wangjun/odoo,ingadhoc/odoo,frouty/odoo_oph,CatsAndDogsbvba/odoo,damdam-s/OpenUpgrade,makinacorpus/odoo,tangyiyong/odoo,dkubiak789/odoo,OSSESAC/odoopubarquiluz,Codefans-fan/odoo,oliverhr/odoo,aviciimaxwell/odoo,hubsaysnuaa/odoo,mmbtba/odoo,Kilhog/odoo,wangjun/odoo,fuhongliang/odoo,mlaitinen/odoo,jolevq/odoopub,ccomb/OpenUpgrade,vrenaville/ngo-addons-backport,goliveirab/odoo,bguillot/OpenUpgrade,xzYue/odoo,shaufi/odoo,massot/odoo,savoirfairelinux/OpenUpgrade,nitinitprof/odoo,fossoult/odoo,acshan/odoo,ClearCorp-dev/odoo,janocat/odoo,storm-computers/odoo,alqfahad/odoo,grap/OCB,kirca/OpenUpgrade,gorjuce/odoo,Kilhog/odoo,ApuliaSoftware/odoo,datenbetrieb/odoo,chiragjogi/odoo,leorochael/odoo,abstract-open-solutions/OCB,NeovaHealth/odoo,rahuldhote/odoo,collex100/odoo,Gitlab11/odoo,hanicker/odoo,Drooids/odoo,grap/OpenUpgrade,matrixise/odoo,lgscofield/odoo,feroda/odoo,mlaitinen/odoo,kittiu/odoo,joshuajan/odoo,damdam-s/OpenUpgrade,lightcn/odoo,bkirui/odoo,alexcuellar/odoo,incaser/odoo-odoo,dezynetechnologies/odoo,VitalPet/odoo,fuhongliang/odoo,incaser/odoo-odoo,savoirfairelinux/OpenUpgrade,havt/odoo,nuuuboo/odoo,cloud9UG/odoo,hoatle/odoo,guerrerocarlos/odoo,grap/OpenUpgrade,lightcn/odoo,luiseduardohdbackup/odoo,MarcosCommunity/odoo,omprakasha/odoo,agrista/odoo-saas,OpenUpgrade-dev/OpenUpgrade,bobisme/odoo,PongPi/isl-odoo,charbeljc/OCB,Endika/odoo,apanju/odoo,NeovaHealth/odoo,rubencabrera/odoo,tangyiyong/odoo,bwrsandman/OpenUpgrade,hifly/OpenUpgrade,Eric-Zhong/odoo,massot/odoo,OpenPymeMx/OCB,odoousers2014/odoo,zchking/odoo,jfpla/odoo,sysadminmatmoz/OCB,hifly/OpenUpgrade,datenbetrieb/odoo,kybriainfotech/iSocioCRM,omprakasha/odoo,kybriainfotech/iSocioCRM,nuuuboo/odoo,salaria/odoo,credativUK/OCB,OpusVL/odoo,hopeall/odoo,Noviat/odoo,hbrunn/OpenUpgrade,draugiskisprendimai/odoo,mlaitinen/odoo,lightcn/odoo,tinkerthaler/odoo,fossoult/odoo,doomsterinc/odoo,ramadhane/odoo,QianBIG/odoo,sergio-incaser/odoo,florentx/OpenUpgrade,mvaled/OpenUpgrade,ecosoft-odoo/odoo,sve-odoo/odoo,ubic135/odoo-design,ramitalat/odoo,ThinkOpen-Solutions/odoo,kybriainfotech/iSocioCRM,datenbetrieb/odoo,tvibliani/odoo,hmen89/odoo,Gitlab11/odoo,dgzurita/odoo,PongPi/isl-odoo,gsmartway/odoo,ramitalat/odoo,bakhtout/odoo-educ,VitalPet/odoo,florian-dacosta/OpenUpgrade,ehirt/odoo,elmerdpadilla/iv,salaria/odoo,rgeleta/odoo,kybriainfotech/iSocioCRM,chiragjogi/odoo,Endika/OpenUpgrade,alhashash/odoo,bguillot/OpenUpgrade,hifly/OpenUpgrade,doomsterinc/odoo,aviciimaxwell/odoo,leoliujie/odoo,mvaled/OpenUpgrade,sebalix/OpenUpgrade,wangjun/odoo,microcom/odoo,apanju/odoo,omprakasha/odoo,Adel-Magebinary/odoo,gavin-feng/odoo,dsfsdgsbngfggb/odoo,alqfahad/odoo,bwrsandman/OpenUpgrade,nexiles/odoo,Danisan/odoo-1,andreparames/odoo,christophlsa/odoo,bkirui/odoo,rowemoore/odoo,jfpla/odoo,fevxie/odoo,fgesora/odoo,stephen144/odoo,hanicker/odoo,Adel-Magebinary/odoo,joariasl/odoo,makinacorpus/odoo,vrenaville/ngo-addons-backport,VielSoft/odoo,ecosoft-odoo/odoo,alexcuellar/odoo,dariemp/odoo,alexcuellar/odoo,jpshort/odoo,glovebx/odoo,thanhacun/odoo,avoinsystems/odoo,papouso/odoo,jiangzhixiao/odoo,sebalix/OpenUpgrade,abenzbiria/clients_odoo,sinbazhou/odoo,mlaitinen/odoo,Endika/odoo,lgscofield/odoo,juanalfonsopr/odoo,leorochael/odoo,shingonoide/odoo,poljeff/odoo,javierTerry/odoo,sergio-incaser/odoo,oasiswork/odoo,thanhacun/odoo,bakhtout/odoo-educ,grap/OpenUpgrade,jiachenning/odoo,charbeljc/OCB,javierTerry/odoo,VitalPet/odoo,javierTerry/odoo,codekaki/odoo,srimai/odoo,dsfsdgsbngfggb/odoo,hbrunn/OpenUpgrade,Gitlab11/odoo,vrenaville/ngo-addons-backport,arthru/OpenUpgrade,vnsofthe/odoo,spadae22/odoo,fuselock/odoo,nuuuboo/odoo,savoirfairelinux/odoo,shivam1111/odoo,gsmartway/odoo,dgzurita/odoo,Ernesto99/odoo,florian-dacosta/OpenUpgrade,luistorresm/odoo,tvibliani/odoo,savoirfairelinux/odoo,abstract-open-solutions/OCB,janocat/odoo,ApuliaSoftware/odoo,jolevq/odoopub,luiseduardohdbackup/odoo,elmerdpadilla/iv,OSSESAC/odoopubarquiluz,hanicker/odoo,Codefans-fan/odoo,jusdng/odoo,rgeleta/odoo,sinbazhou/odoo,collex100/odoo,patmcb/odoo,tinkhaven-organization/odoo,hifly/OpenUpgrade,andreparames/odoo,Nick-OpusVL/odoo,BT-ojossen/odoo,highco-groupe/odoo,slevenhagen/odoo-npg,hoatle/odoo,hoatle/odoo,highco-groupe/odoo,optima-ict/odoo,provaleks/o8,bobisme/odoo,gsmartway/odoo,Nowheresly/odoo,syci/OCB,colinnewell/odoo,ujjwalwahi/odoo,laslabs/odoo,oliverhr/odoo,jiangzhixiao/odoo,lgscofield/odoo,Maspear/odoo,goliveirab/odoo,tvtsoft/odoo8,guewen/OpenUpgrade,credativUK/OCB,provaleks/o8,Nowheresly/odoo,naousse/odoo,doomsterinc/odoo,Bachaco-ve/odoo,sysadminmatmoz/OCB,Drooids/odoo,nhomar/odoo,sergio-incaser/odoo,hbrunn/OpenUpgrade,osvalr/odoo,dalegregory/odoo,windedge/odoo,abstract-open-solutions/OCB,vrenaville/ngo-addons-backport,jaxkodex/odoo,colinnewell/odoo,bealdav/OpenUpgrade,kittiu/odoo,bakhtout/odoo-educ,Antiun/odoo,Grirrane/odoo,sv-dev1/odoo,syci/OCB,savoirfairelinux/OpenUpgrade,sadleader/odoo,dkubiak789/odoo,0k/OpenUpgrade,synconics/odoo,gsmartway/odoo,fgesora/odoo,poljeff/odoo,fjbatresv/odoo,stonegithubs/odoo,factorlibre/OCB,guewen/OpenUpgrade,cysnake4713/odoo,makinacorpus/odoo,joariasl/odoo,steedos/odoo,glovebx/odoo,Ernesto99/odoo,sv-dev1/odoo,srsman/odoo,BT-ojossen/odoo,PongPi/isl-odoo,Nowheresly/odoo,grap/OCB,bakhtout/odoo-educ,bkirui/odoo,demon-ru/iml-crm,ygol/odoo,pedrobaeza/OpenUpgrade,x111ong/odoo,grap/OpenUpgrade,syci/OCB,camptocamp/ngo-addons-backport,fuhongliang/odoo,andreparames/odoo,Kilhog/odoo,jusdng/odoo,andreparames/odoo,rdeheele/odoo,credativUK/OCB,slevenhagen/odoo-npg,wangjun/odoo,brijeshkesariya/odoo,aviciimaxwell/odoo,x111ong/odoo,BT-rmartin/odoo,mvaled/OpenUpgrade,ojengwa/odoo,takis/odoo,Gitlab11/odoo,diagramsoftware/odoo,lsinfo/odoo,janocat/odoo,eino-makitalo/odoo,Noviat/odoo,rahuldhote/odoo,rowemoore/odoo,xujb/odoo,dkubiak789/odoo,bobisme/odoo,Maspear/odoo,OpusVL/odoo,SAM-IT-SA/odoo,nitinitprof/odoo,odooindia/odoo,draugiskisprendimai/odoo,janocat/odoo,addition-it-solutions/project-all,credativUK/OCB,naousse/odoo,tarzan0820/odoo,CopeX/odoo,ChanduERP/odoo,RafaelTorrealba/odoo,luistorresm/odoo,Nick-OpusVL/odoo,juanalfonsopr/odoo,pplatek/odoo,klunwebale/odoo,dfang/odoo,MarcosCommunity/odoo,synconics/odoo,acshan/odoo,srimai/odoo,thanhacun/odoo,guerrerocarlos/odoo,ojengwa/odoo,tvibliani/odoo,OpenUpgrade-dev/OpenUpgrade,shaufi10/odoo,luistorresm/odoo,erkrishna9/odoo,mlaitinen/odoo,NeovaHealth/odoo,aviciimaxwell/odoo,damdam-s/OpenUpgrade,ecosoft-odoo/odoo,OpusVL/odoo,csrocha/OpenUpgrade,tarzan0820/odoo,srsman/odoo,provaleks/o8,OpenUpgrade-dev/OpenUpgrade,dfang/odoo,apanju/odoo,JonathanStein/odoo,nexiles/odoo,jusdng/odoo,camptocamp/ngo-addons-backport,frouty/odoogoeen,tinkhaven-organization/odoo,CubicERP/odoo,nhomar/odoo,datenbetrieb/odoo,Antiun/odoo,CopeX/odoo,rubencabrera/odoo,pedrobaeza/OpenUpgrade,mustafat/odoo-1,Danisan/odoo-1,Codefans-fan/odoo,patmcb/odoo,sve-odoo/odoo,pedrobaeza/OpenUpgrade,AuyaJackie/odoo,dsfsdgsbngfggb/odoo,vnsofthe/odoo,dfang/odoo,odoousers2014/odoo,christophlsa/odoo,oliverhr/odoo,papouso/odoo,AuyaJackie/odoo,Drooids/odoo,ihsanudin/odoo,sv-dev1/odoo,Nick-OpusVL/odoo,srimai/odoo,kirca/OpenUpgrade,ThinkOpen-Solutions/odoo,blaggacao/OpenUpgrade,nexiles/odoo,jaxkodex/odoo,feroda/odoo,fjbatresv/odoo,AuyaJackie/odoo,Endika/OpenUpgrade,fossoult/odoo,gavin-feng/odoo,dalegregory/odoo,hip-odoo/odoo,Bachaco-ve/odoo,jfpla/odoo,papouso/odoo,xujb/odoo,alqfahad/odoo,luistorresm/odoo,colinnewell/odoo,alexteodor/odoo,Grirrane/odoo,frouty/odoogoeen,cedk/odoo,funkring/fdoo,Maspear/odoo,ehirt/odoo,virgree/odoo,jiangzhixiao/odoo,gorjuce/odoo,credativUK/OCB,juanalfonsopr/odoo,Drooids/odoo,collex100/odoo,Ichag/odoo,BT-fgarbely/odoo,hassoon3/odoo,waytai/odoo,oihane/odoo,CopeX/odoo,Ernesto99/odoo,stonegithubs/odoo,ovnicraft/odoo,n0m4dz/odoo,Nick-OpusVL/odoo,oihane/odoo,florentx/OpenUpgrade,abenzbiria/clients_odoo,florian-dacosta/OpenUpgrade,KontorConsulting/odoo,diagramsoftware/odoo,srimai/odoo,mustafat/odoo-1,numerigraphe/odoo,kybriainfotech/iSocioCRM,glovebx/odoo,jusdng/odoo,colinnewell/odoo,jpshort/odoo,dkubiak789/odoo,grap/OpenUpgrade,Nowheresly/odoo,ojengwa/odoo,cedk/odoo,ujjwalwahi/odoo,glovebx/odoo,fuhongliang/odoo,JGarcia-Panach/odoo,srsman/odoo,tangyiyong/odoo,Antiun/odoo,inspyration/odoo,jusdng/odoo,ApuliaSoftware/odoo,gavin-feng/odoo,cdrooom/odoo,shivam1111/odoo,dgzurita/odoo,colinnewell/odoo,florentx/OpenUpgrade,Grirrane/odoo,highco-groupe/odoo,naousse/odoo,Nick-OpusVL/odoo,nagyistoce/odoo-dev-odoo,zchking/odoo,bguillot/OpenUpgrade,JGarcia-Panach/odoo,bakhtout/odoo-educ,ramitalat/odoo,lightcn/odoo,oasiswork/odoo,tvibliani/odoo,jiangzhixiao/odoo,kifcaliph/odoo,NL66278/OCB,Ichag/odoo,nuuuboo/odoo,Ichag/odoo,hoatle/odoo,sebalix/OpenUpgrade,abdellatifkarroum/odoo,BT-ojossen/odoo,havt/odoo,ApuliaSoftware/odoo,cysnake4713/odoo,deKupini/erp,pplatek/odoo,jiangzhixiao/odoo,tarzan0820/odoo,0k/OpenUpgrade,cloud9UG/odoo,OpenPymeMx/OCB,hmen89/odoo,bguillot/OpenUpgrade,sysadminmatmoz/OCB,microcom/odoo,BT-astauder/odoo,tvtsoft/odoo8,oihane/odoo,sysadminmatmoz/OCB,jaxkodex/odoo,nagyistoce/odoo-dev-odoo,QianBIG/odoo,ehirt/odoo,KontorConsulting/odoo,dfang/odoo,bguillot/OpenUpgrade,provaleks/o8,spadae22/odoo,Danisan/odoo-1,ihsanudin/odoo,SAM-IT-SA/odoo,tinkerthaler/odoo,CatsAndDogsbvba/odoo,poljeff/odoo,oihane/odoo,bwrsandman/OpenUpgrade,OpenPymeMx/OCB,numerigraphe/odoo,codekaki/odoo,deKupini/erp,sinbazhou/odoo,SAM-IT-SA/odoo,oasiswork/odoo,SAM-IT-SA/odoo,savoirfairelinux/OpenUpgrade,naousse/odoo,guewen/OpenUpgrade,pedrobaeza/OpenUpgrade,incaser/odoo-odoo,naousse/odoo,steedos/odoo,massot/odoo,thanhacun/odoo,windedge/odoo,ovnicraft/odoo,acshan/odoo,windedge/odoo,deKupini/erp,rahuldhote/odoo,mszewczy/odoo,charbeljc/OCB,hanicker/odoo,Drooids/odoo,shaufi10/odoo,BT-ojossen/odoo,factorlibre/OCB,CatsAndDogsbvba/odoo,idncom/odoo,ShineFan/odoo,leoliujie/odoo,chiragjogi/odoo,cpyou/odoo,klunwebale/odoo,codekaki/odoo,alexcuellar/odoo,draugiskisprendimai/odoo,optima-ict/odoo,odoousers2014/odoo,BT-fgarbely/odoo,abenzbiria/clients_odoo,mkieszek/odoo,cdrooom/odoo,joariasl/odoo,provaleks/o8,Antiun/odoo,realsaiko/odoo,apocalypsebg/odoo,draugiskisprendimai/odoo,SAM-IT-SA/odoo,JCA-Developpement/Odoo,steedos/odoo,doomsterinc/odoo,fjbatresv/odoo,odooindia/odoo,BT-rmartin/odoo,VielSoft/odoo,aviciimaxwell/odoo,chiragjogi/odoo,srsman/odoo,rschnapka/odoo,tinkerthaler/odoo,ShineFan/odoo,AuyaJackie/odoo,leoliujie/odoo,oihane/odoo,fjbatresv/odoo,frouty/odoo_oph,markeTIC/OCB,incaser/odoo-odoo,hubsaysnuaa/odoo,cdrooom/odoo,goliveirab/odoo,draugiskisprendimai/odoo,lombritz/odoo,ujjwalwahi/odoo,florian-dacosta/OpenUpgrade,grap/OCB,ShineFan/odoo,syci/OCB,abstract-open-solutions/OCB,addition-it-solutions/project-all,ShineFan/odoo,BT-rmartin/odoo,ubic135/odoo-design,oliverhr/odoo,rdeheele/odoo,eino-makitalo/odoo,CatsAndDogsbvba/odoo,kittiu/odoo,luistorresm/odoo,alhashash/odoo,ccomb/OpenUpgrade,nitinitprof/odoo,rschnapka/odoo,demon-ru/iml-crm,apanju/GMIO_Odoo,OpusVL/odoo,lombritz/odoo,Gitlab11/odoo,jeasoft/odoo,VitalPet/odoo,jeasoft/odoo,luistorresm/odoo,Kilhog/odoo,florian-dacosta/OpenUpgrade,vnsofthe/odoo,OpenUpgrade/OpenUpgrade,bplancher/odoo,Bachaco-ve/odoo,mustafat/odoo-1,bguillot/OpenUpgrade,windedge/odoo,AuyaJackie/odoo,incaser/odoo-odoo,jiachenning/odoo,RafaelTorrealba/odoo,Grirrane/odoo,diagramsoftware/odoo,bobisme/odoo,dkubiak789/odoo,jaxkodex/odoo,patmcb/odoo,GauravSahu/odoo,GauravSahu/odoo,agrista/odoo-saas,apanju/odoo,goliveirab/odoo,CatsAndDogsbvba/odoo,MarcosCommunity/odoo,bwrsandman/OpenUpgrade,dariemp/odoo,thanhacun/odoo,guerrerocarlos/odoo,JonathanStein/odoo,syci/OCB,christophlsa/odoo,hoatle/odoo,nuuuboo/odoo,markeTIC/OCB,apanju/GMIO_Odoo,diagramsoftware/odoo,brijeshkesariya/odoo,0k/OpenUpgrade,gavin-feng/odoo,Eric-Zhong/odoo,luiseduardohdbackup/odoo,alhashash/odoo,slevenhagen/odoo-npg,matrixise/odoo,takis/odoo,bwrsandman/OpenUpgrade,synconics/odoo,gavin-feng/odoo,codekaki/odoo,idncom/odoo,Eric-Zhong/odoo,dgzurita/odoo,ChanduERP/odoo,kirca/OpenUpgrade,hoatle/odoo,lsinfo/odoo,SerpentCS/odoo,doomsterinc/odoo,srsman/odoo,odooindia/odoo,Ichag/odoo,GauravSahu/odoo,highco-groupe/odoo,fjbatresv/odoo,addition-it-solutions/project-all,ChanduERP/odoo,slevenhagen/odoo-npg,OpenUpgrade/OpenUpgrade,nuncjo/odoo,fevxie/odoo,makinacorpus/odoo,simongoffin/website_version,jeasoft/odoo,camptocamp/ngo-addons-backport,frouty/odoogoeen,0k/odoo,lombritz/odoo,Maspear/odoo,pedrobaeza/odoo,TRESCLOUD/odoopub,nexiles/odoo,OSSESAC/odoopubarquiluz,klunwebale/odoo,ccomb/OpenUpgrade,goliveirab/odoo,javierTerry/odoo,ccomb/OpenUpgrade,nhomar/odoo,QianBIG/odoo,collex100/odoo,nitinitprof/odoo,rdeheele/odoo,codekaki/odoo,apocalypsebg/odoo,waytai/odoo,funkring/fdoo,sysadminmatmoz/OCB,gdgellatly/OCB1,erkrishna9/odoo,ojengwa/odoo,javierTerry/odoo,Gitlab11/odoo,demon-ru/iml-crm,jesramirez/odoo,nhomar/odoo-mirror,ingadhoc/odoo,fjbatresv/odoo,gsmartway/odoo,massot/odoo,CopeX/odoo,matrixise/odoo,abstract-open-solutions/OCB,shingonoide/odoo,tvtsoft/odoo8,rschnapka/odoo,havt/odoo,ovnicraft/odoo,bobisme/odoo,prospwro/odoo,OpenPymeMx/OCB,massot/odoo,grap/OCB,BT-astauder/odoo,Elico-Corp/odoo_OCB,prospwro/odoo,laslabs/odoo,CopeX/odoo,prospwro/odoo,mvaled/OpenUpgrade,osvalr/odoo,ThinkOpen-Solutions/odoo,apanju/GMIO_Odoo,xzYue/odoo,rschnapka/odoo,BT-astauder/odoo,oliverhr/odoo,shaufi10/odoo,JGarcia-Panach/odoo,hopeall/odoo,sergio-incaser/odoo,VitalPet/odoo,spadae22/odoo,csrocha/OpenUpgrade,christophlsa/odoo,PongPi/isl-odoo,spadae22/odoo,oasiswork/odoo,tvibliani/odoo,shingonoide/odoo,BT-ojossen/odoo,guerrerocarlos/odoo,jesramirez/odoo,Antiun/odoo,andreparames/odoo,SAM-IT-SA/odoo,NeovaHealth/odoo,guerrerocarlos/odoo,slevenhagen/odoo-npg,brijeshkesariya/odoo,sv-dev1/odoo,ingadhoc/odoo,mvaled/OpenUpgrade,jpshort/odoo,slevenhagen/odoo,lombritz/odoo,credativUK/OCB,jfpla/odoo,OpenUpgrade-dev/OpenUpgrade,takis/odoo,RafaelTorrealba/odoo,pedrobaeza/OpenUpgrade,fjbatresv/odoo,ThinkOpen-Solutions/odoo,tangyiyong/odoo,stephen144/odoo,srimai/odoo,shivam1111/odoo,gsmartway/odoo,lsinfo/odoo,zchking/odoo,florentx/OpenUpgrade,simongoffin/website_version,odootr/odoo,guewen/OpenUpgrade,x111ong/odoo,xzYue/odoo,dllsf/odootest,alexteodor/odoo,Danisan/odoo-1,nagyistoce/odoo-dev-odoo,bplancher/odoo,BT-ojossen/odoo,bkirui/odoo,alexcuellar/odoo,gorjuce/odoo,storm-computers/odoo,hassoon3/odoo,ygol/odoo,Eric-Zhong/odoo,simongoffin/website_version,takis/odoo,mmbtba/odoo,jolevq/odoopub,0k/odoo,pedrobaeza/odoo,odootr/odoo,OpenUpgrade-dev/OpenUpgrade,jiachenning/odoo,srimai/odoo,fevxie/odoo,lombritz/odoo,blaggacao/OpenUpgrade,christophlsa/odoo,brijeshkesariya/odoo,jpshort/odoo,jeasoft/odoo,bobisme/odoo,salaria/odoo,alexcuellar/odoo,simongoffin/website_version,oihane/odoo,bplancher/odoo,CubicERP/odoo,fdvarela/odoo8,hip-odoo/odoo,credativUK/OCB,OpenUpgrade-dev/OpenUpgrade,kifcaliph/odoo,ramitalat/odoo,kifcaliph/odoo,juanalfonsopr/odoo,rschnapka/odoo,deKupini/erp,ramadhane/odoo,dsfsdgsbngfggb/odoo,CopeX/odoo,ygol/odoo,podemos-info/odoo,acshan/odoo,BT-fgarbely/odoo,stephen144/odoo,makinacorpus/odoo,numerigraphe/odoo,mkieszek/odoo,n0m4dz/odoo,fuselock/odoo,shaufi10/odoo,nuuuboo/odoo,dalegregory/odoo,x111ong/odoo,florian-dacosta/OpenUpgrade,Ernesto99/odoo,nexiles/odoo,ehirt/odoo,acshan/odoo,gdgellatly/OCB1,0k/OpenUpgrade,storm-computers/odoo,bguillot/OpenUpgrade,fgesora/odoo,GauravSahu/odoo,Elico-Corp/odoo_OCB,kifcaliph/odoo,FlorianLudwig/odoo,guerrerocarlos/odoo,ihsanudin/odoo,dariemp/odoo,Adel-Magebinary/odoo,frouty/odoogoeen,frouty/odoogoeen,rgeleta/odoo,fgesora/odoo,funkring/fdoo,ecosoft-odoo/odoo,sadleader/odoo,elmerdpadilla/iv,fevxie/odoo,naousse/odoo,simongoffin/website_version,Ichag/odoo,brijeshkesariya/odoo,lombritz/odoo,frouty/odoo_oph,vrenaville/ngo-addons-backport,n0m4dz/odoo,realsaiko/odoo,realsaiko/odoo,damdam-s/OpenUpgrade,incaser/odoo-odoo,bwrsandman/OpenUpgrade,chiragjogi/odoo,provaleks/o8,idncom/odoo,mmbtba/odoo,odootr/odoo,tarzan0820/odoo,leoliujie/odoo,gvb/odoo,ingadhoc/odoo,pedrobaeza/odoo,osvalr/odoo,lgscofield/odoo,hanicker/odoo,apanju/odoo,sv-dev1/odoo,grap/OCB,nhomar/odoo-mirror,jolevq/odoopub,virgree/odoo,hbrunn/OpenUpgrade,collex100/odoo,Ernesto99/odoo,podemos-info/odoo,abdellatifkarroum/odoo,kittiu/odoo,dsfsdgsbngfggb/odoo,aviciimaxwell/odoo,xujb/odoo,odoo-turkiye/odoo,kybriainfotech/iSocioCRM,apanju/GMIO_Odoo,xzYue/odoo,hmen89/odoo,gdgellatly/OCB1,cedk/odoo,poljeff/odoo,lombritz/odoo,omprakasha/odoo,feroda/odoo,TRESCLOUD/odoopub,andreparames/odoo,fuselock/odoo,funkring/fdoo,minhtuancn/odoo,gorjuce/odoo,hopeall/odoo,doomsterinc/odoo,brijeshkesariya/odoo,pplatek/odoo,mszewczy/odoo,MarcosCommunity/odoo,factorlibre/OCB,nitinitprof/odoo,oasiswork/odoo,alexteodor/odoo,Bachaco-ve/odoo,dgzurita/odoo,nhomar/odoo-mirror,zchking/odoo,numerigraphe/odoo,papouso/odoo,havt/odoo,camptocamp/ngo-addons-backport,hubsaysnuaa/odoo,dllsf/odootest,ojengwa/odoo,shingonoide/odoo,cedk/odoo,rowemoore/odoo,dalegregory/odoo,nuncjo/odoo,markeTIC/OCB,stonegithubs/odoo,nuncjo/odoo,abdellatifkarroum/odoo,idncom/odoo,cedk/odoo,kittiu/odoo,erkrishna9/odoo,bealdav/OpenUpgrade,0k/OpenUpgrade,sadleader/odoo,joshuajan/odoo,ujjwalwahi/odoo,codekaki/odoo,hopeall/odoo,fossoult/odoo,tangyiyong/odoo,alhashash/odoo,wangjun/odoo,xzYue/odoo,shivam1111/odoo,tvtsoft/odoo8,guewen/OpenUpgrade,PongPi/isl-odoo,GauravSahu/odoo,dezynetechnologies/odoo,jusdng/odoo,Noviat/odoo,waytai/odoo,ramadhane/odoo,bakhtout/odoo-educ,gavin-feng/odoo,pplatek/odoo,leoliujie/odoo,salaria/odoo,ClearCorp-dev/odoo,dkubiak789/odoo,Endika/OpenUpgrade,VielSoft/odoo,Kilhog/odoo,nuncjo/odoo,mmbtba/odoo,virgree/odoo,charbeljc/OCB,ygol/odoo,jeasoft/odoo,srsman/odoo,jaxkodex/odoo,odootr/odoo,microcom/odoo,havt/odoo,SerpentCS/odoo,xujb/odoo,slevenhagen/odoo,rubencabrera/odoo,waytai/odoo,Daniel-CA/odoo,bkirui/odoo,numerigraphe/odoo,draugiskisprendimai/odoo,slevenhagen/odoo,agrista/odoo-saas,shingonoide/odoo,dalegregory/odoo,leorochael/odoo,Endika/odoo,Drooids/odoo,hopeall/odoo,laslabs/odoo,joariasl/odoo,MarcosCommunity/odoo,jesramirez/odoo,gorjuce/odoo,mmbtba/odoo,Maspear/odoo,addition-it-solutions/project-all,cpyou/odoo,Noviat/odoo,makinacorpus/odoo,0k/odoo,spadae22/odoo,sve-odoo/odoo,cpyou/odoo,Ichag/odoo,frouty/odoogoeen,Nick-OpusVL/odoo,storm-computers/odoo,abdellatifkarroum/odoo,alexteodor/odoo,ramitalat/odoo,JonathanStein/odoo,sinbazhou/odoo,stonegithubs/odoo,pedrobaeza/OpenUpgrade,MarcosCommunity/odoo,Endika/odoo,JGarcia-Panach/odoo,nuncjo/odoo,RafaelTorrealba/odoo,mszewczy/odoo,vnsofthe/odoo,janocat/odoo,dgzurita/odoo,cysnake4713/odoo,bkirui/odoo,hubsaysnuaa/odoo,minhtuancn/odoo,Daniel-CA/odoo,abdellatifkarroum/odoo,wangjun/odoo,Maspear/odoo,mvaled/OpenUpgrade,sinbazhou/odoo,nagyistoce/odoo-dev-odoo,CopeX/odoo,Bachaco-ve/odoo,odoo-turkiye/odoo,gvb/odoo,frouty/odoogoeen,kirca/OpenUpgrade,hassoon3/odoo,KontorConsulting/odoo,collex100/odoo,optima-ict/odoo,GauravSahu/odoo,nitinitprof/odoo,laslabs/odoo,hassoon3/odoo,camptocamp/ngo-addons-backport,guewen/OpenUpgrade,NeovaHealth/odoo,cysnake4713/odoo,Drooids/odoo,diagramsoftware/odoo,poljeff/odoo,steedos/odoo,vrenaville/ngo-addons-backport,csrocha/OpenUpgrade,nhomar/odoo,nhomar/odoo-mirror,KontorConsulting/odoo,mkieszek/odoo,odootr/odoo,MarcosCommunity/odoo,prospwro/odoo,leorochael/odoo,gdgellatly/OCB1,ramadhane/odoo,funkring/fdoo,sinbazhou/odoo,draugiskisprendimai/odoo,tarzan0820/odoo,dariemp/odoo,hopeall/odoo,lgscofield/odoo,nuuuboo/odoo,JCA-Developpement/Odoo,ChanduERP/odoo,BT-fgarbely/odoo,dfang/odoo,csrocha/OpenUpgrade,avoinsystems/odoo,grap/OCB,sve-odoo/odoo,sergio-incaser/odoo,fuhongliang/odoo,Noviat/odoo,Noviat/odoo,Danisan/odoo-1,xujb/odoo,jaxkodex/odoo,bealdav/OpenUpgrade,lsinfo/odoo,jpshort/odoo,shingonoide/odoo,hip-odoo/odoo,abdellatifkarroum/odoo,Maspear/odoo,waytai/odoo,grap/OpenUpgrade,tinkerthaler/odoo,hubsaysnuaa/odoo,dsfsdgsbngfggb/odoo,tinkhaven-organization/odoo,x111ong/odoo,fevxie/odoo,deKupini/erp,fuhongliang/odoo,Bachaco-ve/odoo,synconics/odoo,SerpentCS/odoo,rschnapka/odoo,OSSESAC/odoopubarquiluz,mvaled/OpenUpgrade,demon-ru/iml-crm,x111ong/odoo,syci/OCB,dezynetechnologies/odoo,rahuldhote/odoo,blaggacao/OpenUpgrade,Gitlab11/odoo,OpenPymeMx/OCB,CubicERP/odoo,shivam1111/odoo,dllsf/odootest,Kilhog/odoo,0k/OpenUpgrade,klunwebale/odoo,kybriainfotech/iSocioCRM,Daniel-CA/odoo,abdellatifkarroum/odoo,oasiswork/odoo,BT-fgarbely/odoo,shaufi10/odoo,osvalr/odoo,ehirt/odoo,hubsaysnuaa/odoo,SerpentCS/odoo,BT-rmartin/odoo,incaser/odoo-odoo,gvb/odoo,CubicERP/odoo,virgree/odoo,thanhacun/odoo,vnsofthe/odoo,n0m4dz/odoo,jiachenning/odoo,nuncjo/odoo,virgree/odoo,blaggacao/OpenUpgrade,srimai/odoo,poljeff/odoo,prospwro/odoo,ecosoft-odoo/odoo,funkring/fdoo,arthru/OpenUpgrade,dezynetechnologies/odoo,rahuldhote/odoo,xzYue/odoo,rgeleta/odoo,klunwebale/odoo,savoirfairelinux/odoo,sinbazhou/odoo,joshuajan/odoo,kittiu/odoo,Endika/OpenUpgrade,juanalfonsopr/odoo,Adel-Magebinary/odoo,sv-dev1/odoo,charbeljc/OCB,ojengwa/odoo,fevxie/odoo,minhtuancn/odoo,florentx/OpenUpgrade,windedge/odoo,vrenaville/ngo-addons-backport,Ernesto99/odoo,collex100/odoo,shaufi10/odoo,frouty/odoogoeen,KontorConsulting/odoo,0k/odoo,hubsaysnuaa/odoo,rubencabrera/odoo,cdrooom/odoo,TRESCLOUD/odoopub,klunwebale/odoo,gvb/odoo,fuselock/odoo,jusdng/odoo,bealdav/OpenUpgrade,fuhongliang/odoo,ChanduERP/odoo,salaria/odoo,ChanduERP/odoo,CatsAndDogsbvba/odoo,charbeljc/OCB,OpenUpgrade/OpenUpgrade,papouso/odoo,VielSoft/odoo,slevenhagen/odoo,FlorianLudwig/odoo,Endika/odoo,omprakasha/odoo,bplancher/odoo,OpenUpgrade/OpenUpgrade,dezynetechnologies/odoo,tangyiyong/odoo,shaufi/odoo,apocalypsebg/odoo,mkieszek/odoo,steedos/odoo,ramitalat/odoo,arthru/OpenUpgrade,ccomb/OpenUpgrade,slevenhagen/odoo,havt/odoo,tinkhaven-organization/odoo,podemos-info/odoo,luiseduardohdbackup/odoo,numerigraphe/odoo,damdam-s/OpenUpgrade,Codefans-fan/odoo,FlorianLudwig/odoo,bkirui/odoo,ygol/odoo,CatsAndDogsbvba/odoo,nexiles/odoo,dariemp/odoo,inspyration/odoo,odooindia/odoo,csrocha/OpenUpgrade,idncom/odoo,hifly/OpenUpgrade,patmcb/odoo,funkring/fdoo,odootr/odoo,naousse/odoo,rschnapka/odoo,highco-groupe/odoo,dariemp/odoo,Daniel-CA/odoo,Codefans-fan/odoo,pedrobaeza/OpenUpgrade,gdgellatly/OCB1,datenbetrieb/odoo,camptocamp/ngo-addons-backport,RafaelTorrealba/odoo,ShineFan/odoo,FlorianLudwig/odoo,ubic135/odoo-design,mszewczy/odoo,camptocamp/ngo-addons-backport,prospwro/odoo,frouty/odoo_oph,hanicker/odoo,ojengwa/odoo,dalegregory/odoo,lgscofield/odoo,slevenhagen/odoo-npg,joshuajan/odoo,Endika/OpenUpgrade,gdgellatly/OCB1,fevxie/odoo,osvalr/odoo,hmen89/odoo,windedge/odoo,leorochael/odoo,CubicERP/odoo,rowemoore/odoo,JCA-Developpement/Odoo,Bachaco-ve/odoo,feroda/odoo,damdam-s/OpenUpgrade,nhomar/odoo-mirror,podemos-info/odoo,dalegregory/odoo,leorochael/odoo,ThinkOpen-Solutions/odoo,sadleader/odoo,javierTerry/odoo,apanju/GMIO_Odoo,cloud9UG/odoo,realsaiko/odoo,jpshort/odoo,ecosoft-odoo/odoo,Elico-Corp/odoo_OCB,erkrishna9/odoo,abenzbiria/clients_odoo,Danisan/odoo-1,Endika/OpenUpgrade,jeasoft/odoo,leorochael/odoo,savoirfairelinux/odoo,cloud9UG/odoo,zchking/odoo,acshan/odoo,elmerdpadilla/iv,gorjuce/odoo,arthru/OpenUpgrade,ThinkOpen-Solutions/odoo,numerigraphe/odoo,dsfsdgsbngfggb/odoo,JonathanStein/odoo,optima-ict/odoo,cpyou/odoo,FlorianLudwig/odoo,nhomar/odoo,shivam1111/odoo,rschnapka/odoo,salaria/odoo,dezynetechnologies/odoo,rubencabrera/odoo,javierTerry/odoo,savoirfairelinux/OpenUpgrade,odooindia/odoo,eino-makitalo/odoo,Codefans-fan/odoo,steedos/odoo,spadae22/odoo,luiseduardohdbackup/odoo,SerpentCS/odoo,sergio-incaser/odoo,odoo-turkiye/odoo,shaufi/odoo,agrista/odoo-saas,Noviat/odoo,TRESCLOUD/odoopub,ApuliaSoftware/odoo,ovnicraft/odoo,savoirfairelinux/odoo,makinacorpus/odoo,tvibliani/odoo,tinkhaven-organization/odoo,diagramsoftware/odoo,Grirrane/odoo,sebalix/OpenUpgrade,spadae22/odoo,ovnicraft/odoo,Danisan/odoo-1,srsman/odoo,pedrobaeza/odoo,cpyou/odoo,inspyration/odoo,OSSESAC/odoopubarquiluz,elmerdpadilla/iv,patmcb/odoo,mustafat/odoo-1,vnsofthe/odoo,slevenhagen/odoo,QianBIG/odoo,KontorConsulting/odoo,oasiswork/odoo,0k/odoo,hip-odoo/odoo,Nick-OpusVL/odoo,joariasl/odoo,optima-ict/odoo,vnsofthe/odoo,ygol/odoo,mmbtba/odoo,tinkerthaler/odoo,factorlibre/OCB,alqfahad/odoo,pplatek/odoo,JGarcia-Panach/odoo,lightcn/odoo,joariasl/odoo,addition-it-solutions/project-all,waytai/odoo,glovebx/odoo,pedrobaeza/odoo,virgree/odoo,tinkhaven-organization/odoo,QianBIG/odoo,Elico-Corp/odoo_OCB,laslabs/odoo,acshan/odoo,tvibliani/odoo,minhtuancn/odoo,mlaitinen/odoo,SerpentCS/odoo,gavin-feng/odoo,savoirfairelinux/OpenUpgrade,frouty/odoo_oph,nexiles/odoo,cloud9UG/odoo,ingadhoc/odoo,hopeall/odoo,NL66278/OCB,fdvarela/odoo8,shaufi/odoo,apocalypsebg/odoo,jesramirez/odoo,Eric-Zhong/odoo,jolevq/odoopub,ClearCorp-dev/odoo,JCA-Developpement/Odoo,MarcosCommunity/odoo,Adel-Magebinary/odoo,dgzurita/odoo,odoo-turkiye/odoo,podemos-info/odoo,VielSoft/odoo,fdvarela/odoo8,leoliujie/odoo,steedos/odoo,ihsanudin/odoo,alexcuellar/odoo,Ichag/odoo,Elico-Corp/odoo_OCB,odoo-turkiye/odoo,factorlibre/OCB,dfang/odoo,avoinsystems/odoo,bobisme/odoo,synconics/odoo,lightcn/odoo,OpenUpgrade/OpenUpgrade,kirca/OpenUpgrade,microcom/odoo,FlorianLudwig/odoo,odoousers2014/odoo,nhomar/odoo,hbrunn/OpenUpgrade,BT-fgarbely/odoo,podemos-info/odoo,ovnicraft/odoo,NL66278/OCB,waytai/odoo,sebalix/OpenUpgrade,ThinkOpen-Solutions/odoo,havt/odoo,csrocha/OpenUpgrade,sadleader/odoo,rahuldhote/odoo,joshuajan/odoo,lightcn/odoo,patmcb/odoo,ccomb/OpenUpgrade,slevenhagen/odoo,rubencabrera/odoo,bakhtout/odoo-educ,apanju/GMIO_Odoo,credativUK/OCB,BT-astauder/odoo,ramadhane/odoo,apanju/GMIO_Odoo,PongPi/isl-odoo,joshuajan/odoo,NeovaHealth/odoo,papouso/odoo,grap/OpenUpgrade,gsmartway/odoo,stephen144/odoo,codekaki/odoo,GauravSahu/odoo,kirca/OpenUpgrade,stephen144/odoo,JonathanStein/odoo,VitalPet/odoo,kittiu/odoo,oliverhr/odoo,idncom/odoo,juanalfonsopr/odoo,Antiun/odoo,microcom/odoo,joariasl/odoo,QianBIG/odoo,feroda/odoo,BT-astauder/odoo,wangjun/odoo,rubencabrera/odoo,hip-odoo/odoo,VitalPet/odoo,papouso/odoo,fuselock/odoo,addition-it-solutions/project-all,inspyration/odoo,brijeshkesariya/odoo,apanju/odoo,synconics/odoo,jaxkodex/odoo,gvb/odoo,abenzbiria/clients_odoo,rdeheele/odoo,lgscofield/odoo,avoinsystems/odoo,odoo-turkiye/odoo,blaggacao/OpenUpgrade,grap/OCB,demon-ru/iml-crm,ramadhane/odoo,savoirfairelinux/odoo,charbeljc/OCB,rdeheele/odoo,bealdav/OpenUpgrade,mustafat/odoo-1,luistorresm/odoo,hanicker/odoo,hifly/OpenUpgrade,ujjwalwahi/odoo,OpenPymeMx/OCB,rowemoore/odoo,BT-rmartin/odoo,agrista/odoo-saas,eino-makitalo/odoo,ClearCorp-dev/odoo,sv-dev1/odoo,guerrerocarlos/odoo,bwrsandman/OpenUpgrade,alqfahad/odoo,markeTIC/OCB,shaufi/odoo,fdvarela/odoo8,minhtuancn/odoo,provaleks/o8,hifly/OpenUpgrade,arthru/OpenUpgrade,luiseduardohdbackup/odoo,BT-rmartin/odoo,fgesora/odoo,markeTIC/OCB,avoinsystems/odoo,cloud9UG/odoo,Kilhog/odoo,alqfahad/odoo,aviciimaxwell/odoo,CubicERP/odoo,minhtuancn/odoo,feroda/odoo,damdam-s/OpenUpgrade,bealdav/OpenUpgrade,virgree/odoo,BT-fgarbely/odoo,ClearCorp-dev/odoo,oihane/odoo,Nowheresly/odoo,abstract-open-solutions/OCB,camptocamp/ngo-addons-backport,BT-rmartin/odoo,storm-computers/odoo,odoo-turkiye/odoo,gvb/odoo,NeovaHealth/odoo,PongPi/isl-odoo,ehirt/odoo,odootr/odoo,tvtsoft/odoo8,apocalypsebg/odoo,tangyiyong/odoo,mszewczy/odoo,vrenaville/ngo-addons-backport,windedge/odoo,omprakasha/odoo,diagramsoftware/odoo,Codefans-fan/odoo,sebalix/OpenUpgrade,Adel-Magebinary/odoo,lsinfo/odoo,ovnicraft/odoo,glovebx/odoo,pplatek/odoo,mmbtba/odoo,ubic135/odoo-design,mlaitinen/odoo,mustafat/odoo-1,avoinsystems/odoo,fossoult/odoo,ubic135/odoo-design,JGarcia-Panach/odoo,Daniel-CA/odoo,n0m4dz/odoo,colinnewell/odoo,leoliujie/odoo,ujjwalwahi/odoo,AuyaJackie/odoo,jfpla/odoo,janocat/odoo,goliveirab/odoo,markeTIC/OCB,osvalr/odoo,chiragjogi/odoo,ihsanudin/odoo,shaufi/odoo,erkrishna9/odoo,ingadhoc/odoo,csrocha/OpenUpgrade,xzYue/odoo,jfpla/odoo,feroda/odoo,andreparames/odoo,eino-makitalo/odoo,KontorConsulting/odoo,nagyistoce/odoo-dev-odoo,x111ong/odoo,Endika/OpenUpgrade,OSSESAC/odoopubarquiluz,ihsanudin/odoo,dllsf/odootest,mkieszek/odoo,JCA-Developpement/Odoo,Nowheresly/odoo,OpenPymeMx/OCB,VielSoft/odoo,guewen/OpenUpgrade,matrixise/odoo,ShineFan/odoo,NL66278/OCB,JonathanStein/odoo,JonathanStein/odoo,shivam1111/odoo,ujjwalwahi/odoo,gorjuce/odoo,podemos-info/odoo,cysnake4713/odoo,xujb/odoo,jiangzhixiao/odoo,cedk/odoo,n0m4dz/odoo,omprakasha/odoo,sve-odoo/odoo,shaufi10/odoo,tinkerthaler/odoo,christophlsa/odoo,Nowheresly/odoo,christophlsa/odoo,ccomb/OpenUpgrade,rgeleta/odoo,mszewczy/odoo,odoousers2014/odoo,codekaki/odoo,Endika/odoo,laslabs/odoo,OpenUpgrade/OpenUpgrade,ihsanudin/odoo,ygol/odoo,salaria/odoo,SAM-IT-SA/odoo,takis/odoo,shaufi/odoo,frouty/odoo_oph,apanju/odoo,luiseduardohdbackup/odoo,rahuldhote/odoo,sebalix/OpenUpgrade,lsinfo/odoo,florentx/OpenUpgrade,jiachenning/odoo,hmen89/odoo,OpenUpgrade/OpenUpgrade,blaggacao/OpenUpgrade,tinkhaven-organization/odoo,avoinsystems/odoo,grap/OCB,VitalPet/odoo,CubicERP/odoo,cedk/odoo,osvalr/odoo,BT-ojossen/odoo,bplancher/odoo,factorlibre/OCB,xujb/odoo,juanalfonsopr/odoo,synconics/odoo,datenbetrieb/odoo,dkubiak789/odoo,ramadhane/odoo,fuselock/odoo,alhashash/odoo,takis/odoo,glovebx/odoo,jiachenning/odoo,kifcaliph/odoo,hassoon3/odoo,optima-ict/odoo,realsaiko/odoo,poljeff/odoo,zchking/odoo,jfpla/odoo,microcom/odoo,Grirrane/odoo,nagyistoce/odoo-dev-odoo,jpshort/odoo,shingonoide/odoo,stonegithubs/odoo,tarzan0820/odoo,patmcb/odoo,nuncjo/odoo,ApuliaSoftware/odoo,minhtuancn/odoo,ingadhoc/odoo,bplancher/odoo,nitinitprof/odoo,oliverhr/odoo,pplatek/odoo,SerpentCS/odoo,ehirt/odoo,sysadminmatmoz/OCB,apocalypsebg/odoo,abstract-open-solutions/OCB,Daniel-CA/odoo,apocalypsebg/odoo,jiangzhixiao/odoo,fgesora/odoo,Daniel-CA/odoo,stonegithubs/odoo,blaggacao/OpenUpgrade,klunwebale/odoo,fuselock/odoo,slevenhagen/odoo-npg,storm-computers/odoo,alexteodor/odoo,gdgellatly/OCB1,zchking/odoo,fossoult/odoo,jeasoft/odoo,odoousers2014/odoo,AuyaJackie/odoo,fossoult/odoo,rowemoore/odoo,eino-makitalo/odoo,rgeleta/odoo,gdgellatly/OCB1,dezynetechnologies/odoo,VielSoft/odoo,NL66278/OCB,Elico-Corp/odoo_OCB,arthru/OpenUpgrade,fdvarela/odoo8,janocat/odoo,Eric-Zhong/odoo,nagyistoce/odoo-dev-odoo,RafaelTorrealba/odoo,mustafat/odoo-1,goliveirab/odoo,pedrobaeza/odoo,hoatle/odoo,cloud9UG/odoo,stephen144/odoo,RafaelTorrealba/odoo,ShineFan/odoo,prospwro/odoo,TRESCLOUD/odoopub,Eric-Zhong/odoo,gvb/odoo,ChanduERP/odoo,tarzan0820/odoo,mkieszek/odoo,ApuliaSoftware/odoo,rgeleta/odoo,eino-makitalo/odoo,OpenPymeMx/OCB,Ernesto99/odoo | ---
+++
@@ -25,7 +25,7 @@
Print product labels with barcodes.
""",
"update_xml" : ["product_data.xml","product_report.xml",
- "product_view.xml", "pricelist_view.xml"],
+ "product_view.xml", "pricelist_view.xml","product_security.xml"],
"active": False,
"installable": True
} |
a3ee55cf4d9182247dcc7a42b0336c467dce9e3e | linter.py | linter.py | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}: {severity}: {message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+'
r'(?P<message>.+)'
)
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
on_stderr = None # handle stderr via split_match
tempfile_suffix = '-'
defaults = {
'selector': 'source.c, source.c++',
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
def split_match(self, match):
"""
Return the components of the match.
We override this because included header files can cause linter errors,
and we only want errors from the linted file.
"""
if match:
if match.group('file') != self.filename:
return None
return super().split_match(match)
| from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}:{column}:{severity}:{id}:{message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)'
r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):'
r'(?P<code>\w+):(?P<message>.+)'
)
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
on_stderr = None # handle stderr via split_match
tempfile_suffix = '-'
defaults = {
'selector': 'source.c, source.c++',
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
def split_match(self, match):
"""
Return the components of the match.
We override this because included header files can cause linter errors,
and we only want errors from the linted file.
"""
if match:
if match.group('file') != self.filename:
return None
return super().split_match(match)
| Add cppcheck issue id as code field | Add cppcheck issue id as code field | Python | mit | SublimeLinter/SublimeLinter-cppcheck | ---
+++
@@ -4,16 +4,16 @@
class Cppcheck(Linter):
cmd = (
'cppcheck',
- '--template={file}:{line}: {severity}: {message}',
+ '--template={file}:{line}:{column}:{severity}:{id}:{message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
- r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
- r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+'
- r'(?P<message>.+)'
+ r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)'
+ r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):'
+ r'(?P<code>\w+):(?P<message>.+)'
)
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
on_stderr = None # handle stderr via split_match |
336fbbd82a09469a7ac7d0eb850daa6a55f42669 | ctypescrypto/__init__.py | ctypescrypto/__init__.py | """
Interface to some libcrypto functions
"""
from ctypes import CDLL, c_char_p
def config(filename=None):
"""
Loads OpenSSL Config file. If none are specified, loads default
(compiled in) one
"""
libcrypto.OPENSSL_config(filename)
__all__ = ['config']
libcrypto = CDLL("libcrypto.so.1.0.0")
libcrypto.OPENSSL_config.argtypes = (c_char_p, )
libcrypto.OPENSSL_add_all_algorithms_conf()
| """
Interface to some libcrypto functions
"""
from ctypes import CDLL, c_char_p
from ctypes.util import find_library
import sys
def config(filename=None):
"""
Loads OpenSSL Config file. If none are specified, loads default
(compiled in) one
"""
libcrypto.OPENSSL_config(filename)
__all__ = ['config']
if sys.platform.startswith('win'):
__libname__ = find_library('libeay32')
else:
__libname__ = find_library('crypto')
if __libname__ is None:
raise OSError("Cannot find OpenSSL crypto library")
libcrypto = CDLL(__libname__)
libcrypto.OPENSSL_config.argtypes = (c_char_p, )
libcrypto.OPENSSL_add_all_algorithms_conf()
| Use find_library to search for openssl libs | Use find_library to search for openssl libs
| Python | mit | vbwagner/ctypescrypto | ---
+++
@@ -5,6 +5,8 @@
from ctypes import CDLL, c_char_p
+from ctypes.util import find_library
+import sys
def config(filename=None):
"""
@@ -15,6 +17,14 @@
__all__ = ['config']
-libcrypto = CDLL("libcrypto.so.1.0.0")
+if sys.platform.startswith('win'):
+ __libname__ = find_library('libeay32')
+else:
+ __libname__ = find_library('crypto')
+
+if __libname__ is None:
+ raise OSError("Cannot find OpenSSL crypto library")
+
+libcrypto = CDLL(__libname__)
libcrypto.OPENSSL_config.argtypes = (c_char_p, )
libcrypto.OPENSSL_add_all_algorithms_conf() |
024ddea9e3dc5ab2702b08c860e6df8702b3e5e8 | captain_hook/endpoint.py | captain_hook/endpoint.py | from __future__ import absolute_import
from os.path import abspath
from os.path import dirname
from flask import Flask, request
import yaml
import utils.config
from services import find_services
from comms import find_and_load_comms
CONFIG_FOLDER = dirname(dirname(abspath(__file__)))
application = Flask(__name__)
@application.route('/<service>', methods=['GET', 'POST'])
def receive_webhook(service):
config = utils.config.load_config(CONFIG_FOLDER)
services = find_services(config)
comms = find_and_load_comms(config)
print services
print comms
return services[service](
request,
request.get_json(),
comms,
config
).execute()
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')
| from __future__ import absolute_import
from os.path import abspath
from os.path import dirname
from flask import Flask, request
import yaml
import utils.config
from services import find_services
from comms import find_and_load_comms
CONFIG_FOLDER = dirname(dirname(abspath(__file__)))
application = Flask(__name__)
@application.route('/<service>', methods=['GET', 'POST'])
def receive_webhook(service):
config = utils.config.load_config(CONFIG_FOLDER)
services = find_services(config)
comms = find_and_load_comms(config)
print services
print comms
return services[service](
request,
request.get_json(),
comms,
config[service]
).execute()
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')
| Make services only receive their related configs | Make services only receive their related configs
| Python | apache-2.0 | brantje/captain_hook,brantje/telegram-github-bot,brantje/telegram-github-bot,brantje/captain_hook,brantje/telegram-github-bot,brantje/captain_hook | ---
+++
@@ -26,7 +26,7 @@
request,
request.get_json(),
comms,
- config
+ config[service]
).execute()
|
694651b5c143e4ce1fd3de25500909c1a16faf95 | api/podcasts/controller.py | api/podcasts/controller.py | from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> list[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| from typing import List
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_feeds = list(fetch_podcasts(provider))
cache.set(CACHE_KEY, cached_feeds, 600)
return cached_feeds
def fetch_cached_podcast(slug) -> PodcastDetails:
key = f"{CACHE_KEY}:{slug}"
cached_podcast = cache.get(key)
if cached_podcast is None:
provider = PodcastProvider.objects.get(type="timbre")
cached_podcast = fetch_podcast(provider, slug)
cache.set(key, cached_podcast, 300)
return cached_podcast
| Fix typehint that is invalid in python 3.8 | Fix typehint that is invalid in python 3.8
| Python | mit | urfonline/api,urfonline/api,urfonline/api | ---
+++
@@ -1,3 +1,5 @@
+from typing import List
+
from django.core.cache import cache
from .models import PodcastProvider
@@ -8,7 +10,7 @@
CACHE_KEY = "76_timbre_feeds"
-def fetch_cached_podcasts() -> list[PodcastDetails]:
+def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(CACHE_KEY)
if cached_feeds is None: |
3a7e87be0cc42b47375baec22ffdb978cb21847c | main.py | main.py | #!/usr/bin/env python3
import requests
AUTH_TOKEN = open("config/auth_token").read().strip()
USER_ID = open("config/user_id").read().strip()
BASE_URL = "https://api.telegram.org/bot" + AUTH_TOKEN + "/"
def send_request(command, **params):
requests.get(BASE_URL + command, params=params)
def send_message(chat_id, text):
send_request("sendMessage", chat_id=chat_id, text=text)
send_message(USER_ID, "test")
| #!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class TelegramBotApi:
def __init__(self, auth_token):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
def send_message(self, chat_id, text):
self.__send_request("sendMessage", chat_id=chat_id, text=text)
def __send_request(self, command, **params):
requests.get(self.base_url + command, params=params)
class Config:
def __init__(self, config_dir):
self.config_dir = config_dir + "/"
def get_auth_token(self):
return self.__get_config_value("auth_token")
def get_user_id(self):
return self.__get_config_value("user_id")
def __get_config_value(self, config_key):
return open(self.config_dir + config_key).read().strip()
config = Config(CONFIG_DIR)
api = TelegramBotApi(config.get_auth_token())
api.send_message(config.get_user_id(), "test")
| Create TelegramBotApi and Config classes | Create TelegramBotApi and Config classes
To clean up code
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -2,18 +2,35 @@
import requests
-AUTH_TOKEN = open("config/auth_token").read().strip()
-USER_ID = open("config/user_id").read().strip()
-
-BASE_URL = "https://api.telegram.org/bot" + AUTH_TOKEN + "/"
+CONFIG_DIR = "config"
-def send_request(command, **params):
- requests.get(BASE_URL + command, params=params)
+class TelegramBotApi:
+ def __init__(self, auth_token):
+ self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
+
+ def send_message(self, chat_id, text):
+ self.__send_request("sendMessage", chat_id=chat_id, text=text)
+
+ def __send_request(self, command, **params):
+ requests.get(self.base_url + command, params=params)
-def send_message(chat_id, text):
- send_request("sendMessage", chat_id=chat_id, text=text)
+class Config:
+ def __init__(self, config_dir):
+ self.config_dir = config_dir + "/"
+
+ def get_auth_token(self):
+ return self.__get_config_value("auth_token")
+
+ def get_user_id(self):
+ return self.__get_config_value("user_id")
+
+ def __get_config_value(self, config_key):
+ return open(self.config_dir + config_key).read().strip()
-send_message(USER_ID, "test")
+config = Config(CONFIG_DIR)
+api = TelegramBotApi(config.get_auth_token())
+
+api.send_message(config.get_user_id(), "test") |
46fc845f76cfc244e6dff98a152221f7c3044386 | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
import inspect
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
path = inspect.getfile(inspect.currentframe())
home = os.path.dirname(os.path.abspath(path)) + '/../..'
cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \
'--view-failed --view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| from SCons.Script import *
import shlex
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = [python, 'tests/testHarness', '-C', 'tests', '--diff-failed',
'--view-failed', '--view-unfiltered', '--save-failed', '--build']
cmd = shlex.join(cmd)
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| Fix testHarness call for Windows | Fix testHarness call for Windows
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang | ---
+++
@@ -1,5 +1,5 @@
from SCons.Script import *
-import inspect
+import shlex
def run_tests(env):
@@ -22,13 +22,9 @@
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
- path = inspect.getfile(inspect.currentframe())
- home = os.path.dirname(os.path.abspath(path)) + '/../..'
-
- cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \
- '--view-failed --view-unfiltered --save-failed --build'
-
- if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
+ cmd = [python, 'tests/testHarness', '-C', 'tests', '--diff-failed',
+ '--view-failed', '--view-unfiltered', '--save-failed', '--build']
+ cmd = shlex.join(cmd)
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
|
6612978356a9b40e3a4b663c61b8e5ab96316623 | examples/async_server.py | examples/async_server.py | from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
def filter_handler(address, *args):
print(f"{address}: {args}")
dispatcher = Dispatcher()
dispatcher.map("/filter", filter_handler)
ip = "127.0.0.1"
port = 1337
async def loop():
"""Example main loop that only runs for 10 iterations before finishing"""
for i in range(10):
print(f"Loop {i}")
await asyncio.sleep(1)
async def init_main():
server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop())
transport, protocol = await server.create_serve_endpoint() # Create datagram endpoint and start serving
await loop() # Enter main loop of program
transport.close() # Clean up serve endpoint
asyncio.run(init_main())
| import sys
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
def filter_handler(address, *args):
print(f"{address}: {args}")
dispatcher = Dispatcher()
dispatcher.map("/filter", filter_handler)
ip = "127.0.0.1"
port = 1337
async def loop():
"""Example main loop that only runs for 10 iterations before finishing"""
for i in range(10):
print(f"Loop {i}")
await asyncio.sleep(1)
async def init_main():
server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop())
transport, protocol = await server.create_serve_endpoint() # Create datagram endpoint and start serving
await loop() # Enter main loop of program
transport.close() # Clean up serve endpoint
if sys.version_info >= (3, 7):
asyncio.run(init_main())
else:
# TODO(python-upgrade): drop this once 3.6 is no longer supported
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(init_main())
event_loop.close()
| Support Python 3.6 event loops in this example | Support Python 3.6 event loops in this example
| Python | unlicense | attwad/python-osc | ---
+++
@@ -1,3 +1,4 @@
+import sys
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
@@ -30,4 +31,10 @@
transport.close() # Clean up serve endpoint
-asyncio.run(init_main())
+if sys.version_info >= (3, 7):
+ asyncio.run(init_main())
+else:
+ # TODO(python-upgrade): drop this once 3.6 is no longer supported
+ event_loop = asyncio.get_event_loop()
+ event_loop.run_until_complete(init_main())
+ event_loop.close() |
709e1562e61110ba94ae7581952bc5233ee1035e | main.py | main.py | import argparse
import logging
from create_dataset import *
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
parser.add_argument('--type', help='pickle or lmdb')
parser.add_argument('--train', help='training dir')
parser.add_argument('--resize', help='resize image')
parser.add_argument('--output', help='output dataset dir')
args = parser.parse_args()
if not args.train or not args.output or not args.type:
parser.print_help()
else:
db_name = args.train.split('/')[-1]
if not db_name:
db_name = args.train.split('/')[-2]
if not db_name:
db_name = args.train
images = image_loader(args.train, int(args.resize))
if args.type == 'lmdb':
create_lmdb(images, args.output + '/' + db_name)
elif args.type == 'pickle':
create_pickle(images, args.output + '/' + db_name)
| import argparse
import logging
from create_dataset import *
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
parser.add_argument('-type', help='pickle or lmdb')
parser.add_argument('-train', help='training dir')
parser.add_argument('-test', help='testing dir')
parser.add_argument('-resize', help='resize image')
parser.add_argument('-output', help='output dataset dir')
parser.add_argument('-split', help='split train/test ratio')
args = parser.parse_args()
if not args.train or not args.output or not args.type:
parser.print_help()
elif not args.test and not args.split:
print 'Error: Need to specify the test dir or split ratio'
else:
train, test = None, None
db_name = args.train.split('/')[-1]
if not db_name:
db_name = args.train.split('/')[-2]
if not db_name:
db_name = args.train
train = image_loader(args.train, int(args.resize))
if not args.test:
# split from training data
train, test = split_testing(train, args.split)
elif not args.split:
# load from testing folder
test = image_loader(args.test, int(args.resize))
# Make sure the train and test are holded
if not train or not test:
print 'Error: training data and testing data are not holded'
# Save to different formats
if args.type == 'lmdb':
create_lmdb(train, test, args.output + '/' + db_name)
elif args.type == 'pickle':
create_pickle(train, test, args.output + '/' + db_name)
| Adjust the interface for split function | Adjust the interface for split function
| Python | mit | CorcovadoMing/DataLoader,CorcovadoMing/DataLoader | ---
+++
@@ -6,24 +6,47 @@
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
- parser.add_argument('--type', help='pickle or lmdb')
- parser.add_argument('--train', help='training dir')
- parser.add_argument('--resize', help='resize image')
- parser.add_argument('--output', help='output dataset dir')
-
+ parser.add_argument('-type', help='pickle or lmdb')
+ parser.add_argument('-train', help='training dir')
+ parser.add_argument('-test', help='testing dir')
+ parser.add_argument('-resize', help='resize image')
+ parser.add_argument('-output', help='output dataset dir')
+ parser.add_argument('-split', help='split train/test ratio')
args = parser.parse_args()
if not args.train or not args.output or not args.type:
parser.print_help()
+
+ elif not args.test and not args.split:
+ print 'Error: Need to specify the test dir or split ratio'
+
else:
+ train, test = None, None
+
db_name = args.train.split('/')[-1]
if not db_name:
db_name = args.train.split('/')[-2]
if not db_name:
db_name = args.train
- images = image_loader(args.train, int(args.resize))
+ train = image_loader(args.train, int(args.resize))
+
+ if not args.test:
+ # split from training data
+ train, test = split_testing(train, args.split)
+ elif not args.split:
+ # load from testing folder
+ test = image_loader(args.test, int(args.resize))
+
+ # Make sure the train and test are holded
+ if not train or not test:
+ print 'Error: training data and testing data are not holded'
+
+ # Save to different formats
if args.type == 'lmdb':
- create_lmdb(images, args.output + '/' + db_name)
+ create_lmdb(train, test, args.output + '/' + db_name)
elif args.type == 'pickle':
- create_pickle(images, args.output + '/' + db_name)
+ create_pickle(train, test, args.output + '/' + db_name)
+
+
+ |
6d03be0c21ac21e9d5ed826c5fe4991fa01743cb | main.py | main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import Tool
import time
from Tieba import Tieba
def main():
print("Local Time:", time.asctime(time.localtime()))
# Read Cookies
cookies = Tool.load_cookies_path(".")
for cookie in cookies:
# Login
user = Tieba(cookie)
# List Likes
print(user.get_likes())
# Sign
print(user.username, "Signing")
for name in user.get_likes():
if user.sign_Wap(name):
time.sleep(10)
main()
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import Tool
import time
from Tieba import Tieba
def main():
print("Local Time:", time.asctime(time.localtime()))
# Read Cookies
cookies = Tool.load_cookies_path(".")
for cookie in cookies:
# Login
user = Tieba(cookie)
# List Likes
print(user.get_likes())
# Sign
print(user.username, "Signing")
for name in user.get_likes():
if user.sign_Wap(name):
time.sleep(10)
main()
| Change newline character to LF | Change newline character to LF
| Python | apache-2.0 | jiangzc/TiebaSign | |
9dc068f947cbd5ca29b324436496d2d78f55edf7 | src/trajectory/trajectory.py | src/trajectory/trajectory.py | #!/usr/bin/env python
import math
from geometry_msgs.msg import Point
class NegativeTimeException(Exception):
pass
class Trajectory:
def __init__(self):
self.position = Point()
def get_position_at(self, t):
if t < 0:
raise NegativeTimeException()
| #!/usr/bin/env python
import math
from twisted.conch.insults.insults import Vector
from geometry_msgs.msg import Point
class NegativeTimeException(Exception):
pass
class Trajectory:
def __init__(self):
self.position = Point()
def get_position_at(self, t):
if t < 0:
raise NegativeTimeException()
def abs_vector(self):
return (self.x * self.x + self.y * self.y) ** 0.5
def sub_point(self, other):
return Vector(self.x - other.x, self.y - other.y)
Vector.__abs__ = abs_vector
Point.__sub__ = sub_point
| Implement __abs__ and __sub__ dunder methods | feat: Implement __abs__ and __sub__ dunder methods
Implement methods which are required to apply assertEqual and assertAlmostEqual to points. | Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
import math
+from twisted.conch.insults.insults import Vector
from geometry_msgs.msg import Point
@@ -14,3 +15,14 @@
def get_position_at(self, t):
if t < 0:
raise NegativeTimeException()
+
+def abs_vector(self):
+ return (self.x * self.x + self.y * self.y) ** 0.5
+
+
+def sub_point(self, other):
+ return Vector(self.x - other.x, self.y - other.y)
+
+
+Vector.__abs__ = abs_vector
+Point.__sub__ = sub_point |
92d2ff8a16b7419123a848f98ec8594694c5203a | lib/python2.6/aquilon/client/depends.py | lib/python2.6/aquilon/client/depends.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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.
""" Suggested versions of external libraries, and the defaults for the
binaries shipped.
"""
import sys
import ms.version
ms.version.addpkg('lxml', '2.3.2')
if sys.platform == "sunos5":
# ctypes is missing from the default Python build on Solaris, due to
# http://bugs.python.org/issue2552. It is available as a separate package
# though.
ms.version.addpkg("ctypes", "1.0.2")
# required to move the ctypes path before the core paths
sys.path[0] = sys.path.pop()
| # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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.
""" Suggested versions of external libraries, and the defaults for the
binaries shipped.
"""
import sys
import ms.version
ms.version.addpkg('lxml', '2.3.2')
if sys.platform == "sunos5":
# ctypes is missing from the default Python build on Solaris, due to
# http://bugs.python.org/issue2552. It is available as a separate package
# though.
ms.version.addpkg("ctypes", "1.0.2")
# required to move the ctypes path before the core paths
sys.path.insert(0, sys.path.pop())
| Fix imports when using the client on Solaris | Fix imports when using the client on Solaris
Previously the incorrect syntax had been used for inserting an item at
the beginning of sys.path.
Change-Id: I98a1451dd84619a0ba5f5be3dc4163509b867149
Addresses-Issue: Jira/AQUILON-1276
Reviewed-by: Gabor Gombas <3bb8c49439d9d044594e1c6967f991d0b4248a64@morganstanley.com>
| Python | apache-2.0 | stdweird/aquilon,quattor/aquilon,stdweird/aquilon,stdweird/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,quattor/aquilon,quattor/aquilon | ---
+++
@@ -31,4 +31,4 @@
ms.version.addpkg("ctypes", "1.0.2")
# required to move the ctypes path before the core paths
- sys.path[0] = sys.path.pop()
+ sys.path.insert(0, sys.path.pop()) |
1923fdf26f2df092a52318dfcc91825fa10fac40 | mesh.py | mesh.py | #!/usr/bin/env python3
import os
import shutil
import sys
import traceback
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
print('%s $ ' % os.getcwd(), end='', flush=True)
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
print(command)
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == "__main__":
while True:
try:
prompt()
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except SystemExit:
break
except:
traceback.print_exc()
| #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s $ ' % os.getcwd()
def read_command():
line = input(prompt())
return line
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == "__main__":
while True:
try:
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except SystemExit:
break
except:
traceback.print_exc()
| Add readline support with vi keybindings | Add readline support with vi keybindings
| Python | mit | mmichie/mesh | ---
+++
@@ -3,21 +3,25 @@
import os
import shutil
import sys
+import readline
import traceback
+
+readline.parse_and_bind('tab: complete')
+readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
- print('%s $ ' % os.getcwd(), end='', flush=True)
+ return '%s $ ' % os.getcwd()
def read_command():
- return sys.stdin.readline()
+ line = input(prompt())
+ return line
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
- print(command)
return True
def run_builtin(cmd, cmd_text):
@@ -33,7 +37,6 @@
if __name__ == "__main__":
while True:
try:
- prompt()
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd) |
bd5223af36fc167ce48bfa5c97f8a3fd79a7995a | camera_selection/scripts/camera_selection.py | camera_selection/scripts/camera_selection.py | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,PIN_MAP_FEED1,PIN_MAP_FEED2]
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('camera_feed_selection',CameraFeedSelection, self.callback)
#Set pin as output
for pin_list in PIN_MAP_LIST:
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
def callback(self, msg):
feed_pin_map = PIN_MAP_LIST[msg.feed]
for i, level in enumerate(msg.pin_values):
if level:
GPIO.output(feed_pin_map[i], GPIO.HIGH)
else
GPIO.output(feed_pin_map[i], GPIO.LOW)
if __name__ == '__main__':
try:
camera_selection = CameraSelection()
rospy.spin()
except rospy.ROSInterruptException:
pass
| #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,PIN_MAP_FEED1,PIN_MAP_FEED2]
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('camera_feed_selection',CameraFeedSelection, self.callback)
#Set pin as output
for pin_list in PIN_MAP_LIST:
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
def callback(self, msg):
# Get pin map for relevant feed
feed_pin_map = PIN_MAP_LIST[msg.feed]
# Convert selected camera to binary array
cam_select = [int(bit) for bit in bin(msg.camera)[2:]]
for indx, output_pin in enumerate(cam_select):
if output_pin:
GPIO.output(feed_pin_map[indx], GPIO.HIGH)
else
GPIO.output(feed_pin_map[indx], GPIO.LOW)
if __name__ == '__main__':
try:
camera_selection = CameraSelection()
rospy.spin()
except rospy.ROSInterruptException:
pass
| Add camera selection based on desired feed and camera number | Add camera selection based on desired feed and camera number
| Python | mit | vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control | ---
+++
@@ -20,12 +20,15 @@
def callback(self, msg):
+ # Get pin map for relevant feed
feed_pin_map = PIN_MAP_LIST[msg.feed]
- for i, level in enumerate(msg.pin_values):
- if level:
- GPIO.output(feed_pin_map[i], GPIO.HIGH)
+ # Convert selected camera to binary array
+ cam_select = [int(bit) for bit in bin(msg.camera)[2:]]
+ for indx, output_pin in enumerate(cam_select):
+ if output_pin:
+ GPIO.output(feed_pin_map[indx], GPIO.HIGH)
else
- GPIO.output(feed_pin_map[i], GPIO.LOW)
+ GPIO.output(feed_pin_map[indx], GPIO.LOW)
|
65ede498c28dc37b96bc1a2d435f5714c9a4eb1e | cms/middleware/media.py | cms/middleware/media.py | from django.forms.widgets import Media
from django.utils.encoding import smart_unicode
from django.conf import settings
from cms.middleware.toolbar import HTML_TYPES
def inster_before_tag(string, tag, insertion):
no_case = string.lower()
index = no_case.find("<%s" % tag.lower())
if index > -1:
start_tag = index
return string[:start_tag] + insertion + string[start_tag:]
else:
return string
class PlaceholderMediaMiddleware(object):
def inject_media(self, request, response):
if request.is_ajax():
return False
if response.status_code != 200:
return False
if not response['Content-Type'].split(';')[0] in HTML_TYPES:
return False
if request.path_info.startswith(settings.MEDIA_URL):
return False
return True
def process_request(self, request):
request.placeholder_media = Media()
def process_response(self, request, response):
if self.inject_media(request, response) and hasattr('placeholder_media'):
response.content = inster_before_tag(smart_unicode(response.content),
u'/head', smart_unicode(request.placeholder_media.render()))
return response
| from django.forms.widgets import Media
from django.utils.encoding import smart_unicode
from django.conf import settings
from cms.middleware.toolbar import HTML_TYPES
def inster_before_tag(string, tag, insertion):
no_case = string.lower()
index = no_case.find("<%s" % tag.lower())
if index > -1:
start_tag = index
return string[:start_tag] + insertion + string[start_tag:]
else:
return string
class PlaceholderMediaMiddleware(object):
def inject_media(self, request, response):
if request.is_ajax():
return False
if response.status_code != 200:
return False
if not response['Content-Type'].split(';')[0] in HTML_TYPES:
return False
if request.path_info.startswith(settings.MEDIA_URL):
return False
return True
def process_request(self, request):
request.placeholder_media = Media()
def process_response(self, request, response):
if self.inject_media(request, response) and hasattr(request,'placeholder_media'):
response.content = inster_before_tag(smart_unicode(response.content),
u'/head', smart_unicode(request.placeholder_media.render()))
return response
| Fix forgotten 'request' parameter to hasattr | Fix forgotten 'request' parameter to hasattr
| Python | bsd-3-clause | sephii/django-cms,mkoistinen/django-cms,cyberintruder/django-cms,andyzsf/django-cms,isotoma/django-cms,takeshineshiro/django-cms,SachaMPS/django-cms,sznekol/django-cms,pbs/django-cms,chkir/django-cms,stefanw/django-cms,vad/django-cms,ScholzVolkmer/django-cms,webu/django-cms,VillageAlliance/django-cms,intip/django-cms,czpython/django-cms,nostalgiaz/django-cms,selecsosi/django-cms,chkir/django-cms,Vegasvikk/django-cms,stefanw/django-cms,petecummings/django-cms,adaptivelogic/django-cms,benzkji/django-cms,bittner/django-cms,iddqd1/django-cms,sephii/django-cms,jalaziz/django-cms-grappelli-old,pixbuffer/django-cms,vad/django-cms,iddqd1/django-cms,foobacca/django-cms,SofiaReis/django-cms,webu/django-cms,timgraham/django-cms,11craft/django-cms,benzkji/django-cms,saintbird/django-cms,kk9599/django-cms,keimlink/django-cms,wuzhihui1123/django-cms,jproffitt/django-cms,robmagee/django-cms,liuyisiyisi/django-cms,rsalmaso/django-cms,SofiaReis/django-cms,timgraham/django-cms,czpython/django-cms,bittner/django-cms,FinalAngel/django-cms,mkoistinen/django-cms,stefanw/django-cms,youprofit/django-cms,jrief/django-cms,pancentric/django-cms,nimbis/django-cms,mkoistinen/django-cms,wuzhihui1123/django-cms,isotoma/django-cms,jproffitt/django-cms,leture/django-cms,rryan/django-cms,astagi/django-cms,rscnt/django-cms,wyg3958/django-cms,11craft/django-cms,sznekol/django-cms,bittner/django-cms,SinnerSchraderMobileMirrors/django-cms,driesdesmet/django-cms,josjevv/django-cms,FinalAngel/django-cms,wuzhihui1123/django-cms,Jaccorot/django-cms,pbs/django-cms,owers19856/django-cms,rryan/django-cms,MagicSolutions/django-cms,vstoykov/django-cms,jrief/django-cms,keimlink/django-cms,datakortet/django-cms,ojii/django-cms,leture/django-cms,rsalmaso/django-cms,sephii/django-cms,SachaMPS/django-cms,frnhr/django-cms,nimbis/django-cms,SachaMPS/django-cms,rscnt/django-cms,intgr/django-cms,saintbird/django-cms,liuyisiyisi/django-cms,datakortet/django-cms,MagicSolutions/django-cms,vstoykov/django-cms,ojii/django-cms,11craft/django-cms,divio/django-cms,wuzhihui1123/django-cms,DylannCordel/django-cms,irudayarajisawa/django-cms,divio/django-cms,stefanfoulis/django-cms,rscnt/django-cms,rsalmaso/django-cms,SinnerSchraderMobileMirrors/django-cms,cyberintruder/django-cms,11craft/django-cms,vxsx/django-cms,kk9599/django-cms,bittner/django-cms,intip/django-cms,chrisglass/django-cms,nostalgiaz/django-cms,Vegasvikk/django-cms,sznekol/django-cms,AlexProfi/django-cms,czpython/django-cms,foobacca/django-cms,vad/django-cms,sephii/django-cms,stefanfoulis/django-cms,qnub/django-cms,SmithsonianEnterprises/django-cms,philippze/django-cms,netzkolchose/django-cms,dhorelik/django-cms,vxsx/django-cms,adaptivelogic/django-cms,jeffreylu9/django-cms,benzkji/django-cms,Livefyre/django-cms,memnonila/django-cms,ojii/django-cms,FinalAngel/django-cms,robmagee/django-cms,jsma/django-cms,jsma/django-cms,driesdesmet/django-cms,timgraham/django-cms,philippze/django-cms,foobacca/django-cms,divio/django-cms,intip/django-cms,donce/django-cms,MagicSolutions/django-cms,jsma/django-cms,netzkolchose/django-cms,keimlink/django-cms,ScholzVolkmer/django-cms,selecsosi/django-cms,stefanfoulis/django-cms,farhaadila/django-cms,chkir/django-cms,360youlun/django-cms,mkoistinen/django-cms,frnhr/django-cms,chmberl/django-cms,qnub/django-cms,memnonila/django-cms,netzkolchose/django-cms,Livefyre/django-cms,dhorelik/django-cms,dhorelik/django-cms,DylannCordel/django-cms,datakortet/django-cms,nimbis/django-cms,VillageAlliance/django-cms,jrief/django-cms,Jaccorot/django-cms,wyg3958/django-cms,jproffitt/django-cms,VillageAlliance/django-cms,Jaccorot/django-cms,yakky/django-cms,AlexProfi/django-cms,yakky/django-cms,intgr/django-cms,petecummings/django-cms,jalaziz/django-cms-grappelli-old,jrclaramunt/django-cms,pbs/django-cms,ScholzVolkmer/django-cms,iddqd1/django-cms,pixbuffer/django-cms,benzkji/django-cms,netzkolchose/django-cms,vad/django-cms,leture/django-cms,adaptivelogic/django-cms,nimbis/django-cms,robmagee/django-cms,chrisglass/django-cms,pixbuffer/django-cms,owers19856/django-cms,czpython/django-cms,jproffitt/django-cms,pbs/django-cms,takeshineshiro/django-cms,nostalgiaz/django-cms,evildmp/django-cms,astagi/django-cms,foobacca/django-cms,youprofit/django-cms,DylannCordel/django-cms,FinalAngel/django-cms,andyzsf/django-cms,josjevv/django-cms,jeffreylu9/django-cms,chmberl/django-cms,liuyisiyisi/django-cms,wyg3958/django-cms,evildmp/django-cms,pancentric/django-cms,qnub/django-cms,farhaadila/django-cms,jrclaramunt/django-cms,jalaziz/django-cms-grappelli-old,isotoma/django-cms,Livefyre/django-cms,selecsosi/django-cms,SmithsonianEnterprises/django-cms,SofiaReis/django-cms,evildmp/django-cms,360youlun/django-cms,kk9599/django-cms,datakortet/django-cms,farhaadila/django-cms,josjevv/django-cms,jeffreylu9/django-cms,saintbird/django-cms,intgr/django-cms,irudayarajisawa/django-cms,youprofit/django-cms,divio/django-cms,petecummings/django-cms,driesdesmet/django-cms,360youlun/django-cms,webu/django-cms,rryan/django-cms,vstoykov/django-cms,andyzsf/django-cms,evildmp/django-cms,stefanw/django-cms,donce/django-cms,frnhr/django-cms,stefanfoulis/django-cms,memnonila/django-cms,irudayarajisawa/django-cms,philippze/django-cms,donce/django-cms,andyzsf/django-cms,jrief/django-cms,intip/django-cms,selecsosi/django-cms,vxsx/django-cms,SmithsonianEnterprises/django-cms,rsalmaso/django-cms,rryan/django-cms,isotoma/django-cms,vxsx/django-cms,nostalgiaz/django-cms,jrclaramunt/django-cms,owers19856/django-cms,frnhr/django-cms,astagi/django-cms,pancentric/django-cms,intgr/django-cms,yakky/django-cms,yakky/django-cms,jsma/django-cms,AlexProfi/django-cms,takeshineshiro/django-cms,chmberl/django-cms,jeffreylu9/django-cms,cyberintruder/django-cms,SinnerSchraderMobileMirrors/django-cms,Vegasvikk/django-cms,Livefyre/django-cms | ---
+++
@@ -28,7 +28,7 @@
request.placeholder_media = Media()
def process_response(self, request, response):
- if self.inject_media(request, response) and hasattr('placeholder_media'):
+ if self.inject_media(request, response) and hasattr(request,'placeholder_media'):
response.content = inster_before_tag(smart_unicode(response.content),
u'/head', smart_unicode(request.placeholder_media.render()))
return response |
daac5f26c07045ad162a481d035359dd17227c91 | Lib/test/test_imaplib.py | Lib/test/test_imaplib.py | from test_support import verify,verbose
import imaplib
import time
# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.
timevalues = [2000000000, 2000000000.0, time.localtime(2000000000),
"18-May-2033 05:33:20 +0200"]
for t in timevalues:
imaplib.Time2Internaldate(t)
| import imaplib
import time
# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.
timevalues = [2000000000, 2000000000.0, time.localtime(2000000000),
"18-May-2033 05:33:20 +0200"]
for t in timevalues:
imaplib.Time2Internaldate(t)
| Remove unused imports, clean up trailing whitespace. | Remove unused imports, clean up trailing whitespace.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,3 @@
-from test_support import verify,verbose
import imaplib
import time
@@ -11,4 +10,3 @@
for t in timevalues:
imaplib.Time2Internaldate(t)
- |
6dd523e0d92c39f1a3e4c9be2dac0442535bb88f | changes/backends/jenkins/generic_builder.py | changes/backends/jenkins/generic_builder.py | from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
def get_job_parameters(self, job, script=None):
params = super(JenkinsGenericBuilder, self).get_job_parameters(job)
if script is None:
script = self.script
project = job.project
repository = project.repository
vcs = repository.get_vcs()
if vcs:
repo_url = vcs.remote_url
else:
repo_url = repository.url
params.extend([
{'name': 'CHANGES_PID', 'value': project.slug},
{'name': 'REPO_URL', 'value': repo_url},
{'name': 'SCRIPT', 'value': script},
{'name': 'REPO_VCS', 'value': repository.backend.name},
{'name': 'CLUSTER', 'value': self.cluster},
])
return params
| from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
def get_job_parameters(self, job, script=None, target_id=None):
params = super(JenkinsGenericBuilder, self).get_job_parameters(
job, target_id=target_id)
if script is None:
script = self.script
project = job.project
repository = project.repository
vcs = repository.get_vcs()
if vcs:
repo_url = vcs.remote_url
else:
repo_url = repository.url
params.extend([
{'name': 'CHANGES_PID', 'value': project.slug},
{'name': 'REPO_URL', 'value': repo_url},
{'name': 'SCRIPT', 'value': script},
{'name': 'REPO_VCS', 'value': repository.backend.name},
{'name': 'CLUSTER', 'value': self.cluster},
])
return params
| Fix target_id support in JenkinsGenericBuilder | Fix target_id support in JenkinsGenericBuilder
| Python | apache-2.0 | wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes | ---
+++
@@ -7,8 +7,9 @@
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
- def get_job_parameters(self, job, script=None):
- params = super(JenkinsGenericBuilder, self).get_job_parameters(job)
+ def get_job_parameters(self, job, script=None, target_id=None):
+ params = super(JenkinsGenericBuilder, self).get_job_parameters(
+ job, target_id=target_id)
if script is None:
script = self.script |
7b6c3b4af18746ad02169a93270fc13579c60829 | pycket/targetpycket.py | pycket/targetpycket.py | from pycket.expand import load_json_ast_rpython
from pycket.interpreter import interpret_one
from pycket.error import SchemeException
from rpython.rlib import jit
def main(argv):
jit.set_param(None, "trace_limit", 20000)
# XXX crappy argument handling
try:
index = argv.index("--jit")
except ValueError:
pass
else:
if index == len(argv) - 1:
print "missing argument after --jit"
return 2
jitarg = argv[index + 1]
del argv[index:index+2]
jit.set_user_param(None, jitarg)
if len(argv) != 2:
print "need exactly one argument, the json file to run"
return 3
ast = load_json_ast_rpython(argv[1])
try:
val = interpret_one(ast)
except SchemeException, e:
print "ERROR:", e.msg
raise # to see interpreter-level traceback
else:
print val.tostring()
return 0
def target(*args):
return main
if __name__ == '__main__':
import sys
main(sys.argv)
| from pycket.expand import load_json_ast_rpython
from pycket.interpreter import interpret_one
from pycket.error import SchemeException
from rpython.rlib import jit
from rpython.rlib.objectmodel import we_are_translated
def main(argv):
jit.set_param(None, "trace_limit", 20000)
# XXX crappy argument handling
try:
index = argv.index("--jit")
except ValueError:
pass
else:
if index == len(argv) - 1:
print "missing argument after --jit"
return 2
jitarg = argv[index + 1]
del argv[index:index+2]
jit.set_user_param(None, jitarg)
if len(argv) != 2:
print "need exactly one argument, the json file to run"
return 3
ast = load_json_ast_rpython(argv[1])
try:
val = interpret_one(ast)
except SchemeException, e:
print "ERROR:", e.msg
raise # to see interpreter-level traceback
else:
print val.tostring()
return 0
def target(*args):
return main
if __name__ == '__main__':
assert not we_are_translated()
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
try:
sys.exit(f(sys.argv))
except SystemExit:
pass
except:
import pdb, traceback
_type, value, tb = sys.exc_info()
traceback.print_exception(_type, value, tb)
pdb.post_mortem(tb)
| Add auto-pdb fallback when not in translated mode for target | Add auto-pdb fallback when not in translated mode for target
| Python | mit | pycket/pycket,pycket/pycket,samth/pycket,krono/pycket,samth/pycket,vishesh/pycket,samth/pycket,magnusmorton/pycket,pycket/pycket,krono/pycket,magnusmorton/pycket,magnusmorton/pycket,krono/pycket,cderici/pycket,cderici/pycket,vishesh/pycket,vishesh/pycket,cderici/pycket | ---
+++
@@ -3,6 +3,8 @@
from pycket.error import SchemeException
from rpython.rlib import jit
+
+from rpython.rlib.objectmodel import we_are_translated
def main(argv):
jit.set_param(None, "trace_limit", 20000)
@@ -36,5 +38,15 @@
return main
if __name__ == '__main__':
- import sys
- main(sys.argv)
+ assert not we_are_translated()
+ from rpython.translator.driver import TranslationDriver
+ f, _ = target(TranslationDriver(), sys.argv)
+ try:
+ sys.exit(f(sys.argv))
+ except SystemExit:
+ pass
+ except:
+ import pdb, traceback
+ _type, value, tb = sys.exc_info()
+ traceback.print_exception(_type, value, tb)
+ pdb.post_mortem(tb) |
ad73c91d4e2b2d5faed35420a1393d016af84e40 | tests/test_event_manager/test_attribute.py | tests/test_event_manager/test_attribute.py | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| Add test for attribute instance assertion | Add test for attribute instance assertion
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -9,6 +9,10 @@
class TestAttribute(BaseTest):
+ def test_name_should_not_be_instance(self):
+ with self.assertRaises(AssertionError):
+ Attribute(name='instance')
+
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test' |
b5cab8fe05899891e4508cb686d40d88e3c5b955 | tests/unit/geometry/GenericGeometryTest.py | tests/unit/geometry/GenericGeometryTest.py | import openpnm as op
class GenericGeometryTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
self.geo.regenerate_models()
def teardown_class(self):
mgr = op.Workspace()
mgr.clear()
def test_plot_histogram(self):
self.geo.show_hist()
self.geo.show_hist(props=['pore.diameter', 'pore.volume',
'throat.length'])
self.geo.show_hist(props=['pore.diameter', 'pore.volume',
'throat.length', 'throat.diameter',
'pore.seed'])
if __name__ == '__main__':
t = GenericGeometryTest()
self = t
t.setup_class()
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
| import openpnm as op
class GenericGeometryTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
self.geo.regenerate_models()
def teardown_class(self):
mgr = op.Workspace()
mgr.clear()
def test_plot_histogram(self):
# Test default args
self.geo.show_hist()
# Test with non-default args
self.geo.show_hist(props=['pore.diameter', 'pore.volume', 'throat.length'])
# Test layout when num_props = 4 => should be 2 by 2
self.geo.show_hist(
props=[
'pore.diameter',
'throat.diameter',
'pore.volume',
'throat.length'
]
)
# Test layout when num_props > 4 => should be nrows by 3
self.geo.show_hist(
props=[
'pore.diameter',
'pore.volume',
'throat.length',
'throat.diameter',
'pore.seed'
]
)
if __name__ == '__main__':
t = GenericGeometryTest()
self = t
t.setup_class()
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
| Augment unit test for show_hist | Augment unit test for show_hist
| Python | mit | PMEAL/OpenPNM | ---
+++
@@ -15,12 +15,29 @@
mgr.clear()
def test_plot_histogram(self):
+ # Test default args
self.geo.show_hist()
- self.geo.show_hist(props=['pore.diameter', 'pore.volume',
- 'throat.length'])
- self.geo.show_hist(props=['pore.diameter', 'pore.volume',
- 'throat.length', 'throat.diameter',
- 'pore.seed'])
+ # Test with non-default args
+ self.geo.show_hist(props=['pore.diameter', 'pore.volume', 'throat.length'])
+ # Test layout when num_props = 4 => should be 2 by 2
+ self.geo.show_hist(
+ props=[
+ 'pore.diameter',
+ 'throat.diameter',
+ 'pore.volume',
+ 'throat.length'
+ ]
+ )
+ # Test layout when num_props > 4 => should be nrows by 3
+ self.geo.show_hist(
+ props=[
+ 'pore.diameter',
+ 'pore.volume',
+ 'throat.length',
+ 'throat.diameter',
+ 'pore.seed'
+ ]
+ )
if __name__ == '__main__': |
2c73d919273b1660af40053afa198a42278c07a9 | tests/qtgui/qdatastream_gui_operators_test.py | tests/qtgui/qdatastream_gui_operators_test.py | # -*- coding: utf-8 -*-
import unittest
import sys
from PySide import QtGui, QtCore
class QAppPresence(unittest.TestCase):
def testQPixmap(self):
ds = QtCore.QDataStream()
p = QtGui.QPixmap()
ds << p
ds >> p
if __name__ == '__main__':
app = QtGui.QApplication([])
unittest.main()
| # -*- coding: utf-8 -*-
import unittest
import sys
from PySide.QtCore import QDataStream, QByteArray, QIODevice, Qt
from PySide.QtGui import QPixmap, QColor
from helper import UsesQApplication
class QPixmapQDatastream(UsesQApplication):
'''QDataStream <<>> QPixmap'''
def setUp(self):
super(QPixmapQDatastream, self).setUp()
self.source_pixmap = QPixmap(100, 100)
self.source_pixmap.fill(Qt.red)
self.output_pixmap = QPixmap()
self.buffer = QByteArray()
self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly)
self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly)
def testStream(self):
self.write_stream << self.source_pixmap
self.read_stream >> self.output_pixmap
image = self.output_pixmap.toImage()
pixel = image.pixel(10,10)
self.assertEqual(pixel, QColor(Qt.red).rgba())
self.assertEqual(self.source_pixmap.toImage(), self.output_pixmap.toImage())
if __name__ == '__main__':
unittest.main()
| Fix QDataStream <</>> QPixmap test | Fix QDataStream <</>> QPixmap test
| Python | lgpl-2.1 | BadSingleton/pyside2,IronManMark20/pyside2,qtproject/pyside-pyside,M4rtinK/pyside-android,gbaty/pyside2,RobinD42/pyside,enthought/pyside,M4rtinK/pyside-bb10,enthought/pyside,enthought/pyside,qtproject/pyside-pyside,enthought/pyside,BadSingleton/pyside2,IronManMark20/pyside2,IronManMark20/pyside2,enthought/pyside,IronManMark20/pyside2,pankajp/pyside,M4rtinK/pyside-android,BadSingleton/pyside2,enthought/pyside,M4rtinK/pyside-android,RobinD42/pyside,M4rtinK/pyside-bb10,PySide/PySide,M4rtinK/pyside-android,pankajp/pyside,qtproject/pyside-pyside,pankajp/pyside,PySide/PySide,PySide/PySide,RobinD42/pyside,gbaty/pyside2,M4rtinK/pyside-bb10,M4rtinK/pyside-bb10,M4rtinK/pyside-android,IronManMark20/pyside2,BadSingleton/pyside2,M4rtinK/pyside-bb10,PySide/PySide,RobinD42/pyside,PySide/PySide,gbaty/pyside2,RobinD42/pyside,gbaty/pyside2,M4rtinK/pyside-android,RobinD42/pyside,qtproject/pyside-pyside,gbaty/pyside2,RobinD42/pyside,qtproject/pyside-pyside,enthought/pyside,pankajp/pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,pankajp/pyside | ---
+++
@@ -3,17 +3,33 @@
import unittest
import sys
-from PySide import QtGui, QtCore
+from PySide.QtCore import QDataStream, QByteArray, QIODevice, Qt
+from PySide.QtGui import QPixmap, QColor
+
+from helper import UsesQApplication
+
+class QPixmapQDatastream(UsesQApplication):
+ '''QDataStream <<>> QPixmap'''
+
+ def setUp(self):
+ super(QPixmapQDatastream, self).setUp()
+ self.source_pixmap = QPixmap(100, 100)
+ self.source_pixmap.fill(Qt.red)
+ self.output_pixmap = QPixmap()
+ self.buffer = QByteArray()
+ self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly)
+ self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly)
+
+ def testStream(self):
+ self.write_stream << self.source_pixmap
+
+ self.read_stream >> self.output_pixmap
+
+ image = self.output_pixmap.toImage()
+ pixel = image.pixel(10,10)
+ self.assertEqual(pixel, QColor(Qt.red).rgba())
+ self.assertEqual(self.source_pixmap.toImage(), self.output_pixmap.toImage())
-class QAppPresence(unittest.TestCase):
-
- def testQPixmap(self):
- ds = QtCore.QDataStream()
- p = QtGui.QPixmap()
- ds << p
- ds >> p
-
if __name__ == '__main__':
- app = QtGui.QApplication([])
unittest.main() |
6129a57ab8b7de1a4189706a966b32174182c086 | server.py | server.py | from flask import Flask
# Create Flask application
app = Flask(__name__)
@app.route('/inventory')
def index():
""" Intro page of the inventory API
This method will only return some welcome words.
Returns:
response: welcome words in json format and status 200
Todo:
* Finish the implementations.
* Write the tests for this.
"""
pass
@app.route('/inventory/products/<int:id>', methods=['PUT'])
def update_product(id):
""" Update info about a product
This method will update the info about a product
(eg. amount of new, open box or used.)
Args:
id (string): The id of the product to be update
Returns:
response: update successful message with status 200 if succeeded
or no product found with status 404 if cannot found the product
or invalid update with status 400 if the update violates any limitation.
Todo:
* Finish the implementations.
* Write the tests for this.
"""
pass
| from flask import Flask
# Create Flask application
app = Flask(__name__)
@app.route('/inventory')
def index():
""" Intro page of the inventory API
This method will only return some welcome words.
Returns:
response: welcome words in json format and status 200
Todo:
* Finish the implementations.
* Write the tests for this.
"""
pass
@app.route('/inventory/products', methods=['GET'])
def get_product_list():
""" Get info about all products
This method will get the info about all the products
Args:
no arguments
Returns:
response: product information(product id, location id, used/new/open_box, total_quantity, restock_level)
status 200 if succeeded
Todo:
* Finish the implementations.
* Write the tests for this.
"""
@app.route('/inventory/products/<int:id>', methods=['PUT'])
def update_product(id):
""" Update info about a product
This method will update the info about a product
(eg. amount of new, open box or used.)
Args:
id (string): The id of the product to be update
Returns:
response: update successful message with status 200 if succeeded
or no product found with status 404 if cannot found the product
or invalid update with status 400 if the update violates any limitation.
Todo:
* Finish the implementations.
* Write the tests for this.
"""
pass
| Create a GET products method | Create a GET products method
| Python | mit | devops-foxtrot-s17/inventory,devops-foxtrot-s17/inventory | ---
+++
@@ -19,6 +19,24 @@
"""
pass
+@app.route('/inventory/products', methods=['GET'])
+def get_product_list():
+ """ Get info about all products
+
+ This method will get the info about all the products
+
+ Args:
+ no arguments
+
+ Returns:
+ response: product information(product id, location id, used/new/open_box, total_quantity, restock_level)
+ status 200 if succeeded
+
+ Todo:
+ * Finish the implementations.
+ * Write the tests for this.
+
+ """
@app.route('/inventory/products/<int:id>', methods=['PUT'])
def update_product(id): |
cc04dc53dd992b14b2f56f50f3efbfde83d5154d | dodo.py | dodo.py | from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
return {
'actions': ['python -m doctest -v README.rst'],
'file_dep': ['configclass.py', 'README.rst'],
}
def task_coverage():
return {
'actions': [
'coverage run --source=configclass.py,test_configclass.py `which py.test`',
'coverage report --show-missing'],
'verbosity': 2,
}
def task_manifest():
"""create manifest file for distutils """
cmd = "git ls-tree --name-only -r HEAD > MANIFEST"
return {'actions': [cmd]}
def task_pypi():
"""upload package to pypi"""
return {
'actions': ["python setup.py sdist upload"],
'task_dep': ['manifest'],
}
| from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
return {
'actions': ['python -m doctest -v README.rst'],
'file_dep': ['configclass.py', 'README.rst'],
}
def task_coverage():
return {
'actions': [
'coverage run --source=configclass,test_configclass `which py.test`',
'coverage report --show-missing'],
'verbosity': 2,
}
def task_manifest():
"""create manifest file for distutils """
cmd = "git ls-tree --name-only -r HEAD > MANIFEST"
return {'actions': [cmd]}
def task_pypi():
"""upload package to pypi"""
return {
'actions': ["python setup.py sdist upload"],
'task_dep': ['manifest'],
}
| Fix call to "coverage run" | doit: Fix call to "coverage run"
| Python | mit | schettino72/configclass | ---
+++
@@ -22,7 +22,7 @@
def task_coverage():
return {
'actions': [
- 'coverage run --source=configclass.py,test_configclass.py `which py.test`',
+ 'coverage run --source=configclass,test_configclass `which py.test`',
'coverage report --show-missing'],
'verbosity': 2,
} |
ee2ecf60ea2fdbfe7f6c4f9ccc7275d534eeeacf | test_proj/urls.py | test_proj/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
| try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
| Support for Django > 1.4 for test proj | Support for Django > 1.4 for test proj
| Python | mit | glic3rinu/django-admin-tools,artscoop/django-admin-tools,artscoop/django-admin-tools,artscoop/django-admin-tools,glic3rinu/django-admin-tools,glic3rinu/django-admin-tools,glic3rinu/django-admin-tools,artscoop/django-admin-tools | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import *
+try:
+ from django.conf.urls import patterns, url, include
+except ImportError: # django < 1.4
+ from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
|
eaa85b0fe69e4ff020cd269007fa1a5c7f864b53 | admin/common_auth/models.py | admin/common_auth/models.py | from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
| from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
class Meta:
# custom permissions for use in the OSF Admin App
permissions = (
('mark_spam', 'Can mark comments, projects and registrations as spam'),
('view_spam', 'Can view nodes, comments, and projects marked as spam'),
('view_metrics', 'Can view metrics on the OSF Admin app'),
('view_prereg', 'Can view entries for the preregistration chellenge on the admin'),
('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'),
)
| Add custom permissions to admin profile for spam, metrics, and prereg | Add custom permissions to admin profile for spam, metrics, and prereg
| Python | apache-2.0 | mattclark/osf.io,crcresearch/osf.io,acshi/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,caneruguz/osf.io,binoculars/osf.io,caneruguz/osf.io,cslzchen/osf.io,felliott/osf.io,crcresearch/osf.io,hmoco/osf.io,baylee-d/osf.io,caseyrollins/osf.io,acshi/osf.io,leb2dg/osf.io,erinspace/osf.io,Johnetordoff/osf.io,chennan47/osf.io,saradbowman/osf.io,icereval/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,caneruguz/osf.io,leb2dg/osf.io,laurenrevere/osf.io,aaxelb/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,sloria/osf.io,erinspace/osf.io,chrisseto/osf.io,cslzchen/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,cslzchen/osf.io,caseyrollins/osf.io,adlius/osf.io,mattclark/osf.io,icereval/osf.io,hmoco/osf.io,adlius/osf.io,acshi/osf.io,cslzchen/osf.io,acshi/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,felliott/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,chennan47/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,felliott/osf.io,caseyrollins/osf.io,adlius/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,aaxelb/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,sloria/osf.io,erinspace/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,crcresearch/osf.io,leb2dg/osf.io,chrisseto/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,aaxelb/osf.io,chrisseto/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,acshi/osf.io,sloria/osf.io,mattclark/osf.io,binoculars/osf.io,binoculars/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,Nesiehr/osf.io,felliott/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,adlius/osf.io,mfraezz/osf.io,hmoco/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,hmoco/osf.io,icereval/osf.io,laurenrevere/osf.io | ---
+++
@@ -7,3 +7,14 @@
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
+
+
+ class Meta:
+ # custom permissions for use in the OSF Admin App
+ permissions = (
+ ('mark_spam', 'Can mark comments, projects and registrations as spam'),
+ ('view_spam', 'Can view nodes, comments, and projects marked as spam'),
+ ('view_metrics', 'Can view metrics on the OSF Admin app'),
+ ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'),
+ ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'),
+ ) |
275c39faa02dc0bd4f8b9d9bd2a012eaee12a338 | nose2/tests/functional/test_coverage.py | nose2/tests/functional/test_coverage.py | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
| import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
| Fix regex matching coverage output | Fix regex matching coverage output
The coverage library now returns the file extensions.
| Python | bsd-2-clause | ojengwa/nose2,ptthiem/nose2,ptthiem/nose2,little-dude/nose2,ojengwa/nose2,little-dude/nose2 | ---
+++
@@ -16,7 +16,7 @@
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
- stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS)
+ stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
- stderr='TOTAL ' + STATS)
+ stderr='TOTAL ' + STATS) |
8a509fd2b6bfa5114986df5548132ab41eefff13 | lightstep/util.py | lightstep/util.py | """ Utility functions
"""
import random
import time
from . import constants
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol = 'https://'
else:
protocol = 'http://'
return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary'])
def _generate_guid():
"""
Construct a guid - random 64 bit integer converted to a string.
"""
return str(random.getrandbits(64))
def _now_micros():
"""
Get the current time in microseconds since the epoch.
"""
return _time_to_micros(time.time())
def _time_to_micros(t):
"""
Convert a time.time()-style timestamp to microseconds.
"""
return long(round(t * constants.SECONDS_TO_MICRO))
def _merge_dicts(*dict_args):
"""Destructively merges dictionaries, returns None instead of an empty dictionary.
Elements of dict_args can be None.
Keys in latter dicts override those in earlier ones.
"""
result = {}
for dictionary in dict_args:
if dictionary:
result.update(dictionary)
return result if result else None
| """ Utility functions
"""
import random
import time
from . import constants
guid_rng = random.Random() # Uses urandom seed
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol = 'https://'
else:
protocol = 'http://'
return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary'])
def _generate_guid():
"""
Construct a guid - random 64 bit integer converted to a string.
"""
return str(guid_rng.getrandbits(64))
def _now_micros():
"""
Get the current time in microseconds since the epoch.
"""
return _time_to_micros(time.time())
def _time_to_micros(t):
"""
Convert a time.time()-style timestamp to microseconds.
"""
return long(round(t * constants.SECONDS_TO_MICRO))
def _merge_dicts(*dict_args):
"""Destructively merges dictionaries, returns None instead of an empty dictionary.
Elements of dict_args can be None.
Keys in latter dicts override those in earlier ones.
"""
result = {}
for dictionary in dict_args:
if dictionary:
result.update(dictionary)
return result if result else None
| Use a private RNG for guids. Avoids potential for trouble w/ the global instance. | Use a private RNG for guids. Avoids potential for trouble w/ the global instance.
| Python | mit | lightstephq/lightstep-tracer-python | ---
+++
@@ -3,6 +3,8 @@
import random
import time
from . import constants
+
+guid_rng = random.Random() # Uses urandom seed
def _service_url_from_hostport(secure, host, port):
"""
@@ -20,7 +22,7 @@
"""
Construct a guid - random 64 bit integer converted to a string.
"""
- return str(random.getrandbits(64))
+ return str(guid_rng.getrandbits(64))
def _now_micros():
""" |
64db9a503322ce1ee61c64afbdc38f367c3d6627 | guardian/testapp/tests/management_test.py | guardian/testapp/tests/management_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.management import create_anonymous_user
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(SimpleTestCase):
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
| from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
| Use unit test.TestCase instead of SimpleTestCase | Use unit test.TestCase instead of SimpleTestCase
| Python | bsd-2-clause | calvinpy/django-guardian,vovanbo/django-guardian,loop0/django-guardian,frwickst/django-guardian,thedrow/django-guardian,emperorcezar/django-guardian,alexshin/django-guardian,calvinpy/django-guardian,flisky/django-guardian,vitan/django-guardian,sustainingtechnologies/django-guardian,rfleschenberg/django-guardian,frwickst/django-guardian,alexshin/django-guardian,RDXT/django-guardian,lukaszb/django-guardian,benkonrath/django-guardian,brianmay/django-guardian,flisky/django-guardian,rmgorman/django-guardian,vitan/django-guardian,rmgorman/django-guardian,onaio/django-guardian,thedrow/django-guardian,alexshin/django-guardian,kostko/django-guardian,EnHatch/django-guardian,TailorDev/django-guardian,calvinpy/django-guardian,rfleschenberg/django-guardian,EnHatch/django-guardian,giocalitri/django-guardian,hunter007/django-guardian,sustainingtechnologies/django-guardian,brianmay/django-guardian,sindrig/django-guardian,RDXT/django-guardian,denilsonsa/django-guardian,sindrig/django-guardian,patgmiller/django-guardian,loop0/django-guardian,EnHatch/django-guardian,benkonrath/django-guardian,vovanbo/django-guardian,kostko/django-guardian,thedrow/django-guardian,EnHatch/django-guardian,benkonrath/django-guardian,loop0/django-guardian,vovanbo/django-guardian,giocalitri/django-guardian,onaio/django-guardian,TailorDev/django-guardian,patgmiller/django-guardian,patgmiller/django-guardian,vitan/django-guardian,sustainingtechnologies/django-guardian,haxo/django-guardian,frwickst/django-guardian,haxo/django-guardian,flisky/django-guardian,haxo/django-guardian,infoxchange/django-guardian,emperorcezar/django-guardian,denilsonsa/django-guardian,lukaszb/django-guardian,brianmay/django-guardian,thedrow/django-guardian,flisky/django-guardian,TailorDev/django-guardian,infoxchange/django-guardian,sustainingtechnologies/django-guardian,lukaszb/django-guardian,hunter007/django-guardian,onaio/django-guardian,emperorcezar/django-guardian,giocalitri/django-guardian,denilsonsa/django-guardian,infoxchange/django-guardian,emperorcezar/django-guardian,rmgorman/django-guardian,sindrig/django-guardian,kostko/django-guardian,rfleschenberg/django-guardian,loop0/django-guardian,kostko/django-guardian,RDXT/django-guardian,vitan/django-guardian,hunter007/django-guardian,denilsonsa/django-guardian,haxo/django-guardian | ---
+++
@@ -1,17 +1,19 @@
from __future__ import absolute_import
from __future__ import unicode_literals
-from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
+from guardian.compat import unittest
from guardian.management import create_anonymous_user
+import django
mocked_get_init_anon = mock.Mock()
-class TestGetAnonymousUser(SimpleTestCase):
+class TestGetAnonymousUser(unittest.TestCase):
+ @unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon' |
2e40bccd158d0dd3a8e741704f055dbe7a04e3a5 | heat/db/sqlalchemy/migrate_repo/manage.py | heat/db/sqlalchemy/migrate_repo/manage.py | #!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False')
| #!/usr/bin/env python
# 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 migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False')
| Add Apache 2.0 license to source file | Add Apache 2.0 license to source file
As per OpenStack licensing guide lines [1]:
[H102 H103] Newly contributed Source Code should be licensed under
the Apache 2.0 license.
[H104] Files with no code shouldn't contain any license header nor
comments, and must be left completely empty.
[1] http://docs.openstack.org/developer/hacking/#openstack-licensing
Change-Id: I82387fec7ac94001a6c2379321ebf1f2e3f40c12
| Python | apache-2.0 | openstack/heat,noironetworks/heat,openstack/heat,noironetworks/heat | ---
+++
@@ -1,4 +1,17 @@
#!/usr/bin/env python
+
+# 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 migrate.versioning.shell import main
if __name__ == '__main__': |
c10badab9b93eb021b1942475c681042292c182c | scrapi/harvesters/boise_state.py | scrapi/harvesters/boise_state.py | '''
Harvester for the ScholarWorks for the SHARE project
Example API call: http://scholarworks.boisestate.edu/do/oai/?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
long_name = 'ScholarWorks'
url = 'http://scholarworks.boisestate.edu'
base_url = 'http://scholarworks.boisestate.edu/do/oai/'
property_list = ['source', 'identifier', 'type', 'date', 'setSpec', 'publisher', 'rights', 'format']
timezone_granularity = True
| '''
Harvester for the ScholarWorks for the SHARE project
Example API call: http://scholarworks.boisestate.edu/do/oai/?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
long_name = 'Boise State University ScholarWorks'
url = 'http://scholarworks.boisestate.edu'
base_url = 'http://scholarworks.boisestate.edu/do/oai/'
property_list = ['source', 'identifier', 'type', 'date', 'setSpec', 'publisher', 'rights', 'format']
timezone_granularity = True
| Update longname for Boise state | Update longname for Boise state
| Python | apache-2.0 | CenterForOpenScience/scrapi,CenterForOpenScience/scrapi | ---
+++
@@ -10,7 +10,7 @@
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
- long_name = 'ScholarWorks'
+ long_name = 'Boise State University ScholarWorks'
url = 'http://scholarworks.boisestate.edu'
base_url = 'http://scholarworks.boisestate.edu/do/oai/' |
ac4f5451baaefd67392d9b908c9ccffc4083a9ad | fluidsynth/fluidsynth.py | fluidsynth/fluidsynth.py | from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
| from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")
| Change the LD search path | Change the LD search path
| Python | mit | paultag/python-fluidsynth | ---
+++
@@ -18,4 +18,4 @@
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
-C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
+C = ffi.dlopen("libfluidsynth.so.1") |
894060b4e4a59d1626cf2b9d80b5184371d79fb9 | mopidy/mixers/alsa.py | mopidy/mixers/alsa.py | import alsaaudio
from mopidy.mixers import BaseMixer
class AlsaMixer(BaseMixer):
"""
Mixer which uses the Advanced Linux Sound Architecture (ALSA) to control
volume.
"""
def __init__(self, *args, **kwargs):
super(AlsaMixer, self).__init__(*args, **kwargs)
self._mixer = alsaaudio.Mixer()
def _get_volume(self):
return self._mixer.getvolume()[0]
def _set_volume(self, volume):
self._mixer.setvolume(volume)
| import alsaaudio
import logging
from mopidy.mixers import BaseMixer
logger = logging.getLogger('mopidy.mixers.alsa')
class AlsaMixer(BaseMixer):
"""
Mixer which uses the Advanced Linux Sound Architecture (ALSA) to control
volume.
"""
def __init__(self, *args, **kwargs):
super(AlsaMixer, self).__init__(*args, **kwargs)
# A mixer named 'Master' does not always exist, so we fall back to
# using 'PCM'. If this turns out to be a bad solution, we should make
# it possible to override with a setting.
self._mixer = None
for mixer_name in (u'Master', u'PCM'):
if mixer_name in alsaaudio.mixers():
logger.info(u'Mixer in use: %s', mixer_name)
self._mixer = alsaaudio.Mixer(mixer_name)
break
assert self._mixer is not None
def _get_volume(self):
return self._mixer.getvolume()[0]
def _set_volume(self, volume):
self._mixer.setvolume(volume)
| Make AlsaMixer work on hosts without a mixer named 'Master' | Make AlsaMixer work on hosts without a mixer named 'Master'
| Python | apache-2.0 | tkem/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,vrs01/mopidy,dbrgn/mopidy,adamcik/mopidy,ali/mopidy,dbrgn/mopidy,hkariti/mopidy,bencevans/mopidy,mopidy/mopidy,swak/mopidy,glogiotatidis/mopidy,priestd09/mopidy,tkem/mopidy,abarisain/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,priestd09/mopidy,jodal/mopidy,hkariti/mopidy,dbrgn/mopidy,jmarsik/mopidy,dbrgn/mopidy,quartz55/mopidy,bacontext/mopidy,ali/mopidy,pacificIT/mopidy,mokieyue/mopidy,liamw9534/mopidy,bacontext/mopidy,jodal/mopidy,ZenithDK/mopidy,quartz55/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,jodal/mopidy,jcass77/mopidy,rawdlite/mopidy,mokieyue/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,SuperStarPL/mopidy,ali/mopidy,adamcik/mopidy,jmarsik/mopidy,mokieyue/mopidy,hkariti/mopidy,bencevans/mopidy,jmarsik/mopidy,bencevans/mopidy,mopidy/mopidy,ali/mopidy,vrs01/mopidy,bacontext/mopidy,woutervanwijk/mopidy,pacificIT/mopidy,woutervanwijk/mopidy,glogiotatidis/mopidy,adamcik/mopidy,swak/mopidy,diandiankan/mopidy,rawdlite/mopidy,ZenithDK/mopidy,quartz55/mopidy,tkem/mopidy,quartz55/mopidy,glogiotatidis/mopidy,kingosticks/mopidy,jcass77/mopidy,tkem/mopidy,vrs01/mopidy,priestd09/mopidy,swak/mopidy,kingosticks/mopidy,hkariti/mopidy,kingosticks/mopidy,diandiankan/mopidy,rawdlite/mopidy,swak/mopidy,bencevans/mopidy,diandiankan/mopidy,mokieyue/mopidy,abarisain/mopidy,bacontext/mopidy,mopidy/mopidy,rawdlite/mopidy,pacificIT/mopidy,jcass77/mopidy,liamw9534/mopidy,vrs01/mopidy,diandiankan/mopidy | ---
+++
@@ -1,6 +1,9 @@
import alsaaudio
+import logging
from mopidy.mixers import BaseMixer
+
+logger = logging.getLogger('mopidy.mixers.alsa')
class AlsaMixer(BaseMixer):
"""
@@ -10,7 +13,16 @@
def __init__(self, *args, **kwargs):
super(AlsaMixer, self).__init__(*args, **kwargs)
- self._mixer = alsaaudio.Mixer()
+ # A mixer named 'Master' does not always exist, so we fall back to
+ # using 'PCM'. If this turns out to be a bad solution, we should make
+ # it possible to override with a setting.
+ self._mixer = None
+ for mixer_name in (u'Master', u'PCM'):
+ if mixer_name in alsaaudio.mixers():
+ logger.info(u'Mixer in use: %s', mixer_name)
+ self._mixer = alsaaudio.Mixer(mixer_name)
+ break
+ assert self._mixer is not None
def _get_volume(self):
return self._mixer.getvolume()[0] |
4b0c8371bf08ff2d0c3f7c64dd5867d5732d3531 | doc/java/lang.py | doc/java/lang.py | import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._JThread.attach
attachAsDaemon = jpype._jthread._JThread.attachAsDaemon
detach = jpype._jthread._JThread.detach
class AutoCloseable:
""" Customizer for ``java.lang.AutoCloseable`` and ``java.io.Closeable``
This customizer adds support of the ``with`` operator to all Java
classes that implement the Java ``AutoCloseable`` interface.
Example:
.. code-block:: python
from java.nio.files import Files, Paths
with Files.newInputStream(Paths.get("foo")) as fd:
# operate on the input stream
# Input stream closes at the end of the block.
"""
...
| import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._JThread.attach
attachAsDaemon = jpype._jthread._JThread.attachAsDaemon
detach = jpype._jthread._JThread.detach
class AutoCloseable:
""" Customizer for ``java.lang.AutoCloseable`` and ``java.io.Closeable``
This customizer adds support of the ``with`` operator to all Java
classes that implement the Java ``AutoCloseable`` interface.
Example:
.. code-block:: python
from java.nio.file import Files, Paths
with Files.newInputStream(Paths.get("foo")) as fd:
# operate on the input stream
# Input stream closes at the end of the block.
"""
...
| Fix java.nio.file import in AutoCloseable example | Fix java.nio.file import in AutoCloseable example
| Python | apache-2.0 | originell/jpype,originell/jpype,originell/jpype,originell/jpype,originell/jpype | ---
+++
@@ -25,7 +25,7 @@
.. code-block:: python
- from java.nio.files import Files, Paths
+ from java.nio.file import Files, Paths
with Files.newInputStream(Paths.get("foo")) as fd:
# operate on the input stream
|
ffc3bec9d488135ba2331386cec3279283927217 | bamp/helpers/ui.py | bamp/helpers/ui.py | import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results are returned to the caller.
"""
@wraps(func)
def wrapper(*args, **kwargs):
result, errors = func(*args, **kwargs)
if result: # call succeeded
return result, errors
# call returned error
error_exit(errors)
return wrapper
def _echo_exit(messages, exit_, color):
"""Iterate over list of messages and print them using passed color.
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
:type messages: list(str)
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
:type color: str
"""
for m in messages:
click.secho(m, fg=color)
if exit_:
sys.exit(exit_)
error_exit = partial(_echo_exit, exit_=1, color='red')
ok_exit = partial(_echo_exit, exit_=0, color='green')
| import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results are returned to the caller.
"""
@wraps(func)
def wrapper(*args, **kwargs):
result, errors = func(*args, **kwargs)
if result: # call succeeded
return result, errors
# call returned error
error_exit(errors)
return wrapper
def _echo_exit(messages, exit_, color):
"""Iterate over list of messages and print them using passed color.
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
:type messages: list(str) or str
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
:type color: str
"""
if isinstance(messages, str):
messages = [messages]
for m in messages:
click.secho(m, fg=color)
if exit_:
sys.exit(exit_)
error_exit = partial(_echo_exit, exit_=1, color='red')
ok_exit = partial(_echo_exit, exit_=0, color='green')
| Enable passing str to echo | Enable passing str to echo
| Python | mit | inirudebwoy/bamp | ---
+++
@@ -27,13 +27,16 @@
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
- :type messages: list(str)
+ :type messages: list(str) or str
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
:type color: str
"""
+ if isinstance(messages, str):
+ messages = [messages]
+
for m in messages:
click.secho(m, fg=color)
if exit_: |
3504b4f3687fdf3ac52d6d7df9306519762900a7 | ndaparser/__init__.py | ndaparser/__init__.py | import ndaparser
if __name__ == "__main__" :
trns = ndaparser.parseLine("T10188000060SCTSZFW3GT3WU1B 1501131501131501121710Viitemaksu +000000000000002800 HAKKERI HEIKKI HOKSAAVA A 00000000000000111012 ")
print(trns)
| import ndaparser
if __name__ == "__main__" :
transactions = [];
with open("./testdata.nda") as f:
for line in f:
transaction = ndaparser.parseLine(line)
if transaction is not None:
transactions.append(transaction)
for transaction in transactions:
print(transaction)
| Read testdata from file, print valid transactions | Read testdata from file, print valid transactions
| Python | mit | rambo/asylum,hacklab-fi/asylum,ojousima/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,ojousima/asylum,ojousima/asylum,jautero/asylum,rambo/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,ojousima/asylum,jautero/asylum,jautero/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum | ---
+++
@@ -1,5 +1,11 @@
import ndaparser
if __name__ == "__main__" :
- trns = ndaparser.parseLine("T10188000060SCTSZFW3GT3WU1B 1501131501131501121710Viitemaksu +000000000000002800 HAKKERI HEIKKI HOKSAAVA A 00000000000000111012 ")
- print(trns)
+ transactions = [];
+ with open("./testdata.nda") as f:
+ for line in f:
+ transaction = ndaparser.parseLine(line)
+ if transaction is not None:
+ transactions.append(transaction)
+ for transaction in transactions:
+ print(transaction) |
087925b336794b71675b31b70f845042e1f635fb | metro_accounts/metro_account.py | metro_accounts/metro_account.py | # -*- coding: utf-8 -*-
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | # -*- coding: utf-8 -*-
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
'''
Update SQL:
update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
'''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | Add the SQL to update account balance direction field bal_direct | Add the SQL to update account balance direction field bal_direct
| Python | agpl-3.0 | 837278709/metro-openerp,john-wang-metro/metro-openerp,john-wang-metro/metro-openerp,837278709/metro-openerp,837278709/metro-openerp,john-wang-metro/metro-openerp | ---
+++
@@ -12,5 +12,10 @@
('c', 'Credit'),
], 'Balance Direction',)
}
+'''
+Update SQL:
+update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
+update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
+'''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
82b78ed248f28709b6603315bd673337e4997c4e | pseudorandom.py | pseudorandom.py | #!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
request.headers['Content-Type'] == 'text/plain'):
return make_response((u"{0}\n".format(get_full_name()), 200,
{'Content-Type': 'text/plain'}))
else:
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| #!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
content_type = request.headers.get('Content-Type', '')
browser = request.headers.get('User-Agent', '').lower()
if browser[:4] in ('curl', 'wget') and content_type in ('text/plain', ''):
return make_response((u"{0}\n".format(get_full_name()), 200,
{'Content-Type': 'text/plain'}))
else:
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Send text to wget/curl unless html content-type | Send text to wget/curl unless html content-type
| Python | mit | treyhunner/pseudorandom.name,treyhunner/pseudorandom.name | ---
+++
@@ -9,8 +9,9 @@
@app.route("/")
def index():
- if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
- request.headers['Content-Type'] == 'text/plain'):
+ content_type = request.headers.get('Content-Type', '')
+ browser = request.headers.get('User-Agent', '').lower()
+ if browser[:4] in ('curl', 'wget') and content_type in ('text/plain', ''):
return make_response((u"{0}\n".format(get_full_name()), 200,
{'Content-Type': 'text/plain'}))
else: |
7b9233c157630733da688abb7c0f3fffecddd0e7 | scripts/lib/getUserPath.py | scripts/lib/getUserPath.py | def getUserPath(filename, is_command):
import lib.app, os
# Places quotation marks around the full path, to handle cases where the user-specified path / file name contains spaces
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the expected output is a stand-alone string, the quotation marks should be omitted
wrapper=''
if is_command and filename.count(' '):
wrapper='\"'
return wrapper + os.path.abspath(os.path.join(lib.app.workingDir, filename)) + wrapper
| def getUserPath(filename, is_command):
import lib.app, os
# Places quotation marks around the full path, to handle cases where the user-specified path / file name contains spaces
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the expected output is a stand-alone string, the quotation marks should be omitted
wrapper=''
if is_command and (filename.count(' ') or lib.app.workingDir(' ')):
wrapper='\"'
return wrapper + os.path.abspath(os.path.join(lib.app.workingDir, filename)) + wrapper
| Fix for working directory containing whitespace | Scripts: Fix for working directory containing whitespace
| Python | mpl-2.0 | MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3 | ---
+++
@@ -4,7 +4,7 @@
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the expected output is a stand-alone string, the quotation marks should be omitted
wrapper=''
- if is_command and filename.count(' '):
+ if is_command and (filename.count(' ') or lib.app.workingDir(' ')):
wrapper='\"'
return wrapper + os.path.abspath(os.path.join(lib.app.workingDir, filename)) + wrapper
|
4c4fd3021931e2203088a2ec578eb479a622e2c5 | blogsite/models.py | blogsite/models.py | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
"""
# Columns
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128))
body = db.Column(db.String(4096))
def __init__(self, title, body):
"""Constructor for Post.
Parameters
----------
title : String
Title/Summary of post
body : String
Contents
"""
self.title = title
self.body = body
def __repr__(self):
"""Representation."""
return '<Post %r:%r>' % (self.id, self.title)
| """Collection of Models used in blogsite."""
from . import db
from datetime import datetime
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
pub_date : SQLAlchemy.Column
Date and Time of Post creation
category_id : SQLAlchemy.Column
Foreign Key ID to Category
category : SQLAlchemy.relationship
Category object that relates to this Post
"""
# Columns
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128))
body = db.Column(db.String(4096))
pub_date = db.Column(db.DateTime)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
category = db.relationship('Category',
backref=db.backref('posts', lazy='dynamic'))
def __init__(self, title, body, category, pub_date=None):
"""Constructor for Post.
Parameters
----------
title : String
Title/Summary of post
body : String
Contents
category : Category
Category object blog post is related to
pub_date : DateTime
Optional
"""
self.title = title
self.body = body
self.category = category
if pub_date is None:
pub_date = datetime.utcnow()
self.pub_date = pub_date
def __repr__(self):
"""Representation."""
return '<Post %r:%r>' % (self.id, self.title)
class Category(db.Model):
"""Model to represent a overall category.
Attributes
----------
id : SQLAlchemy.Column
name : SQLAlchemy.Column
"""
# Columns
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(128))
def __init__(self, name):
"""Constructor for Category.
Parameters
----------
name : String
Name of new category
"""
self.name = name
def __repr__(self):
"""Representation."""
return '<Category %r>' % self.name
| Add Category model and expanding Post model. | Add Category model and expanding Post model.
Post model now contains a publish date and a foreign key reference
to the Category model.
| Python | mit | paulaylingdev/blogsite,paulaylingdev/blogsite | ---
+++
@@ -1,5 +1,6 @@
"""Collection of Models used in blogsite."""
from . import db
+from datetime import datetime
class Post(db.Model):
@@ -11,14 +12,24 @@
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
+ pub_date : SQLAlchemy.Column
+ Date and Time of Post creation
+ category_id : SQLAlchemy.Column
+ Foreign Key ID to Category
+ category : SQLAlchemy.relationship
+ Category object that relates to this Post
"""
# Columns
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128))
body = db.Column(db.String(4096))
+ pub_date = db.Column(db.DateTime)
+ category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
+ category = db.relationship('Category',
+ backref=db.backref('posts', lazy='dynamic'))
- def __init__(self, title, body):
+ def __init__(self, title, body, category, pub_date=None):
"""Constructor for Post.
Parameters
@@ -27,10 +38,46 @@
Title/Summary of post
body : String
Contents
+ category : Category
+ Category object blog post is related to
+ pub_date : DateTime
+ Optional
"""
self.title = title
self.body = body
+ self.category = category
+ if pub_date is None:
+ pub_date = datetime.utcnow()
+ self.pub_date = pub_date
def __repr__(self):
"""Representation."""
return '<Post %r:%r>' % (self.id, self.title)
+
+
+class Category(db.Model):
+ """Model to represent a overall category.
+
+ Attributes
+ ----------
+ id : SQLAlchemy.Column
+ name : SQLAlchemy.Column
+ """
+
+ # Columns
+ id = db.Column(db.Integer, primary_key=True, autoincrement=True)
+ name = db.Column(db.String(128))
+
+ def __init__(self, name):
+ """Constructor for Category.
+
+ Parameters
+ ----------
+ name : String
+ Name of new category
+ """
+ self.name = name
+
+ def __repr__(self):
+ """Representation."""
+ return '<Category %r>' % self.name |
d7621f5bf2e1ae30f79d1701fe5e34ee60da1a53 | go/api/go_api/tests/test_client.py | go/api/go_api/tests/test_client.py | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_request(self, mock_req):
client.request('123', 'lorem ipsum', 'GET')
mock_req.assert_called_with(
'GET',
settings.GO_API_URL,
auth=('session_id', '123'),
data='lorem ipsum')
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_req.assert_called_with(
'POST',
settings.GO_API_URL,
auth=('session_id', '123'),
data=json.dumps({
'jsonrpc': '2.0',
'id': 'abc',
'params': ['foo', 'bar'],
'method': 'do_something',
}))
| import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_req.assert_called_with(
'POST',
settings.GO_API_URL,
auth=('session_id', '123'),
data=json.dumps({
'jsonrpc': '2.0',
'id': 'abc',
'params': ['foo', 'bar'],
'method': 'do_something',
}))
| Remove a test that is no longer relevant | Remove a test that is no longer relevant
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -9,16 +9,6 @@
class ClientTestCase(TestCase):
- @patch('requests.request')
- def test_request(self, mock_req):
- client.request('123', 'lorem ipsum', 'GET')
-
- mock_req.assert_called_with(
- 'GET',
- settings.GO_API_URL,
- auth=('session_id', '123'),
- data='lorem ipsum')
-
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc') |
f85bcd07f34f817722b6a5af317e9dbfa2667576 | mysite/search/tasks/__init__.py | mysite/search/tasks/__init__.py | from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
run_every = timedelta(days=1)
def run(self, **kwargs):
logger = self.get_logger(**kwargs)
for lp_project in lpproj2ohproj:
openhatch_proj = lpproj2ohproj[lp_project]
logger.info("Started to grab lp.net bugs for %s into %s" % (
lp_project, openhatch_proj))
grab_lp_bugs(lp_project=lp_project,
openhatch_project=openhatch_project)
class GrabMiroBugs(PeriodicTask):
run_every = timedelta(days=1)
def run(self, **kwargs):
logger = self.get_logger(**kwargs)
logger.info("Started to grab Miro bitesized bugs")
mysite.customs.miro.grab_miro_bugs()
tasks.register(GrabMiroBugs)
tasks.register(GrabLaunchpadBugs)
| from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
run_every = timedelta(days=1)
def run(self, **kwargs):
logger = self.get_logger(**kwargs)
for lp_project in lpproj2ohproj:
openhatch_proj = lpproj2ohproj[lp_project]
logger.info("Started to grab lp.net bugs for %s into %s" % (
lp_project, openhatch_proj))
grab_lp_bugs(lp_project=lp_project,
openhatch_project=openhatch_proj)
class GrabMiroBugs(PeriodicTask):
run_every = timedelta(days=1)
def run(self, **kwargs):
logger = self.get_logger(**kwargs)
logger.info("Started to grab Miro bitesized bugs")
mysite.customs.miro.grab_miro_bugs()
tasks.register(GrabMiroBugs)
tasks.register(GrabLaunchpadBugs)
| Fix the same typo in GrabLaunchpadBugs | Fix the same typo in GrabLaunchpadBugs
| Python | agpl-3.0 | moijes12/oh-mainline,sudheesh001/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,campbe13/openhatch,campbe13/openhatch,openhatch/oh-mainline,SnappleCap/oh-mainline,nirmeshk/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,heeraj123/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,nirmeshk/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,ehashman/oh-mainline,SnappleCap/oh-mainline,heeraj123/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,campbe13/openhatch,moijes12/oh-mainline,jledbetter/openhatch,ojengwa/oh-mainline,heeraj123/oh-mainline,mzdaniel/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,vipul-sharma20/oh-mainline,jledbetter/openhatch,ojengwa/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,SnappleCap/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,Changaco/oh-mainline,willingc/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,jledbetter/openhatch,willingc/oh-mainline,waseem18/oh-mainline,openhatch/oh-mainline,openhatch/oh-mainline,willingc/oh-mainline,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,waseem18/oh-mainline,heeraj123/oh-mainline,jledbetter/openhatch,moijes12/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,Changaco/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,Changaco/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,moijes12/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,jledbetter/openhatch,vipul-sharma20/oh-mainline | ---
+++
@@ -14,7 +14,7 @@
logger.info("Started to grab lp.net bugs for %s into %s" % (
lp_project, openhatch_proj))
grab_lp_bugs(lp_project=lp_project,
- openhatch_project=openhatch_project)
+ openhatch_project=openhatch_proj)
class GrabMiroBugs(PeriodicTask): |
279f0b984209f27743791aca9cf3da7941e5d520 | zephyr/lib/minify.py | zephyr/lib/minify.py | from django.conf import settings
from hashlib import sha1
from os import path
from pipeline.compressors import SubProcessCompressor
class ClosureSourceMapCompressor(SubProcessCompressor):
def compress_js(self, js):
# js is the full text of the JavaScript source, and we can't
# easily get either the input file names or the output file
# name. So we just pick a unique arbitrary name. This is
# okay because we can figure out from the source map file
# contents which JavaScript files it corresponds to.
source_map = path.join(settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR,
sha1(js).hexdigest() + '.map')
command = '%s --create_source_map %s' % (
settings.PIPELINE_CLOSURE_BINARY, source_map)
return self.execute_command(command, js)
| from django.conf import settings
from hashlib import sha1
from os import path
from pipeline.compressors import SubProcessCompressor
class ClosureSourceMapCompressor(SubProcessCompressor):
def compress_js(self, js):
# js is the full text of the JavaScript source, and we can't
# easily get either the input file names or the output file
# name. So we just pick a unique arbitrary name. This is
# okay because we can figure out from the source map file
# contents which JavaScript files it corresponds to.
# As a hack to make things easier, assume that any large input
# corresponds to app.js. This is like 60 times bigger than
# any other input file, at present.
if len(js) > 100000:
source_map_name = 'app.js.map'
else:
source_map_name = sha1(js).hexdigest() + '.map'
source_map = path.join(
settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, source_map_name)
command = '%s --create_source_map %s' % (
settings.PIPELINE_CLOSURE_BINARY, source_map)
return self.execute_command(command, js)
| Make it easier to find the source map for app.js | Make it easier to find the source map for app.js
(imported from commit bca27c9838573fb4b74e2d269b253a48702c9e1c)
| Python | apache-2.0 | gigawhitlocks/zulip,hayderimran7/zulip,dhcrzf/zulip,jackrzhang/zulip,MariaFaBella85/zulip,verma-varsha/zulip,esander91/zulip,jonesgithub/zulip,johnnygaddarr/zulip,hackerkid/zulip,joshisa/zulip,Frouk/zulip,arpitpanwar/zulip,qq1012803704/zulip,dawran6/zulip,RobotCaleb/zulip,wavelets/zulip,qq1012803704/zulip,jerryge/zulip,isht3/zulip,itnihao/zulip,hj3938/zulip,ufosky-server/zulip,yuvipanda/zulip,pradiptad/zulip,adnanh/zulip,xuanhan863/zulip,ahmadassaf/zulip,jimmy54/zulip,MariaFaBella85/zulip,dattatreya303/zulip,timabbott/zulip,he15his/zulip,ryanbackman/zulip,Drooids/zulip,PaulPetring/zulip,yocome/zulip,JanzTam/zulip,karamcnair/zulip,j831/zulip,atomic-labs/zulip,rht/zulip,Cheppers/zulip,sharmaeklavya2/zulip,Vallher/zulip,moria/zulip,paxapy/zulip,wangdeshui/zulip,m1ssou/zulip,dwrpayne/zulip,vikas-parashar/zulip,christi3k/zulip,amyliu345/zulip,andersk/zulip,xuxiao/zulip,moria/zulip,bluesea/zulip,aakash-cr7/zulip,aps-sids/zulip,jerryge/zulip,so0k/zulip,cosmicAsymmetry/zulip,Diptanshu8/zulip,vaidap/zulip,PaulPetring/zulip,developerfm/zulip,blaze225/zulip,vikas-parashar/zulip,Qgap/zulip,kou/zulip,PhilSk/zulip,hj3938/zulip,hafeez3000/zulip,paxapy/zulip,ahmadassaf/zulip,andersk/zulip,KingxBanana/zulip,wangdeshui/zulip,proliming/zulip,ufosky-server/zulip,dwrpayne/zulip,hengqujushi/zulip,susansls/zulip,praveenaki/zulip,gigawhitlocks/zulip,DazWorrall/zulip,huangkebo/zulip,technicalpickles/zulip,thomasboyt/zulip,levixie/zulip,guiquanz/zulip,Qgap/zulip,avastu/zulip,yocome/zulip,guiquanz/zulip,umkay/zulip,saitodisse/zulip,mansilladev/zulip,JanzTam/zulip,Jianchun1/zulip,amanharitsh123/zulip,hj3938/zulip,Frouk/zulip,pradiptad/zulip,zofuthan/zulip,dwrpayne/zulip,xuanhan863/zulip,hackerkid/zulip,cosmicAsymmetry/zulip,huangkebo/zulip,kaiyuanheshang/zulip,hafeez3000/zulip,luyifan/zulip,bitemyapp/zulip,adnanh/zulip,jessedhillon/zulip,praveenaki/zulip,xuanhan863/zulip,noroot/zulip,armooo/zulip,reyha/zulip,sharmaeklavya2/zulip,armooo/zulip,verma-varsha/zulip,Batterfii/zulip,suxinde2009/zulip,KingxBanana/zulip,eastlhu/zulip,willingc/zulip,peguin40/zulip,samatdav/zulip,AZtheAsian/zulip,aakash-cr7/zulip,tbutter/zulip,ryansnowboarder/zulip,johnnygaddarr/zulip,stamhe/zulip,atomic-labs/zulip,guiquanz/zulip,dwrpayne/zulip,codeKonami/zulip,ericzhou2008/zulip,amanharitsh123/zulip,SmartPeople/zulip,stamhe/zulip,dwrpayne/zulip,ikasumiwt/zulip,aps-sids/zulip,amallia/zulip,ufosky-server/zulip,voidException/zulip,eeshangarg/zulip,hayderimran7/zulip,karamcnair/zulip,zacps/zulip,dawran6/zulip,sup95/zulip,yuvipanda/zulip,karamcnair/zulip,ericzhou2008/zulip,dattatreya303/zulip,hafeez3000/zulip,shrikrishnaholla/zulip,joshisa/zulip,mohsenSy/zulip,udxxabp/zulip,swinghu/zulip,jeffcao/zulip,ipernet/zulip,peiwei/zulip,vakila/zulip,esander91/zulip,jainayush975/zulip,stamhe/zulip,amyliu345/zulip,niftynei/zulip,KJin99/zulip,guiquanz/zulip,babbage/zulip,shrikrishnaholla/zulip,saitodisse/zulip,Frouk/zulip,m1ssou/zulip,amallia/zulip,KJin99/zulip,babbage/zulip,codeKonami/zulip,levixie/zulip,he15his/zulip,johnnygaddarr/zulip,he15his/zulip,swinghu/zulip,sonali0901/zulip,akuseru/zulip,ryansnowboarder/zulip,tdr130/zulip,dxq-git/zulip,MariaFaBella85/zulip,j831/zulip,zacps/zulip,zofuthan/zulip,joshisa/zulip,natanovia/zulip,vaidap/zulip,tdr130/zulip,thomasboyt/zulip,deer-hope/zulip,dxq-git/zulip,aliceriot/zulip,noroot/zulip,noroot/zulip,wdaher/zulip,souravbadami/zulip,andersk/zulip,ApsOps/zulip,andersk/zulip,susansls/zulip,PaulPetring/zulip,jainayush975/zulip,KJin99/zulip,peguin40/zulip,glovebx/zulip,sup95/zulip,vaidap/zulip,SmartPeople/zulip,zacps/zulip,EasonYi/zulip,schatt/zulip,zachallaun/zulip,jonesgithub/zulip,synicalsyntax/zulip,zofuthan/zulip,wavelets/zulip,vabs22/zulip,armooo/zulip,AZtheAsian/zulip,jphilipsen05/zulip,eastlhu/zulip,JPJPJPOPOP/zulip,lfranchi/zulip,j831/zulip,aakash-cr7/zulip,zwily/zulip,Suninus/zulip,voidException/zulip,udxxabp/zulip,technicalpickles/zulip,krtkmj/zulip,zorojean/zulip,voidException/zulip,jerryge/zulip,rishig/zulip,arpitpanwar/zulip,hackerkid/zulip,glovebx/zulip,bitemyapp/zulip,so0k/zulip,LeeRisk/zulip,MayB/zulip,bowlofstew/zulip,mansilladev/zulip,KJin99/zulip,alliejones/zulip,reyha/zulip,MayB/zulip,gigawhitlocks/zulip,grave-w-grave/zulip,dnmfarrell/zulip,jeffcao/zulip,lfranchi/zulip,hafeez3000/zulip,Juanvulcano/zulip,dxq-git/zulip,timabbott/zulip,fw1121/zulip,dxq-git/zulip,saitodisse/zulip,jackrzhang/zulip,eeshangarg/zulip,krtkmj/zulip,sharmaeklavya2/zulip,hackerkid/zulip,synicalsyntax/zulip,rht/zulip,bastianh/zulip,mdavid/zulip,tdr130/zulip,dwrpayne/zulip,suxinde2009/zulip,brockwhittaker/zulip,ikasumiwt/zulip,Frouk/zulip,Gabriel0402/zulip,Jianchun1/zulip,arpith/zulip,umkay/zulip,christi3k/zulip,tommyip/zulip,thomasboyt/zulip,dotcool/zulip,ufosky-server/zulip,swinghu/zulip,Qgap/zulip,showell/zulip,LeeRisk/zulip,johnnygaddarr/zulip,pradiptad/zulip,arpitpanwar/zulip,zofuthan/zulip,aakash-cr7/zulip,wangdeshui/zulip,easyfmxu/zulip,zulip/zulip,Galexrt/zulip,yocome/zulip,johnnygaddarr/zulip,sonali0901/zulip,Cheppers/zulip,proliming/zulip,Juanvulcano/zulip,peguin40/zulip,jeffcao/zulip,developerfm/zulip,saitodisse/zulip,itnihao/zulip,arpith/zulip,gkotian/zulip,shrikrishnaholla/zulip,technicalpickles/zulip,tommyip/zulip,rishig/zulip,wavelets/zulip,JanzTam/zulip,bastianh/zulip,punchagan/zulip,developerfm/zulip,Qgap/zulip,schatt/zulip,Suninus/zulip,ashwinirudrappa/zulip,jeffcao/zulip,tommyip/zulip,dhcrzf/zulip,noroot/zulip,tbutter/zulip,praveenaki/zulip,Diptanshu8/zulip,MayB/zulip,paxapy/zulip,bluesea/zulip,suxinde2009/zulip,xuanhan863/zulip,brainwane/zulip,arpitpanwar/zulip,xuxiao/zulip,christi3k/zulip,esander91/zulip,zorojean/zulip,pradiptad/zulip,schatt/zulip,firstblade/zulip,KingxBanana/zulip,tommyip/zulip,JPJPJPOPOP/zulip,zachallaun/zulip,adnanh/zulip,eeshangarg/zulip,developerfm/zulip,nicholasbs/zulip,jerryge/zulip,ahmadassaf/zulip,timabbott/zulip,seapasulli/zulip,zorojean/zulip,ApsOps/zulip,synicalsyntax/zulip,sharmaeklavya2/zulip,wweiradio/zulip,MariaFaBella85/zulip,PaulPetring/zulip,codeKonami/zulip,swinghu/zulip,Gabriel0402/zulip,dattatreya303/zulip,timabbott/zulip,bssrdf/zulip,ipernet/zulip,Galexrt/zulip,Qgap/zulip,peguin40/zulip,jphilipsen05/zulip,jonesgithub/zulip,saitodisse/zulip,jrowan/zulip,yocome/zulip,ashwinirudrappa/zulip,pradiptad/zulip,Batterfii/zulip,eeshangarg/zulip,bssrdf/zulip,eastlhu/zulip,deer-hope/zulip,blaze225/zulip,DazWorrall/zulip,udxxabp/zulip,vakila/zulip,sup95/zulip,souravbadami/zulip,punchagan/zulip,huangkebo/zulip,natanovia/zulip,moria/zulip,joshisa/zulip,vikas-parashar/zulip,thomasboyt/zulip,adnanh/zulip,andersk/zulip,zulip/zulip,nicholasbs/zulip,amallia/zulip,firstblade/zulip,reyha/zulip,themass/zulip,tbutter/zulip,shaunstanislaus/zulip,jeffcao/zulip,shrikrishnaholla/zulip,verma-varsha/zulip,synicalsyntax/zulip,vabs22/zulip,JanzTam/zulip,vikas-parashar/zulip,DazWorrall/zulip,guiquanz/zulip,fw1121/zulip,bluesea/zulip,shaunstanislaus/zulip,sup95/zulip,isht3/zulip,easyfmxu/zulip,krtkmj/zulip,akuseru/zulip,udxxabp/zulip,punchagan/zulip,akuseru/zulip,noroot/zulip,adnanh/zulip,nicholasbs/zulip,easyfmxu/zulip,Diptanshu8/zulip,Jianchun1/zulip,schatt/zulip,jimmy54/zulip,umkay/zulip,showell/zulip,hackerkid/zulip,synicalsyntax/zulip,AZtheAsian/zulip,isht3/zulip,he15his/zulip,jerryge/zulip,xuxiao/zulip,themass/zulip,Frouk/zulip,johnny9/zulip,jackrzhang/zulip,isht3/zulip,bastianh/zulip,calvinleenyc/zulip,zulip/zulip,amanharitsh123/zulip,eastlhu/zulip,lfranchi/zulip,punchagan/zulip,mohsenSy/zulip,fw1121/zulip,blaze225/zulip,itnihao/zulip,ashwinirudrappa/zulip,tdr130/zulip,qq1012803704/zulip,sup95/zulip,jessedhillon/zulip,ericzhou2008/zulip,jonesgithub/zulip,noroot/zulip,gkotian/zulip,glovebx/zulip,LAndreas/zulip,glovebx/zulip,PaulPetring/zulip,alliejones/zulip,rishig/zulip,verma-varsha/zulip,peiwei/zulip,peiwei/zulip,hengqujushi/zulip,seapasulli/zulip,grave-w-grave/zulip,DazWorrall/zulip,kaiyuanheshang/zulip,reyha/zulip,hayderimran7/zulip,gigawhitlocks/zulip,dxq-git/zulip,KingxBanana/zulip,showell/zulip,zorojean/zulip,grave-w-grave/zulip,lfranchi/zulip,mohsenSy/zulip,SmartPeople/zulip,kokoar/zulip,fw1121/zulip,wdaher/zulip,zulip/zulip,mansilladev/zulip,thomasboyt/zulip,wweiradio/zulip,wavelets/zulip,atomic-labs/zulip,jessedhillon/zulip,souravbadami/zulip,hayderimran7/zulip,jainayush975/zulip,thomasboyt/zulip,blaze225/zulip,dxq-git/zulip,punchagan/zulip,dhcrzf/zulip,mdavid/zulip,aliceriot/zulip,bluesea/zulip,aakash-cr7/zulip,dnmfarrell/zulip,Frouk/zulip,jimmy54/zulip,Suninus/zulip,avastu/zulip,shaunstanislaus/zulip,ufosky-server/zulip,alliejones/zulip,Galexrt/zulip,peguin40/zulip,ikasumiwt/zulip,avastu/zulip,ashwinirudrappa/zulip,pradiptad/zulip,JPJPJPOPOP/zulip,moria/zulip,ahmadassaf/zulip,Vallher/zulip,joyhchen/zulip,bastianh/zulip,andersk/zulip,bastianh/zulip,levixie/zulip,kokoar/zulip,kaiyuanheshang/zulip,ryansnowboarder/zulip,Vallher/zulip,brockwhittaker/zulip,yuvipanda/zulip,ashwinirudrappa/zulip,showell/zulip,KJin99/zulip,brainwane/zulip,grave-w-grave/zulip,technicalpickles/zulip,LeeRisk/zulip,zachallaun/zulip,JPJPJPOPOP/zulip,jonesgithub/zulip,RobotCaleb/zulip,LeeRisk/zulip,calvinleenyc/zulip,PaulPetring/zulip,hackerkid/zulip,eeshangarg/zulip,developerfm/zulip,dotcool/zulip,samatdav/zulip,proliming/zulip,aps-sids/zulip,ahmadassaf/zulip,developerfm/zulip,mahim97/zulip,isht3/zulip,johnnygaddarr/zulip,alliejones/zulip,zulip/zulip,littledogboy/zulip,synicalsyntax/zulip,SmartPeople/zulip,aliceriot/zulip,atomic-labs/zulip,zwily/zulip,Diptanshu8/zulip,hengqujushi/zulip,shubhamdhama/zulip,hayderimran7/zulip,bitemyapp/zulip,ipernet/zulip,LeeRisk/zulip,johnny9/zulip,kou/zulip,tiansiyuan/zulip,susansls/zulip,joshisa/zulip,dattatreya303/zulip,Drooids/zulip,kou/zulip,TigorC/zulip,themass/zulip,zorojean/zulip,j831/zulip,nicholasbs/zulip,armooo/zulip,aps-sids/zulip,dnmfarrell/zulip,LAndreas/zulip,tdr130/zulip,shaunstanislaus/zulip,bowlofstew/zulip,alliejones/zulip,brockwhittaker/zulip,qq1012803704/zulip,johnny9/zulip,bluesea/zulip,littledogboy/zulip,zwily/zulip,MariaFaBella85/zulip,voidException/zulip,esander91/zulip,suxinde2009/zulip,eastlhu/zulip,Jianchun1/zulip,Galexrt/zulip,gigawhitlocks/zulip,niftynei/zulip,zulip/zulip,mahim97/zulip,zwily/zulip,zwily/zulip,wdaher/zulip,qq1012803704/zulip,gigawhitlocks/zulip,mahim97/zulip,hj3938/zulip,bowlofstew/zulip,AZtheAsian/zulip,bitemyapp/zulip,kou/zulip,ahmadassaf/zulip,tdr130/zulip,ericzhou2008/zulip,fw1121/zulip,ikasumiwt/zulip,yuvipanda/zulip,he15his/zulip,ryansnowboarder/zulip,PhilSk/zulip,jrowan/zulip,Batterfii/zulip,tdr130/zulip,Drooids/zulip,paxapy/zulip,arpitpanwar/zulip,tiansiyuan/zulip,luyifan/zulip,huangkebo/zulip,reyha/zulip,natanovia/zulip,ericzhou2008/zulip,zacps/zulip,TigorC/zulip,xuanhan863/zulip,mansilladev/zulip,bitemyapp/zulip,vakila/zulip,joshisa/zulip,TigorC/zulip,dotcool/zulip,suxinde2009/zulip,yocome/zulip,aps-sids/zulip,krtkmj/zulip,Batterfii/zulip,wangdeshui/zulip,nicholasbs/zulip,jackrzhang/zulip,gkotian/zulip,MayB/zulip,bowlofstew/zulip,dattatreya303/zulip,nicholasbs/zulip,wavelets/zulip,hustlzp/zulip,jessedhillon/zulip,hj3938/zulip,moria/zulip,avastu/zulip,xuxiao/zulip,Cheppers/zulip,bitemyapp/zulip,willingc/zulip,KJin99/zulip,joyhchen/zulip,firstblade/zulip,zwily/zulip,ikasumiwt/zulip,EasonYi/zulip,zhaoweigg/zulip,amyliu345/zulip,amallia/zulip,susansls/zulip,cosmicAsymmetry/zulip,sonali0901/zulip,jrowan/zulip,voidException/zulip,wangdeshui/zulip,deer-hope/zulip,grave-w-grave/zulip,ikasumiwt/zulip,akuseru/zulip,gigawhitlocks/zulip,arpitpanwar/zulip,jrowan/zulip,jphilipsen05/zulip,tommyip/zulip,zacps/zulip,amallia/zulip,gkotian/zulip,christi3k/zulip,ryanbackman/zulip,shrikrishnaholla/zulip,KJin99/zulip,Jianchun1/zulip,lfranchi/zulip,jainayush975/zulip,jackrzhang/zulip,ipernet/zulip,voidException/zulip,lfranchi/zulip,luyifan/zulip,saitodisse/zulip,hj3938/zulip,yuvipanda/zulip,Suninus/zulip,EasonYi/zulip,brainwane/zulip,aps-sids/zulip,TigorC/zulip,littledogboy/zulip,dhcrzf/zulip,arpith/zulip,ahmadassaf/zulip,developerfm/zulip,stamhe/zulip,glovebx/zulip,bssrdf/zulip,Diptanshu8/zulip,kou/zulip,dotcool/zulip,hengqujushi/zulip,praveenaki/zulip,Qgap/zulip,kokoar/zulip,esander91/zulip,Juanvulcano/zulip,j831/zulip,amyliu345/zulip,firstblade/zulip,fw1121/zulip,firstblade/zulip,krtkmj/zulip,susansls/zulip,amyliu345/zulip,bowlofstew/zulip,luyifan/zulip,levixie/zulip,he15his/zulip,ericzhou2008/zulip,dnmfarrell/zulip,zwily/zulip,brockwhittaker/zulip,willingc/zulip,rht/zulip,babbage/zulip,littledogboy/zulip,arpitpanwar/zulip,timabbott/zulip,suxinde2009/zulip,joyhchen/zulip,xuxiao/zulip,shrikrishnaholla/zulip,umkay/zulip,tiansiyuan/zulip,Qgap/zulip,aps-sids/zulip,yuvipanda/zulip,rht/zulip,schatt/zulip,peiwei/zulip,mdavid/zulip,calvinleenyc/zulip,punchagan/zulip,fw1121/zulip,tommyip/zulip,m1ssou/zulip,gkotian/zulip,gkotian/zulip,suxinde2009/zulip,praveenaki/zulip,ApsOps/zulip,susansls/zulip,stamhe/zulip,LAndreas/zulip,amanharitsh123/zulip,tbutter/zulip,brainwane/zulip,KingxBanana/zulip,so0k/zulip,peiwei/zulip,mohsenSy/zulip,themass/zulip,shaunstanislaus/zulip,adnanh/zulip,itnihao/zulip,esander91/zulip,hengqujushi/zulip,Jianchun1/zulip,EasonYi/zulip,mahim97/zulip,blaze225/zulip,samatdav/zulip,atomic-labs/zulip,umkay/zulip,xuxiao/zulip,dattatreya303/zulip,niftynei/zulip,tiansiyuan/zulip,adnanh/zulip,zorojean/zulip,ApsOps/zulip,akuseru/zulip,proliming/zulip,swinghu/zulip,jrowan/zulip,eastlhu/zulip,mdavid/zulip,Gabriel0402/zulip,hustlzp/zulip,zhaoweigg/zulip,zachallaun/zulip,zofuthan/zulip,guiquanz/zulip,brainwane/zulip,souravbadami/zulip,verma-varsha/zulip,levixie/zulip,PhilSk/zulip,bssrdf/zulip,m1ssou/zulip,calvinleenyc/zulip,kokoar/zulip,ashwinirudrappa/zulip,zhaoweigg/zulip,jimmy54/zulip,vakila/zulip,johnny9/zulip,gkotian/zulip,LeeRisk/zulip,TigorC/zulip,JPJPJPOPOP/zulip,eeshangarg/zulip,wavelets/zulip,bowlofstew/zulip,mahim97/zulip,tiansiyuan/zulip,cosmicAsymmetry/zulip,thomasboyt/zulip,Suninus/zulip,Drooids/zulip,showell/zulip,tiansiyuan/zulip,jessedhillon/zulip,SmartPeople/zulip,LeeRisk/zulip,so0k/zulip,bluesea/zulip,seapasulli/zulip,shubhamdhama/zulip,jonesgithub/zulip,samatdav/zulip,zulip/zulip,sonali0901/zulip,Drooids/zulip,firstblade/zulip,bitemyapp/zulip,samatdav/zulip,cosmicAsymmetry/zulip,rishig/zulip,blaze225/zulip,sharmaeklavya2/zulip,moria/zulip,andersk/zulip,samatdav/zulip,schatt/zulip,eastlhu/zulip,AZtheAsian/zulip,littledogboy/zulip,showell/zulip,dnmfarrell/zulip,zhaoweigg/zulip,RobotCaleb/zulip,PaulPetring/zulip,zorojean/zulip,DazWorrall/zulip,willingc/zulip,timabbott/zulip,Drooids/zulip,RobotCaleb/zulip,glovebx/zulip,hengqujushi/zulip,dawran6/zulip,esander91/zulip,aakash-cr7/zulip,Batterfii/zulip,Vallher/zulip,he15his/zulip,reyha/zulip,saitodisse/zulip,wweiradio/zulip,calvinleenyc/zulip,nicholasbs/zulip,Galexrt/zulip,zhaoweigg/zulip,jainayush975/zulip,dhcrzf/zulip,Gabriel0402/zulip,Galexrt/zulip,ApsOps/zulip,wdaher/zulip,easyfmxu/zulip,zofuthan/zulip,jerryge/zulip,Batterfii/zulip,mansilladev/zulip,willingc/zulip,armooo/zulip,levixie/zulip,RobotCaleb/zulip,jessedhillon/zulip,brockwhittaker/zulip,EasonYi/zulip,stamhe/zulip,guiquanz/zulip,hafeez3000/zulip,atomic-labs/zulip,arpith/zulip,mahim97/zulip,karamcnair/zulip,johnny9/zulip,rht/zulip,LAndreas/zulip,easyfmxu/zulip,synicalsyntax/zulip,zachallaun/zulip,deer-hope/zulip,vaidap/zulip,kaiyuanheshang/zulip,kou/zulip,jimmy54/zulip,moria/zulip,jackrzhang/zulip,johnny9/zulip,peiwei/zulip,vabs22/zulip,Frouk/zulip,mansilladev/zulip,codeKonami/zulip,LAndreas/zulip,jimmy54/zulip,vabs22/zulip,jphilipsen05/zulip,amyliu345/zulip,so0k/zulip,showell/zulip,bssrdf/zulip,ipernet/zulip,ipernet/zulip,m1ssou/zulip,mdavid/zulip,pradiptad/zulip,m1ssou/zulip,swinghu/zulip,amanharitsh123/zulip,yocome/zulip,aliceriot/zulip,aliceriot/zulip,tiansiyuan/zulip,dhcrzf/zulip,amallia/zulip,so0k/zulip,dnmfarrell/zulip,Vallher/zulip,zachallaun/zulip,huangkebo/zulip,qq1012803704/zulip,karamcnair/zulip,hustlzp/zulip,natanovia/zulip,kaiyuanheshang/zulip,xuanhan863/zulip,MariaFaBella85/zulip,ryanbackman/zulip,jrowan/zulip,wweiradio/zulip,amanharitsh123/zulip,peiwei/zulip,mdavid/zulip,Galexrt/zulip,deer-hope/zulip,ufosky-server/zulip,bssrdf/zulip,willingc/zulip,so0k/zulip,easyfmxu/zulip,DazWorrall/zulip,JPJPJPOPOP/zulip,luyifan/zulip,wweiradio/zulip,mdavid/zulip,tommyip/zulip,Suninus/zulip,PhilSk/zulip,Drooids/zulip,vakila/zulip,luyifan/zulip,bastianh/zulip,ApsOps/zulip,rishig/zulip,kaiyuanheshang/zulip,JanzTam/zulip,joyhchen/zulip,Vallher/zulip,Cheppers/zulip,udxxabp/zulip,paxapy/zulip,PhilSk/zulip,christi3k/zulip,rishig/zulip,dhcrzf/zulip,grave-w-grave/zulip,peguin40/zulip,kokoar/zulip,alliejones/zulip,Cheppers/zulip,hafeez3000/zulip,MayB/zulip,avastu/zulip,qq1012803704/zulip,tbutter/zulip,johnnygaddarr/zulip,babbage/zulip,bluesea/zulip,LAndreas/zulip,ikasumiwt/zulip,lfranchi/zulip,shubhamdhama/zulip,niftynei/zulip,seapasulli/zulip,JanzTam/zulip,deer-hope/zulip,itnihao/zulip,glovebx/zulip,Gabriel0402/zulip,JanzTam/zulip,calvinleenyc/zulip,proliming/zulip,KingxBanana/zulip,seapasulli/zulip,noroot/zulip,praveenaki/zulip,timabbott/zulip,j831/zulip,udxxabp/zulip,hustlzp/zulip,hustlzp/zulip,brainwane/zulip,AZtheAsian/zulip,ryanbackman/zulip,zofuthan/zulip,tbutter/zulip,brockwhittaker/zulip,TigorC/zulip,jainayush975/zulip,vikas-parashar/zulip,johnny9/zulip,sup95/zulip,Cheppers/zulip,zhaoweigg/zulip,shubhamdhama/zulip,umkay/zulip,kou/zulip,technicalpickles/zulip,niftynei/zulip,luyifan/zulip,sharmaeklavya2/zulip,EasonYi/zulip,mohsenSy/zulip,MayB/zulip,Juanvulcano/zulip,xuxiao/zulip,ApsOps/zulip,dnmfarrell/zulip,yocome/zulip,vakila/zulip,jerryge/zulip,codeKonami/zulip,xuanhan863/zulip,hustlzp/zulip,ryansnowboarder/zulip,jackrzhang/zulip,littledogboy/zulip,wdaher/zulip,Batterfii/zulip,mohsenSy/zulip,ryansnowboarder/zulip,codeKonami/zulip,Vallher/zulip,vabs22/zulip,mansilladev/zulip,niftynei/zulip,PhilSk/zulip,dotcool/zulip,seapasulli/zulip,levixie/zulip,dotcool/zulip,ipernet/zulip,ryanbackman/zulip,Gabriel0402/zulip,armooo/zulip,Juanvulcano/zulip,wangdeshui/zulip,yuvipanda/zulip,hayderimran7/zulip,praveenaki/zulip,dwrpayne/zulip,shubhamdhama/zulip,Diptanshu8/zulip,proliming/zulip,amallia/zulip,schatt/zulip,shaunstanislaus/zulip,babbage/zulip,jimmy54/zulip,shubhamdhama/zulip,hengqujushi/zulip,armooo/zulip,wweiradio/zulip,kokoar/zulip,zachallaun/zulip,udxxabp/zulip,firstblade/zulip,bastianh/zulip,avastu/zulip,verma-varsha/zulip,codeKonami/zulip,punchagan/zulip,ericzhou2008/zulip,stamhe/zulip,avastu/zulip,dotcool/zulip,natanovia/zulip,easyfmxu/zulip,dxq-git/zulip,itnihao/zulip,alliejones/zulip,ufosky-server/zulip,wdaher/zulip,krtkmj/zulip,vaidap/zulip,natanovia/zulip,joshisa/zulip,jessedhillon/zulip,rht/zulip,akuseru/zulip,hayderimran7/zulip,dawran6/zulip,christi3k/zulip,sonali0901/zulip,souravbadami/zulip,hackerkid/zulip,EasonYi/zulip,zacps/zulip,jeffcao/zulip,dawran6/zulip,eeshangarg/zulip,souravbadami/zulip,rht/zulip,hafeez3000/zulip,LAndreas/zulip,Suninus/zulip,deer-hope/zulip,joyhchen/zulip,wweiradio/zulip,isht3/zulip,zhaoweigg/zulip,vaidap/zulip,tbutter/zulip,SmartPeople/zulip,ryanbackman/zulip,swinghu/zulip,littledogboy/zulip,umkay/zulip,paxapy/zulip,brainwane/zulip,shubhamdhama/zulip,themass/zulip,seapasulli/zulip,shrikrishnaholla/zulip,willingc/zulip,dawran6/zulip,vabs22/zulip,hustlzp/zulip,huangkebo/zulip,karamcnair/zulip,aliceriot/zulip,proliming/zulip,babbage/zulip,Juanvulcano/zulip,themass/zulip,MayB/zulip,shaunstanislaus/zulip,sonali0901/zulip,bssrdf/zulip,joyhchen/zulip,vakila/zulip,akuseru/zulip,vikas-parashar/zulip,jonesgithub/zulip,technicalpickles/zulip,arpith/zulip,Gabriel0402/zulip,wavelets/zulip,themass/zulip,voidException/zulip,jeffcao/zulip,ashwinirudrappa/zulip,cosmicAsymmetry/zulip,karamcnair/zulip,DazWorrall/zulip,jphilipsen05/zulip,hj3938/zulip,RobotCaleb/zulip,MariaFaBella85/zulip,Cheppers/zulip,natanovia/zulip,jphilipsen05/zulip,technicalpickles/zulip,m1ssou/zulip,wangdeshui/zulip,kokoar/zulip,aliceriot/zulip,ryansnowboarder/zulip,kaiyuanheshang/zulip,atomic-labs/zulip,krtkmj/zulip,babbage/zulip,wdaher/zulip,rishig/zulip,itnihao/zulip,bowlofstew/zulip,RobotCaleb/zulip,arpith/zulip,huangkebo/zulip | ---
+++
@@ -11,8 +11,18 @@
# name. So we just pick a unique arbitrary name. This is
# okay because we can figure out from the source map file
# contents which JavaScript files it corresponds to.
- source_map = path.join(settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR,
- sha1(js).hexdigest() + '.map')
+
+ # As a hack to make things easier, assume that any large input
+ # corresponds to app.js. This is like 60 times bigger than
+ # any other input file, at present.
+
+ if len(js) > 100000:
+ source_map_name = 'app.js.map'
+ else:
+ source_map_name = sha1(js).hexdigest() + '.map'
+
+ source_map = path.join(
+ settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, source_map_name)
command = '%s --create_source_map %s' % (
settings.PIPELINE_CLOSURE_BINARY, source_map) |
0a5e4194fe06b20b4eaacaa9452403f70076ccd3 | base_solver.py | base_solver.py | #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def run(self):
start_time = datetime.now()
self.best_solution, self.best_distance, self.cycles = self.run_search()
finish_time = datetime.now()
self.search_time = finish_time - start_time
def run_search(self):
# dummy - this is where one should implement the algorithm
pass
def get_summary(self):
if self.best_solution is None:
return u'Run the solver first'
txt = (
'========== {solver_name} ==========\n'
'run {cycles} cycles for: {search_time}\n'
'best found solution: {best_solution}\n'
'distance: {distance}\n'
)
return txt.format(
solver_name=str(self.__class__),
cycles=self.cycles,
search_time=self.search_time,
best_solution=self.best_solution,
distance=self.best_distance
)
| #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class RunSolverFirst(Exception):
pass
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def run(self):
start_time = datetime.now()
self.best_solution, self.best_distance, self.cycles = self.run_search()
finish_time = datetime.now()
self.search_time = finish_time - start_time
def run_search(self):
# dummy - this is where one should implement the algorithm
pass
def get_summary(self):
if self.best_solution is None:
raise RunSolverFirst(u'Run the solver first')
txt = (
'========== {solver_name} ==========\n'
'run {cycles} cycles for: {search_time}\n'
'best found solution: {best_solution}\n'
'distance: {distance}\n'
)
return txt.format(
solver_name=str(self.__class__),
cycles=self.cycles,
search_time=self.search_time,
best_solution=self.best_solution,
distance=self.best_distance
)
| Add run solver first exception type | Add run solver first exception type
| Python | mit | Cosiek/KombiVojager | ---
+++
@@ -2,6 +2,10 @@
# encoding: utf-8
from datetime import datetime
+
+class RunSolverFirst(Exception):
+ pass
+
class BaseSolver(object):
task = None
@@ -27,7 +31,7 @@
def get_summary(self):
if self.best_solution is None:
- return u'Run the solver first'
+ raise RunSolverFirst(u'Run the solver first')
txt = (
'========== {solver_name} ==========\n' |
1069565b596d3bc13b99bcae4ec831c2228e7946 | PrinterApplication.py | PrinterApplication.py | from Cura.WxApplication import WxApplication
import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
super(PrinterApplication, self).run()
| from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
super(PrinterApplication, self).run()
| Move WxApplication into its own Wx submodule | Move WxApplication into its own Wx submodule
| Python | agpl-3.0 | lo0ol/Ultimaker-Cura,Curahelper/Cura,senttech/Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,bq/Ultimaker-Cura,fxtentacle/Cura,totalretribution/Cura,derekhe/Cura,ad1217/Cura,ad1217/Cura,derekhe/Cura,Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,markwal/Cura,fieldOfView/Cura,fxtentacle/Cura,hmflash/Cura,quillford/Cura,senttech/Cura,ynotstartups/Wanhao,markwal/Cura,bq/Ultimaker-Cura,fieldOfView/Cura,DeskboxBrazil/Cura,quillford/Cura,totalretribution/Cura | ---
+++
@@ -1,12 +1,8 @@
-from Cura.WxApplication import WxApplication
-
-import wx
+from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
- frame = wx.Frame(None, wx.ID_ANY, "Hello World")
- frame.Show(True)
super(PrinterApplication, self).run() |
4b10355d256f1a0bf6b7cc8eae1eda4b8794cb09 | indra/sources/omnipath/__init__.py | indra/sources/omnipath/__init__.py | from .api import process_from_web
from .processor import OmniPathProcessor
| """
The OmniPath module accesses biomolecular interaction data from various
curated databases using the OmniPath API (see
https://saezlab.github.io/pypath/html/index.html#webservice) and processes
the returned data into statements using the OmniPathProcessor.
Currently, the following data is collected:
- Modifications from the PTMS endpoint https://saezlab.github.io/pypath/html/index.html#enzyme-substrate-interactions
- Ligand-Receptor data from the interactions endpoint https://saezlab.github.io/pypath/html/index.html#interaction-datasets
To process all statements, use the function `process_from_web`:
>>> from indra.sources.omnipath import process_from_web
>>> omnipath_processor = process_from_web()
>>> stmts = omnipath_processor.statements
"""
from .api import process_from_web
from .processor import OmniPathProcessor
| Write short blurb about module and its usage | Write short blurb about module and its usage
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,bgyori/indra,sorgerlab/indra | ---
+++
@@ -1,2 +1,18 @@
+"""
+The OmniPath module accesses biomolecular interaction data from various
+curated databases using the OmniPath API (see
+https://saezlab.github.io/pypath/html/index.html#webservice) and processes
+the returned data into statements using the OmniPathProcessor.
+
+Currently, the following data is collected:
+ - Modifications from the PTMS endpoint https://saezlab.github.io/pypath/html/index.html#enzyme-substrate-interactions
+ - Ligand-Receptor data from the interactions endpoint https://saezlab.github.io/pypath/html/index.html#interaction-datasets
+
+To process all statements, use the function `process_from_web`:
+
+>>> from indra.sources.omnipath import process_from_web
+>>> omnipath_processor = process_from_web()
+>>> stmts = omnipath_processor.statements
+"""
from .api import process_from_web
from .processor import OmniPathProcessor |
ad74a2d02b109308b79b5629920a23b85748e439 | photutils/conftest.py | photutils/conftest.py | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
enable_deprecations_as_exceptions()
| # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
enable_deprecations_as_exceptions()
# Add scikit-image to test header information
try:
PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
except NameError: # astropy < 1.0
pass
| Add scikit-image to test header information | Add scikit-image to test header information | Python | bsd-3-clause | larrybradley/photutils,astropy/photutils | ---
+++
@@ -7,3 +7,9 @@
## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
enable_deprecations_as_exceptions()
+
+# Add scikit-image to test header information
+try:
+ PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
+except NameError: # astropy < 1.0
+ pass |
da90ddfd697da5be7e0c01f183e733bbc981fe85 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
| from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return 'Hello World!'
if __name__ == '__main__':
app.run()
| Index action ready with "Hello, World!" message | Index action ready with "Hello, World!" message
| Python | mit | alexander-emelyanov/microblog,alexander-emelyanov/microblog | ---
+++
@@ -4,7 +4,8 @@
@app.route('/')
-def hello_world():
+@app.route('/index')
+def index():
return 'Hello World!'
|
a9892cc1fcb7d2911f6afba52a06a6f1c1ed9b25 | tests/test_wrap_modes.py | tests/test_wrap_modes.py | from hypothesis_auto import auto_pytest_magic
from isort import wrap_modes
auto_pytest_magic(wrap_modes.grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid_grouped, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid_grouped_no_comma, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.noqa, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(
wrap_modes.vertical_prefix_from_module_import, auto_allow_exceptions_=(ValueError,)
)
| from hypothesis_auto import auto_pytest_magic
from isort import wrap_modes
auto_pytest_magic(wrap_modes.grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid_grouped, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical_grid_grouped_no_comma, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.noqa, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(
wrap_modes.vertical_prefix_from_module_import, auto_allow_exceptions_=(ValueError,)
)
auto_pytest_magic(wrap_modes.vertical_hanging_indent_bracket, auto_allow_exceptions_=(ValueError,))
def test_wrap_mode_interface():
assert (
wrap_modes._wrap_mode_interface("statement", [], "", "", 80, [], "", "", True, True) == ""
)
| Increase wrap mode test coverage | Increase wrap mode test coverage
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -13,3 +13,10 @@
auto_pytest_magic(
wrap_modes.vertical_prefix_from_module_import, auto_allow_exceptions_=(ValueError,)
)
+auto_pytest_magic(wrap_modes.vertical_hanging_indent_bracket, auto_allow_exceptions_=(ValueError,))
+
+
+def test_wrap_mode_interface():
+ assert (
+ wrap_modes._wrap_mode_interface("statement", [], "", "", 80, [], "", "", True, True) == ""
+ ) |
cf52a25001a3c9883caff70d3eb0318c8418fa76 | test/pyrostest/pub_foo.py | test/pyrostest/pub_foo.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
pub = rospy.Publisher('/pub_val', Int32, queue_size=10)
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
pub.publish(rospy.get_param('foo'))
if __name__ == '__main__':
pub_foo()
| #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
pub = rospy.Publisher('/pub_val', Int32, queue_size=10)
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
pub.publish(rospy.get_param('/foo'))
if __name__ == '__main__':
pub_foo()
| Use absolute path to make the node work. | Use absolute path to make the node work.
| Python | mit | gtagency/pyrostest,gtagency/pyrostest | ---
+++
@@ -9,7 +9,7 @@
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
- pub.publish(rospy.get_param('foo'))
+ pub.publish(rospy.get_param('/foo'))
if __name__ == '__main__': |
d54c54d50a17afde8dbaa8116d7475d66f787aad | pdxtrees/settings_production.py | pdxtrees/settings_production.py | """
Based on:
https://devcenter.heroku.com/articles/getting-started-with-django
"""
import settings
DEBUG = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
#DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
) | """
Based on:
https://devcenter.heroku.com/articles/getting-started-with-django
"""
import settings
DEBUG = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
SECRET_KEY = os.environ.get('SECRET_KEY')
WSGI_APPLICATION = 'pdxtrees.wsgi_deploy.application'
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
) | Read secret key from env var explicitly | Read secret key from env var explicitly
| Python | mit | mattblair/pdx-trees-django,mattblair/pdx-trees-django | ---
+++
@@ -12,7 +12,10 @@
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
-#DATABASES['default'] = dj_database_url.config()
+
+SECRET_KEY = os.environ.get('SECRET_KEY')
+
+WSGI_APPLICATION = 'pdxtrees.wsgi_deploy.application'
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') |
66a4fc0ce6e5c07540c5e4849b829e6623df6590 | biothings/web/api/es/handlers/small_handlers.py | biothings/web/api/es/handlers/small_handlers.py | """
TODO load balancer check settings
"""
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from elasticsearch.exceptions import ElasticsearchException
from tornado.web import HTTPError
class StatusHandler(BaseESRequestHandler):
'''
Handles requests to check the status of the server.
'''
async def head(self):
try:
r = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
except ElasticsearchException:
raise HTTPError(503)
if not r:
raise HTTPError(503)
async def get(self):
await self.head()
self.write('OK')
| """
TODO load balancer check settings
"""
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from elasticsearch.exceptions import ElasticsearchException
from tornado.web import HTTPError
class StatusHandler(BaseESRequestHandler):
'''
Handles requests to check the status of the server.
'''
async def head(self):
try:
res = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
except ElasticsearchException:
raise HTTPError(503)
if not res:
raise HTTPError(503)
async def get(self):
await self.head()
self.write('OK')
| Rename var to comply with pylint | Rename var to comply with pylint
| Python | apache-2.0 | biothings/biothings.api,biothings/biothings.api | ---
+++
@@ -13,10 +13,10 @@
'''
async def head(self):
try:
- r = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
+ res = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
except ElasticsearchException:
raise HTTPError(503)
- if not r:
+ if not res:
raise HTTPError(503)
async def get(self): |
da2f01c6fbeba6a0df3d6bb2c6dcf6a6ae659a76 | opentreemap/registration_backend/urls.py | opentreemap/registration_backend/urls.py | from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
| from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
| Use registration form to prevent duplicate emails | Use registration form to prevent duplicate emails
Fixes #725.
We enforce this both at the database level, and here, using django
registration's ready-made form class.
| Python | agpl-3.0 | clever-crow-consulting/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core | ---
+++
@@ -2,6 +2,8 @@
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
+
+from registration.forms import RegistrationFormUniqueEmail
from views import RegistrationView, ActivationView
@@ -18,7 +20,7 @@
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
- RegistrationView.as_view(),
+ RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA |
fdfd26b57abfd471fca36fb1f73f739a6374ddb3 | ScannerServer/nfc_scanner.py | ScannerServer/nfc_scanner.py | import signal
import time
from pirc522 import RFID
loop = True
rfid = RFID()
util = rfid.util()
def end_read(signal, frame):
global loop
print("\nCtrl+C captured, ending read.")
loop = False
rfid.cleanup()
signal.signal(signal.SIGINT, end_read)
print("Scanning...")
while loop:
(not_found, data) = rfid.request()
if not_found:
continue
(error, uid) = rfid.anticoll()
if error:
continue
util.set_tag(uid)
chars = []
num_chars_to_skip = 28
done_reading = False
for i in xrange(16):
(error, data) = rfid.read(i * 4)
if error:
break
for c in data:
if num_chars_to_skip > 0:
num_chars_to_skip -= 1
continue
chars.append(chr(c))
if c == 0:
done_reading = True
break
if done_reading:
print(''.join(chars))
break
time.sleep(5)
| import signal
import time
from pirc522 import RFID
loop = True
rfid = RFID()
util = rfid.util()
def end_read(signal, frame):
global loop
print("\nCtrl+C captured, ending read.")
loop = False
rfid.cleanup()
signal.signal(signal.SIGINT, end_read)
print("Scanning...")
while loop:
(not_found, data) = rfid.request()
if not_found:
continue
(error, uid) = rfid.anticoll()
if error:
continue
util.set_tag(uid)
chars = []
num_chars_to_skip = 28
done_reading = False
for i in xrange(16):
(error, data) = rfid.read(i * 4)
if error:
break
for c in data:
if num_chars_to_skip > 0:
num_chars_to_skip -= 1
continue
if c >= 200:
# TODO(ryok): Investigate why 254 comes at the end of URL
continue
if c == 0:
done_reading = True
break
chars.append(chr(c))
if done_reading:
print(''.join(chars))
break
time.sleep(5)
| Discard charcode 254 at end of URL | Discard charcode 254 at end of URL
| Python | mit | straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock | ---
+++
@@ -40,10 +40,13 @@
if num_chars_to_skip > 0:
num_chars_to_skip -= 1
continue
- chars.append(chr(c))
+ if c >= 200:
+ # TODO(ryok): Investigate why 254 comes at the end of URL
+ continue
if c == 0:
done_reading = True
break
+ chars.append(chr(c))
if done_reading:
print(''.join(chars))
break |
6c3621aa5d3936953da027efde9dd3622da50d38 | virtool/indexes/models.py | virtool/indexes/models.py | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index files
"""
__tablename__ = "index_files"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
index = Column(String, nullable=False)
type = Column(Enum(IndexType))
size = Column(Integer)
def __repr__(self):
return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \
f"size={self.size}"
| from sqlalchemy import Column, Enum, Integer, String
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index files
"""
__tablename__ = "index_files"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
index = Column(String, nullable=False)
type = Column(Enum(IndexType))
size = Column(Integer)
def __repr__(self):
return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \
f"size={self.size}"
| Fix incorrect column in IndexFile model | Fix incorrect column in IndexFile model
* Change `reference` to `index`.
* Removed unused import of `enum` | Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -1,5 +1,4 @@
-import enum
-from sqlalchemy import Column, Integer, String, Enum
+from sqlalchemy import Column, Enum, Integer, String
from virtool.pg.utils import Base, SQLEnum
@@ -29,5 +28,5 @@
size = Column(Integer)
def __repr__(self):
- return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \
+ return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \
f"size={self.size}" |
ba2913658e3770ef73d0e7972435def32199cc08 | test.py | test.py | import random
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
def generate_data(size):
""""
x_train = []
y_train = []
for i in range(size):
x = random.randint(0, 100)
y = 2*x
x_train.append(x)
y_train.append(y)
return np.array(x_train), np.array(y_train)
"""
import numpy as np
#data = np.random.random((10000, 100))
#labels = np.random.randint(2, size=(10000, 1))
data = np.random.random((10000, 1))
labels = data*2
return data, labels
model = Sequential()
model.add(Dense(1, input_dim=1))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
x_train, y_train = generate_data(1000)
x_test, y_test = generate_data(10)
model.fit(x_train, y_train, epochs=1000, batch_size=32)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
print(loss_and_metrics)
| import random
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
def generate_data(size):
""""
x_train = []
y_train = []
for i in range(size):
x = random.randint(0, 100)
y = 2*x
x_train.append(x)
y_train.append(y)
return np.array(x_train), np.array(y_train)
"""
import numpy as np
#data = np.random.random((10000, 100))
#labels = np.random.randint(2, size=(10000, 1))
#data = np.random.random((10000, 2))
#labels = np.sum(data, (1,))
data = np.random.random((10000, 1))
labels = data*2
return data, labels
model = Sequential()
model.add(Dense(1, input_dim=1))
model.compile(optimizer='rmsprop',
loss='mse',
metrics=['accuracy'])
x_train, y_train = generate_data(10000)
x_test, y_test = generate_data(100)
model.fit(x_train, y_train, epochs=30, batch_size=32)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=16)
#print(loss_and_metrics)
pred = model.predict(x_test, batch_size=32, verbose=0)
print("expected:")
print(y_test)
print("actual:")
print(pred)
| Fix lirear regression model loss calculation | Fix lirear regression model loss calculation
| Python | apache-2.0 | alexkorep/dogs-vs-cats | ---
+++
@@ -17,6 +17,8 @@
import numpy as np
#data = np.random.random((10000, 100))
#labels = np.random.randint(2, size=(10000, 1))
+ #data = np.random.random((10000, 2))
+ #labels = np.sum(data, (1,))
data = np.random.random((10000, 1))
labels = data*2
return data, labels
@@ -25,14 +27,21 @@
model = Sequential()
model.add(Dense(1, input_dim=1))
model.compile(optimizer='rmsprop',
- loss='binary_crossentropy',
+ loss='mse',
metrics=['accuracy'])
-x_train, y_train = generate_data(1000)
-x_test, y_test = generate_data(10)
+x_train, y_train = generate_data(10000)
+x_test, y_test = generate_data(100)
-model.fit(x_train, y_train, epochs=1000, batch_size=32)
+model.fit(x_train, y_train, epochs=30, batch_size=32)
-loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
+loss_and_metrics = model.evaluate(x_test, y_test, batch_size=16)
+#print(loss_and_metrics)
-print(loss_and_metrics)
+pred = model.predict(x_test, batch_size=32, verbose=0)
+
+print("expected:")
+print(y_test)
+print("actual:")
+print(pred)
+ |
de16cdd72c69c232008ad22c2c45a2985d7ac99c | urls.py | urls.py | from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
(r'^about$', 'routez.travel.views.about'),
(r'^help$', 'routez.travel.views.help'),
(r'^privacy$', 'routez.travel.views.privacy'),
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
(r'^stoptimes_in_range/(\w+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
# Uncomment this for admin:
#(r'^admin/(.*)', admin.site.root),
)
# Only serve media from Django in debug mode. In non-debug mode, the regular
# web server should do this.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': os.path.join(settings.PROJECT_PATH, 'site_media'),
'show_indexes': True}),
)
| from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
(r'^about$', 'routez.travel.views.about'),
(r'^help$', 'routez.travel.views.help'),
(r'^privacy$', 'routez.travel.views.privacy'),
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
(r'^stoptimes_in_range/([^/]+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
# Uncomment this for admin:
#(r'^admin/(.*)', admin.site.root),
)
# Only serve media from Django in debug mode. In non-debug mode, the regular
# web server should do this.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': os.path.join(settings.PROJECT_PATH, 'site_media'),
'show_indexes': True}),
)
| Fix stoptimes in range function to actually take a full blown address | Fix stoptimes in range function to actually take a full blown address
| Python | agpl-3.0 | wlach/routez,wlach/routez | ---
+++
@@ -15,7 +15,7 @@
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
- (r'^stoptimes_in_range/(\w+)/(\d+)$',
+ (r'^stoptimes_in_range/([^/]+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
# Uncomment this for admin: |
e1dffa732ab0a2f9468e16c026a392e3d35cdd9c | main.py | main.py | import slackclient
import time
import os
| import slackclient
import time
import os
slackClient = slackClient.SLackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
while True:
print(slackClient.rtm_read())
time.sleep(5)
| Add test of slack rtm read | Add test of slack rtm read
| Python | mit | ollien/Slack-Welcome-Bot | ---
+++
@@ -2,3 +2,9 @@
import time
import os
+slackClient = slackClient.SLackClient(os.environ["SLACK_TOKEN"])
+slackClient.rtm_connect()
+
+while True:
+ print(slackClient.rtm_read())
+ time.sleep(5) |
7d6c60898dd2708df07847253bca86049a33ed78 | SigmaPi/SigmaPi/urls.py | SigmaPi/SigmaPi/urls.py | from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'SigmaPi.views.home', name='home'),
# url(r'^SigmaPi/', include('SigmaPi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^users/', include('UserInfo.urls')),
url(r'^secure/', include('Secure.urls')),
url(r'^', include('PubSite.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| import warnings
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
# Turns deprecation warnings into errors
warnings.simplefilter('error', DeprecationWarning)
urlpatterns = [
# Examples:
# url(r'^$', 'SigmaPi.views.home', name='home'),
# url(r'^SigmaPi/', include('SigmaPi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', admin.site.urls),
url(r'^users/', include('UserInfo.urls')),
url(r'^secure/', include('Secure.urls')),
url(r'^', include('PubSite.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| Fix admin URLs; turn deprecation warnings into errors | Fix admin URLs; turn deprecation warnings into errors
| Python | mit | sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web | ---
+++
@@ -1,11 +1,16 @@
+import warnings
+
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
-# Uncomment the next two lines to enable the admin:
from django.contrib import admin
+
admin.autodiscover()
+
+# Turns deprecation warnings into errors
+warnings.simplefilter('error', DeprecationWarning)
urlpatterns = [
# Examples:
@@ -16,7 +21,7 @@
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^admin/', admin.site.urls),
url(r'^users/', include('UserInfo.urls')),
url(r'^secure/', include('Secure.urls')),
url(r'^', include('PubSite.urls')), |
56c173a9f1bd1f22448a33b044283ad0d7bcf16e | tests/test_views.py | tests/test_views.py | from django.test import LiveServerTestCase
try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
from tusclient import client
class TestUploadView(LiveServerTestCase):
def test_get_is_not_allowed(self):
response = self.client.get(reverse('tus_upload'))
assert response.status_code == 405
def test_upload_file(self):
tus_client = client.TusClient(
self.live_server_url + reverse('tus_upload')
)
uploader = tus_client.uploader('tests/files/hello_world.txt', chunk_size=200)
uploader.upload()
assert uploader.request.status_code == 204
| try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
from tusclient.client import TusClient
class TestUploadView(object):
def test_get_is_not_allowed(self, client):
response = client.get(reverse('tus_upload'))
assert response.status_code == 405
def test_upload_file(self, live_server):
tus_client = TusClient(
live_server.url + reverse('tus_upload')
)
uploader = tus_client.uploader('tests/files/hello_world.txt', chunk_size=200)
uploader.upload()
assert uploader.request.status_code == 204
| Refactor view to use fixtures from `pytest-django`. | Refactor view to use fixtures from `pytest-django`.
| Python | mit | alican/django-tus | ---
+++
@@ -1,22 +1,20 @@
-from django.test import LiveServerTestCase
-
try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
-from tusclient import client
+from tusclient.client import TusClient
-class TestUploadView(LiveServerTestCase):
+class TestUploadView(object):
- def test_get_is_not_allowed(self):
- response = self.client.get(reverse('tus_upload'))
+ def test_get_is_not_allowed(self, client):
+ response = client.get(reverse('tus_upload'))
assert response.status_code == 405
- def test_upload_file(self):
- tus_client = client.TusClient(
- self.live_server_url + reverse('tus_upload')
+ def test_upload_file(self, live_server):
+ tus_client = TusClient(
+ live_server.url + reverse('tus_upload')
)
uploader = tus_client.uploader('tests/files/hello_world.txt', chunk_size=200)
uploader.upload() |
4b3428bca7bf9afd448d8c8da1633756a2e540fe | app/models.py | app/models.py | from app import db
from hashlib import md5
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def avatar(self, size):
return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % (md5(self.email.encode('utf-8')).hexdigest(), size)
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return True
def get_id(self):
try:
return unicode(self.id)
except NameError:
return str(self.id)
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
| from app import db
from hashlib import md5
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
def avatar(self, size):
return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % (md5(self.email.encode('utf-8')).hexdigest(), size)
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return True
def get_id(self):
try:
return unicode(self.id)
except NameError:
return str(self.id)
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
| Add more attributes for User, update db | Add more attributes for User, update db
| Python | mit | ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme | ---
+++
@@ -7,6 +7,8 @@
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
+ about_me = db.Column(db.String(140))
+ last_seen = db.Column(db.DateTime)
def avatar(self, size):
return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % (md5(self.email.encode('utf-8')).hexdigest(), size) |
e165143ff629c193a2e9c31874b66c0925de3c60 | sgpublish/io/maya.py | sgpublish/io/maya.py | from __future__ import absolute_import
from . import base
from maya import cmds
__also_reload__ = ['.base']
class Exporter(base.Exporter):
def get_previous_publish_ids(self):
ids = cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, query=True)
return set(int(x.strip()) for x in ids[0].split(',')) if ids else set()
def record_publish_id(self, id_):
ids = self.get_previous_publish_ids()
ids.add(id_)
cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, ','.join(str(x) for x in sorted(ids)))
| from __future__ import absolute_import
import os
from . import base
from maya import cmds
__also_reload__ = ['.base']
class Exporter(base.Exporter):
def __init__(self, *args, **kwargs):
super(Exporter, self).__init__(*args, **kwargs)
@property
def filename_hint(self):
return self._filename_hint or cmds.file(q=True, sceneName=True) or None
@property
def workspace(self):
return self._workspace or cmds.workspace(query=True, rootDirectory=True) or os.getcwd()
def get_previous_publish_ids(self):
ids = cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, query=True)
return set(int(x.strip()) for x in ids[0].split(',')) if ids else set()
def record_publish_id(self, id_):
ids = self.get_previous_publish_ids()
ids.add(id_)
cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, ','.join(str(x) for x in sorted(ids)))
| Add more defaults to Maya exporter | Add more defaults to Maya exporter | Python | bsd-3-clause | westernx/sgpublish | ---
+++
@@ -1,4 +1,6 @@
from __future__ import absolute_import
+
+import os
from . import base
@@ -9,6 +11,17 @@
class Exporter(base.Exporter):
+ def __init__(self, *args, **kwargs):
+ super(Exporter, self).__init__(*args, **kwargs)
+
+ @property
+ def filename_hint(self):
+ return self._filename_hint or cmds.file(q=True, sceneName=True) or None
+
+ @property
+ def workspace(self):
+ return self._workspace or cmds.workspace(query=True, rootDirectory=True) or os.getcwd()
+
def get_previous_publish_ids(self):
ids = cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, query=True)
return set(int(x.strip()) for x in ids[0].split(',')) if ids else set() |
429d701cce7ad2cf8fb77f169c4af6f2f27562fd | db_mutex/models.py | db_mutex/models.py | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock
"""
lock_id = models.CharField(max_length=255, unique=True)
creation_time = models.DateTimeField(auto_now_add=True)
| from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock
"""
lock_id = models.CharField(max_length=255, unique=True)
creation_time = models.DateTimeField(auto_now_add=True)
class Meta:
app_label = "db_mutex"
| Declare app_label in model Meta class to work with Django 1.9 | Declare app_label in model Meta class to work with Django 1.9
Fixes RemovedInDjango19Warning:
Model class db_mutex.models.DBMutex doesn't declare an explicit
app_label and either isn't in an application in INSTALLED_APPS or else
was imported before its application was loaded. This will no longer be
supported in Django 1.9.
| Python | mit | minervaproject/django-db-mutex | ---
+++
@@ -13,3 +13,6 @@
"""
lock_id = models.CharField(max_length=255, unique=True)
creation_time = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ app_label = "db_mutex" |
77d4f2bfcab2cb3ca1b8d1736c51018d69fe0940 | rpe/resources/base.py | rpe/resources/base.py | # Copyright 2019 The resource-policy-evaluation-library 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.
from abc import ABC, abstractmethod
class Resource(ABC):
@staticmethod
def factory(platform, **kargs):
""" Return a resource from the appropriate platform """
from .gcp import GoogleAPIResource
resource_platform_map = {
'gcp': GoogleAPIResource
}
try:
resource = resource_platform_map[platform].factory(
**kargs
)
except KeyError:
raise AttributeError('Unrecognized platform')
return resource
@abstractmethod
def get(self):
pass
@abstractmethod
def remediate(self):
pass
@abstractmethod
def type(self):
pass
| # Copyright 2019 The resource-policy-evaluation-library 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.
from abc import ABC, abstractmethod
class Resource(ABC):
# Returns a dictionary representing the resource. Must contain a 'type' key
# indicating what type of resource it is
@abstractmethod
def get(self):
pass
# Performs remediation based on a json representation of how to remediate a
# resource that does not comply to a given policy. This allows for
# remediation from non-python based engines, such as the open-policy-agent
# engine
@abstractmethod
def remediate(self):
pass
# Returns the resource type
@abstractmethod
def type(self):
pass
| Remove generic factory method from Resource | Remove generic factory method from Resource
| Python | apache-2.0 | forseti-security/resource-policy-evaluation-library | ---
+++
@@ -18,32 +18,21 @@
class Resource(ABC):
- @staticmethod
- def factory(platform, **kargs):
- """ Return a resource from the appropriate platform """
- from .gcp import GoogleAPIResource
-
- resource_platform_map = {
- 'gcp': GoogleAPIResource
- }
-
- try:
- resource = resource_platform_map[platform].factory(
- **kargs
- )
- except KeyError:
- raise AttributeError('Unrecognized platform')
-
- return resource
-
+ # Returns a dictionary representing the resource. Must contain a 'type' key
+ # indicating what type of resource it is
@abstractmethod
def get(self):
pass
+ # Performs remediation based on a json representation of how to remediate a
+ # resource that does not comply to a given policy. This allows for
+ # remediation from non-python based engines, such as the open-policy-agent
+ # engine
@abstractmethod
def remediate(self):
pass
+ # Returns the resource type
@abstractmethod
def type(self):
pass |
dd472ed80ba374d719f9b1dc56fd3038f6a73dee | examples/benchmark/benchmark_twisted_names.py | examples/benchmark/benchmark_twisted_names.py | """
Benchmark on Twisted Names subsystem.
"""
from twisted.names.dns import DNSDatagramProtocol
from twisted.names.server import DNSServerFactory
from twisted.names import hosts, client
from twisted.internet import reactor
import benchmarking
@benchmarking.deferred(max_seconds=5)
class TwistedNamesBenchmarkCase(benchmarking.BenchmarkCase):
def setUp(self):
controller = DNSServerFactory([hosts.Resolver()])
self._port = reactor.listenUDP(0, DNSDatagramProtocol(controller))
self._resolver = client.Resolver(servers=[('127.0.0.1', self._port.getHost().port)])
self._timeout = 1
def tearDown(self):
return self._port.stopListening()
@benchmarking.repeats(15)
@benchmarking.async(concurrency=10, duration=1)
def benchmark_run(self):
return self._resolver.lookupAddress(
'localhost', timeout=(self._timeout,))
| """
Benchmark on Twisted Names subsystem.
"""
from twisted.names.dns import DNSDatagramProtocol
from twisted.names.server import DNSServerFactory
from twisted.names import hosts, client
from twisted.internet import reactor
import benchmarking
@benchmarking.deferred(max_seconds=15)
class TwistedNamesBenchmarkCase(benchmarking.BenchmarkCase):
def setUp(self):
controller = DNSServerFactory([hosts.Resolver()])
self._port = reactor.listenUDP(0, DNSDatagramProtocol(controller))
self._resolver = client.Resolver(servers=[('127.0.0.1', self._port.getHost().port)])
self._timeout = 1
def tearDown(self):
return self._port.stopListening()
@benchmarking.repeats(15)
@benchmarking.async(concurrency=10, duration=5)
def benchmark_run(self):
return self._resolver.lookupAddress(
'localhost', timeout=(self._timeout,))
| Make benchmark params match Twisted's params. | Make benchmark params match Twisted's params.
| Python | mit | AlekSi/benchmarking-py | ---
+++
@@ -10,7 +10,7 @@
import benchmarking
-@benchmarking.deferred(max_seconds=5)
+@benchmarking.deferred(max_seconds=15)
class TwistedNamesBenchmarkCase(benchmarking.BenchmarkCase):
def setUp(self):
controller = DNSServerFactory([hosts.Resolver()])
@@ -22,7 +22,7 @@
return self._port.stopListening()
@benchmarking.repeats(15)
- @benchmarking.async(concurrency=10, duration=1)
+ @benchmarking.async(concurrency=10, duration=5)
def benchmark_run(self):
return self._resolver.lookupAddress(
'localhost', timeout=(self._timeout,)) |
9e013b6123e3eefec64e9e479741a16fe4727ad6 | plugins/python/org.eclipse.eclipsemonkey.lang.python.examples/samples/scripts/Views__Web_View.py | plugins/python/org.eclipse.eclipsemonkey.lang.python.examples/samples/scripts/Views__Web_View.py | #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def changing(self, event):
location = event.location
# Print out the location to the console
print "You clicked on: " + location
def changed(self, event):
pass
page = window.getActivePage()
view = page.showView(
"org.eclipse.eclipsemonkey.ui.scriptableView.GenericScriptableView",
"GoogleWebView",
IWorkbenchPage.VIEW_VISIBLE)
view.setViewTitle("Google")
browser = view.getBrowser()
browser.setUrl("http://www.google.com")
browser.addLocationListener(MyLocationListener());
| #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def changing(self, event):
location = event.location
# Print out the location to the console
print "You clicked on: " + location
def changed(self, event):
pass
page = window.getActivePage()
view = page.showView(
"org.eclipse.eclipsemonkey.ui.scriptableView.GenericScriptableView",
"GoogleWebView",
IWorkbenchPage.VIEW_VISIBLE)
view.setViewTitle("Google")
browser = view.getBrowser()
browser.setUrl("http://www.google.com")
browser.addLocationListener(MyLocationListener());
| Correct sample with new qualified name of the class | Correct sample with new qualified name of the class | Python | epl-1.0 | adaussy/eclipse-monkey-revival,adaussy/eclipse-monkey-revival,adaussy/eclipse-monkey-revival | ---
+++
@@ -5,7 +5,7 @@
#
from org.eclipse.swt.browser import LocationListener
-from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView
+from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener): |
1db1dfe35a97080286577b78f4708cc9afd82232 | rx/checkedobserver.py | rx/checkedobserver.py | from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
try:
self._observer.on_next(value)
finally:
self._state = 0
def on_error(self, err):
self.check_access()
try:
self._observer.on_error(err)
finally:
self._state = 2
def on_completed(self):
self.check_access()
try:
self._observer.on_completed()
finally:
self._state = 2
def check_access(self):
if self._state == 1:
raise ReEntracyException()
if self._state == 2:
raise CompletedException()
if self._state == 0:
self._state = 1
def checked(self):
"""Checks access to the observer for grammar violations. This includes
checking for multiple OnError or OnCompleted calls, as well as
reentrancy in any of the observer methods. If a violation is detected,
an Error is thrown from the offending observer method call.
Returns an observer that checks callbacks invocations against the
observer grammar and, if the checks pass, forwards those to the
specified observer.
"""
return CheckedObserver(self)
CheckedObserver.checked = checked
Observer.checked = checked
| from six import add_metaclass
from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
try:
self._observer.on_next(value)
finally:
self._state = 0
def on_error(self, err):
self.check_access()
try:
self._observer.on_error(err)
finally:
self._state = 2
def on_completed(self):
self.check_access()
try:
self._observer.on_completed()
finally:
self._state = 2
def check_access(self):
if self._state == 1:
raise ReEntracyException()
if self._state == 2:
raise CompletedException()
if self._state == 0:
self._state = 1
@add_metaclass(ExtensionMethod)
class ObserverChecked(Observer):
"""Uses a meta class to extend Observable with the methods in this class"""
def checked(self):
"""Checks access to the observer for grammar violations. This includes
checking for multiple OnError or OnCompleted calls, as well as
reentrancy in any of the observer methods. If a violation is detected,
an Error is thrown from the offending observer method call.
Returns an observer that checks callbacks invocations against the
observer grammar and, if the checks pass, forwards those to the
specified observer."""
return CheckedObserver(self)
| Use extension method for Observer.checked | Use extension method for Observer.checked
| Python | mit | dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY | ---
+++
@@ -1,4 +1,7 @@
+from six import add_metaclass
+
from rx import Observer
+from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
@@ -35,18 +38,18 @@
if self._state == 0:
self._state = 1
+@add_metaclass(ExtensionMethod)
+class ObserverChecked(Observer):
+ """Uses a meta class to extend Observable with the methods in this class"""
-def checked(self):
- """Checks access to the observer for grammar violations. This includes
- checking for multiple OnError or OnCompleted calls, as well as
- reentrancy in any of the observer methods. If a violation is detected,
- an Error is thrown from the offending observer method call.
+ def checked(self):
+ """Checks access to the observer for grammar violations. This includes
+ checking for multiple OnError or OnCompleted calls, as well as
+ reentrancy in any of the observer methods. If a violation is detected,
+ an Error is thrown from the offending observer method call.
- Returns an observer that checks callbacks invocations against the
- observer grammar and, if the checks pass, forwards those to the
- specified observer.
- """
- return CheckedObserver(self)
+ Returns an observer that checks callbacks invocations against the
+ observer grammar and, if the checks pass, forwards those to the
+ specified observer."""
-CheckedObserver.checked = checked
-Observer.checked = checked
+ return CheckedObserver(self) |
f65f18ceec8abf468b1426cf819c806f2d1d7ff8 | auslib/migrate/versions/009_add_rule_alias.py | auslib/migrate/versions/009_add_rule_alias.py | from sqlalchemy import Column, String, MetaData, Table
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
def add_alias(table):
alias = Column('alias', String(50), unique=True)
alias.create(table)
add_alias(Table('rules', metadata, autoload=True))
add_alias(Table('rules_history', metadata, autoload=True))
def downgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
Table('rules', metadata, autoload=True).c.alias.drop()
Table('rules_history', metadata, autoload=True).c.alias.drop()
| from sqlalchemy import Column, String, MetaData, Table
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
alias = Column("alias", String(50), unique=True)
alias.create(Table("rules", metadata, autoload=True), unique_name="alias_unique")
history_alias = Column("alias", String(50))
history_alias.create(Table('rules_history', metadata, autoload=True))
def downgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
Table('rules', metadata, autoload=True).c.alias.drop()
Table('rules_history', metadata, autoload=True).c.alias.drop()
| Fix migration script to make column unique+add index. | Fix migration script to make column unique+add index.
| Python | mpl-2.0 | testbhearsum/balrog,nurav/balrog,aksareen/balrog,testbhearsum/balrog,tieu/balrog,aksareen/balrog,aksareen/balrog,tieu/balrog,nurav/balrog,nurav/balrog,testbhearsum/balrog,tieu/balrog,mozbhearsum/balrog,mozbhearsum/balrog,aksareen/balrog,mozbhearsum/balrog,nurav/balrog,testbhearsum/balrog,mozbhearsum/balrog,tieu/balrog | ---
+++
@@ -4,11 +4,11 @@
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
- def add_alias(table):
- alias = Column('alias', String(50), unique=True)
- alias.create(table)
- add_alias(Table('rules', metadata, autoload=True))
- add_alias(Table('rules_history', metadata, autoload=True))
+ alias = Column("alias", String(50), unique=True)
+ alias.create(Table("rules", metadata, autoload=True), unique_name="alias_unique")
+
+ history_alias = Column("alias", String(50))
+ history_alias.create(Table('rules_history', metadata, autoload=True))
def downgrade(migrate_engine): |
6bdec176a7a43b3e6eb65a2c7e639c09a89d43bc | data_models/data_refinery_models/models.py | data_models/data_refinery_models/models.py | from django.db import models
from django.utils import timezone
class TimeTrackedModel(models.Model):
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(TimeTrackedModel, self).save(*args, **kwargs)
class Meta:
abstract = True
# This model still has a prototypical status, but I needed something to
# test with and it's at least in the right ballpark
class Batch(TimeTrackedModel):
source_type = models.CharField(max_length=256)
size_in_bytes = models.IntegerField()
download_url = models.CharField(max_length=2048)
raw_format = models.CharField(max_length=256)
processed_format = models.CharField(max_length=256)
processor_required = models.IntegerField()
accession_code = models.CharField(max_length=256)
# This field will denote where in our system the file can be found
internal_location = models.CharField(max_length=256)
# This will at some be a meaningful integer->organism lookup thing
organism = models.IntegerField()
STATUSES = (
("NEW", "New"),
("DOWNLOADED", "Downloaded"),
("PROCESSED", "Proccessed"),
)
status = models.CharField(max_length=10, choices=STATUSES)
| from django.db import models
from django.utils import timezone
class TimeTrackedModel(models.Model):
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(TimeTrackedModel, self).save(*args, **kwargs)
class Meta:
abstract = True
# This model still has a prototypical status, but I needed something to
# test with and it's at least in the right ballpark
class Batch(TimeTrackedModel):
source_type = models.CharField(max_length=256)
size_in_bytes = models.IntegerField()
download_url = models.CharField(max_length=2048)
raw_format = models.CharField(max_length=256)
processed_format = models.CharField(max_length=256)
processor_required = models.IntegerField()
accession_code = models.CharField(max_length=256)
# This field will denote where in our system the file can be found
internal_location = models.CharField(max_length=256)
# This will utilize the organism taxonomy ID from NCBI
organism = models.IntegerField()
STATUSES = (
("NEW", "New"),
("DOWNLOADED", "Downloaded"),
("PROCESSED", "Proccessed"),
)
status = models.CharField(max_length=10, choices=STATUSES)
| Change a comment to mention the organism taxonomy ID from NCBI. | Change a comment to mention the organism taxonomy ID from NCBI.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | ---
+++
@@ -31,7 +31,7 @@
# This field will denote where in our system the file can be found
internal_location = models.CharField(max_length=256)
- # This will at some be a meaningful integer->organism lookup thing
+ # This will utilize the organism taxonomy ID from NCBI
organism = models.IntegerField()
STATUSES = ( |
10e040890f5dd1297aa4fa04ce2cf9e9db447d09 | sample/sample/urls.py | sample/sample/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'mini.views.index'),
url(r'^about$', 'mini.views.about'),
# Examples:
# url(r'^$', 'sample.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', 'mini.views.index', name='index'),
url(r'^about$', TemplateView.as_view(template_name='about.html'), name='about'),
# Examples:
# url(r'^$', 'sample.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| Use a generic TemplateView for the sample's about page | Use a generic TemplateView for the sample's about page
| Python | bsd-3-clause | tamarackapp/tamarack-collector-py | ---
+++
@@ -1,9 +1,10 @@
from django.conf.urls import patterns, include, url
from django.contrib import admin
+from django.views.generic import TemplateView
urlpatterns = patterns('',
- url(r'^$', 'mini.views.index'),
- url(r'^about$', 'mini.views.about'),
+ url(r'^$', 'mini.views.index', name='index'),
+ url(r'^about$', TemplateView.as_view(template_name='about.html'), name='about'),
# Examples:
# url(r'^$', 'sample.views.home', name='home'),
# url(r'^blog/', include('blog.urls')), |
3373521f43b0d605bba6cc36b190c064d5a0303e | kytos/core/link.py | kytos/core/link.py | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
super().__init__()
def __eq__(self, other):
"""Check if two instances of Link are equal."""
return ((self.endpoint_a == other.endpoint_a and
self.endpoint_b == other.endpoint_b) or
(self.endpoint_a == other.endpoint_b and
self.endpoint_b == other.endpoint_a))
@property
def id(self): # pylint: disable=invalid-name
"""Return id from Link intance.
Returns:
string: link id.
"""
return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id)
def as_dict(self):
"""Return the Link as a dictionary."""
return {'id': self.id,
'endpoint_a': self.endpoint_a.as_dict(),
'endpoint_b': self.endpoint_b.as_dict(),
'metadata': self.metadata,
'active': self.active,
'enabled': self.enabled}
def as_json(self):
"""Return the Link as a JSON string."""
return json.dumps(self.as_dict())
| """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
self._uuid = uuid4()
super().__init__()
def __eq__(self, other):
"""Check if two instances of Link are equal."""
return ((self.endpoint_a == other.endpoint_a and
self.endpoint_b == other.endpoint_b) or
(self.endpoint_a == other.endpoint_b and
self.endpoint_b == other.endpoint_a))
@property
def id(self): # pylint: disable=invalid-name
"""Return id from Link intance.
Returns:
string: link id.
"""
return "{}".format(self._uuid)
def as_dict(self):
"""Return the Link as a dictionary."""
return {'id': self.id,
'endpoint_a': self.endpoint_a.as_dict(),
'endpoint_b': self.endpoint_b.as_dict(),
'metadata': self.metadata,
'active': self.active,
'enabled': self.enabled}
def as_json(self):
"""Return the Link as a JSON string."""
return json.dumps(self.as_dict())
| Define Link ID as UUID | Define Link ID as UUID
| Python | mit | kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos | ---
+++
@@ -5,6 +5,8 @@
"""
import json
+
+from uuid import uuid4
from kytos.core.common import GenericEntity
@@ -16,6 +18,7 @@
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
+ self._uuid = uuid4()
super().__init__()
def __eq__(self, other):
@@ -33,7 +36,7 @@
string: link id.
"""
- return "{}:{}".format(self.endpoint_a.id, self.endpoint_b.id)
+ return "{}".format(self._uuid)
def as_dict(self):
"""Return the Link as a dictionary.""" |
b6da3311c894ad502b32b1cb96c3b0e0a02b0b85 | blog/views.py | blog/views.py | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list, 5)
page = request.GET.get('page')
try:
blogs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
blogs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
blogs = paginator.page(paginator.num_pages)
return render(request, 'blog/index.html', {
'blogs': blogs,
'menu_context': ('blog',),
})
def post(request, slug):
# @todo: raise a 404 error if not found
blog = Blog.objects.get(slug=slug)
authors = blog.get_authors()
return render(request, 'blog/post.html', {
'blog': blog,
'authors': authors,
'menu_context': ('blog',),
})
| from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list, 5)
page = request.GET.get('page')
try:
blogs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
blogs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
blogs = paginator.page(paginator.num_pages)
return render(request, 'blog/index.html', {
'blogs': blogs,
'menu_context': ('blog',),
})
def post(request, slug):
try:
blog = Blog.objects.get(slug=slug)
except Blog.DoesNotExist:
raise Http404("Blog does not exist")
authors = blog.get_authors()
return render(request, 'blog/post.html', {
'blog': blog,
'authors': authors,
'menu_context': ('blog',),
})
| Handle blogs with a bad URL slug | Handle blogs with a bad URL slug
| Python | bsd-3-clause | brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3 | ---
+++
@@ -1,4 +1,5 @@
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
+from django.http import Http404
from django.shortcuts import render
from .models import Blog
@@ -23,8 +24,11 @@
})
def post(request, slug):
- # @todo: raise a 404 error if not found
- blog = Blog.objects.get(slug=slug)
+ try:
+ blog = Blog.objects.get(slug=slug)
+ except Blog.DoesNotExist:
+ raise Http404("Blog does not exist")
+
authors = blog.get_authors()
return render(request, 'blog/post.html', {
'blog': blog, |
e730c552c0b6095a8962f29a114069fb335d7ec6 | zinnia/urls/shortlink.py | zinnia/urls/shortlink.py | """Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
)
| """Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^e(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
)
| Add a "e" prefix to avoid issue when reaching the ID 46656 | Add a "e" prefix to avoid issue when reaching the ID 46656
| Python | bsd-3-clause | aorzh/django-blog-zinnia,marctc/django-blog-zinnia,marctc/django-blog-zinnia,dapeng0802/django-blog-zinnia,ghachey/django-blog-zinnia,aorzh/django-blog-zinnia,ZuluPro/django-blog-zinnia,1844144/django-blog-zinnia,Maplecroft/django-blog-zinnia,extertioner/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,Fantomas42/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,1844144/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,bywbilly/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,petecummings/django-blog-zinnia,extertioner/django-blog-zinnia,marctc/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,1844144/django-blog-zinnia,aorzh/django-blog-zinnia | ---
+++
@@ -7,7 +7,7 @@
urlpatterns = patterns(
'',
- url(r'^(?P<token>[\da-z]+)/$',
+ url(r'^e(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
) |
f01c6d22d30e175d120e5ffe10bef93378375ea7 | example/myshop/models/__init__.py | example/myshop/models/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import CartItem
from shop.models.defaults.customer import Customer
# models defined by the myshop instance itself
if settings.SHOP_TUTORIAL == 'commodity' or settings.SHOP_TUTORIAL == 'i18n_commodity':
from shop.models.defaults.order_item import OrderItem
from shop.models.defaults.commodity import Commodity
elif settings.SHOP_TUTORIAL == 'smartcard':
from shop.models.defaults.order_item import OrderItem
from .smartcard import SmartCard
elif settings.SHOP_TUTORIAL == 'i18n_smartcard':
from shop.models.defaults.order_item import OrderItem
from .i18n_smartcard import SmartCard
elif settings.SHOP_TUTORIAL == 'polymorphic':
from .polymorphic.order import OrderItem
from .polymorphic.smartcard import SmartCard
from .polymorphic.smartphone import SmartPhoneModel, SmartPhone
from shop.models.defaults.delivery import Delivery, DeliveryItem
from shop.models.defaults.order import Order
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import CartItem
from shop.models.defaults.customer import Customer
# models defined by the myshop instance itself
if settings.SHOP_TUTORIAL == 'commodity' or settings.SHOP_TUTORIAL == 'i18n_commodity':
from shop.models.defaults.order_item import OrderItem
from shop.models.defaults.commodity import Commodity
elif settings.SHOP_TUTORIAL == 'smartcard':
from shop.models.defaults.order_item import OrderItem
from .smartcard import SmartCard
elif settings.SHOP_TUTORIAL == 'i18n_smartcard':
from shop.models.defaults.order_item import OrderItem
from .i18n_smartcard import SmartCard
elif settings.SHOP_TUTORIAL == 'polymorphic':
from .polymorphic.order import OrderItem
from .polymorphic.smartcard import SmartCard
from .polymorphic.smartphone import SmartPhoneModel, SmartPhone
from shop.models.defaults.delivery import Delivery, DeliveryItem
from shop.models.defaults.order import Order
__all__ = ['ShippingAddress', 'BillingAddress', 'Cart', 'CartItem', 'Customer', 'Order', 'OrderItem',
'Commodity', 'SmartCard', 'SmartPhoneModel', 'SmartPhone', 'Delivery', 'DeliveryItem']
| Use __all__ for restricted exports | Use __all__ for restricted exports
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,khchine5/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,awesto/django-shop,jrief/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-shop,khchine5/django-shop | ---
+++
@@ -26,3 +26,6 @@
from shop.models.defaults.delivery import Delivery, DeliveryItem
from shop.models.defaults.order import Order
+
+__all__ = ['ShippingAddress', 'BillingAddress', 'Cart', 'CartItem', 'Customer', 'Order', 'OrderItem',
+ 'Commodity', 'SmartCard', 'SmartPhoneModel', 'SmartPhone', 'Delivery', 'DeliveryItem'] |
e92784a36053e6708a3eb2772f4c5cd4e16cde4a | app/base/templatetags/git.py | app/base/templatetags/git.py | import subprocess
from django.template import Library
register = Library()
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
VERSION = head.stdout.readline().strip()
except:
VERSION = u'unknown'
@register.simple_tag()
def git_version():
return VERSION
| import subprocess
from django.template import Library
register = Library()
GIT_VERSION = None
@register.simple_tag()
def git_version():
global GIT_VERSION
if GIT_VERSION:
return GIT_VERSION
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
GIT_VERSION = head.stdout.readline().strip()
except:
GIT_VERSION = 'unknown'
return GIT_VERSION
| Make GIT_VERSION on footer more robust | [REFACTOR] Make GIT_VERSION on footer more robust
| Python | mit | internship2016/sovolo,internship2016/sovolo,internship2016/sovolo | ---
+++
@@ -3,15 +3,24 @@
register = Library()
-try:
- head = subprocess.Popen("git rev-parse --short HEAD",
- shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- VERSION = head.stdout.readline().strip()
-except:
- VERSION = u'unknown'
+GIT_VERSION = None
@register.simple_tag()
def git_version():
- return VERSION
+ global GIT_VERSION
+ if GIT_VERSION:
+ return GIT_VERSION
+
+ try:
+ head = subprocess.Popen("git rev-parse --short HEAD",
+ shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+
+ GIT_VERSION = head.stdout.readline().strip()
+ except:
+ GIT_VERSION = 'unknown'
+
+ return GIT_VERSION |
59dd1dd68792b13ea75b4aaffc68983236d02ad3 | config/urls.py | config/urls.py | """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from rest_framework.authtoken import views
from apps.commands.urls import router
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='index.html')),
# API
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^api-token-auth/', views.obtain_auth_token)
]
| """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authtoken import views
from apps.commands.urls import router
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))),
# API
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^api-token-auth/', views.obtain_auth_token)
]
| Make sure that we pass a CSRF cookie with value | Make sure that we pass a CSRF cookie with value
We need to pass a CSRF cookie when we make a GET request because
otherwise Angular would have no way of grabing the CSRF.
| Python | mit | gopar/OhMyCommand,gopar/OhMyCommand,gopar/OhMyCommand | ---
+++
@@ -16,6 +16,7 @@
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
+from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authtoken import views
@@ -23,7 +24,7 @@
urlpatterns = [
url(r'^admin/', admin.site.urls),
- url(r'^$', TemplateView.as_view(template_name='index.html')),
+ url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))),
# API
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', |
ec80d534e91e480a40152550db10e8be8e777f43 | pentai/ai/t_all.py | pentai/ai/t_all.py | #!/usr/bin/python
import unittest
import importlib
def iam(m_str):
""" import and add a module """
global all_tests
module = importlib.import_module("pentai.ai.%s" % m_str)
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
all_tests.addTest(suite)
def suite():
global all_tests
all_tests = unittest.TestSuite()
iam("t_alpha_beta")
iam("t_ab_state")
iam("t_length_lookup_table")
iam("t_length_factor")
iam("t_utility")
iam("t_ai_player")
iam("t_take_counter")
iam("t_threat_counter")
iam("t_priority_filter")
iam("t_priority_filter_2")
iam("t_priority_filter_3")
iam("t_priority_filter_4")
iam("t_priority_filter_5")
iam("t_utility_filter")
iam("t_search_order_table")
#iam("t_heuristic_filter")
iam("t_ai_genome")
iam("t_rot_standardise")
iam("t_trans_standardise")
iam("t_standardise")
iam("t_openings_mover")
iam("t_choice_stats")
iam("t_assessor")
return all_tests
def main():
unittest.TextTestRunner().run(suite())
if __name__ == "__main__":
main()
| #!/usr/bin/python
import unittest
import importlib
def iam(m_str):
""" import and add a module """
global all_tests
module = importlib.import_module("pentai.ai.%s" % m_str)
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
all_tests.addTest(suite)
def suite():
global all_tests
all_tests = unittest.TestSuite()
iam("t_alpha_beta")
iam("t_ab_state")
iam("t_length_lookup_table")
iam("t_length_factor")
iam("t_utility")
iam("t_ai_player")
iam("t_take_counter")
iam("t_threat_counter")
iam("t_priority_filter")
iam("t_priority_filter_2")
iam("t_priority_filter_3")
iam("t_priority_filter_4")
#iam("t_priority_filter_5")
iam("t_utility_filter")
iam("t_search_order_table")
#iam("t_heuristic_filter")
iam("t_ai_genome")
iam("t_rot_standardise")
iam("t_trans_standardise")
iam("t_standardise")
iam("t_openings_mover")
iam("t_choice_stats")
iam("t_assessor")
return all_tests
def main():
unittest.TextTestRunner().run(suite())
if __name__ == "__main__":
main()
| Disable PF5 tests for now | Disable PF5 tests for now
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | ---
+++
@@ -27,7 +27,7 @@
iam("t_priority_filter_2")
iam("t_priority_filter_3")
iam("t_priority_filter_4")
- iam("t_priority_filter_5")
+ #iam("t_priority_filter_5")
iam("t_utility_filter")
iam("t_search_order_table")
#iam("t_heuristic_filter") |
269670c239339bb26b61e2f9dcf0a4110b80f828 | exec_thread_1.py | exec_thread_1.py | #import spam
import filter_lta
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print THREAD_FILES
def main():
for i in THREAD_FILES:
LTA_FILES = os.chdir(i)
"""
#Convert the LTA file to the UVFITS format
#Generates UVFITS file with same basename as LTA file
spam.convert_lta_to_uvfits('Name of the file')
#Take generated UVFITS file as input and precalibrate targets
#Generates files (RRLL with the name of the source (can be obtained using ltahdr)
spam.precalibrate_targets('Name of UVFITS output file')
#Take the generated RRLL UVFITS file and process to generate the image
#Generates final image <source name>.SP2B.PBCOR.FITS
#Also generates log file spam_<source name>_<start date>_start_time>.log in
#datfil dir
spam.process_target()
"""
| #import spam
import filter_lta
import os
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print 'Executing this thread'
os.system('pwd')
def main():
for i in THREAD_FILES:
LTA_FILES = os.chdir(i)
"""
#Convert the LTA file to the UVFITS format
#Generates UVFITS file with same basename as LTA file
spam.convert_lta_to_uvfits('Name of the file')
#Take generated UVFITS file as input and precalibrate targets
#Generates files (RRLL with the name of the source (can be obtained using ltahdr)
spam.precalibrate_targets('Name of UVFITS output file')
#Take the generated RRLL UVFITS file and process to generate the image
#Generates final image <source name>.SP2B.PBCOR.FITS
#Also generates log file spam_<source name>_<start date>_start_time>.log in
#datfil dir
spam.process_target()
"""
| Add code to test running thread | Add code to test running thread
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu | ---
+++
@@ -1,12 +1,13 @@
#import spam
import filter_lta
-
+import os
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
-print THREAD_FILES
+print 'Executing this thread'
+os.system('pwd')
def main():
|
bea43abce031ab70a1f4e59e5c1e4a00af37a406 | fancypages/assets/forms/fields.py | fancypages/assets/forms/fields.py | from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
default_fields = {
'asset_pk': IntegerField,
'asset_type': CharField,
}
def __init__(self, *args, **kwargs):
kwargs.pop('queryset', None)
self.pk_field_name = kwargs.pop('to_field_name')
fields = (
self.default_fields['asset_pk'](),
self.default_fields['asset_type'](),
)
super(AssetField, self).__init__(fields, *args, **kwargs)
def prepare_value(self, value):
return super(AssetField, self).prepare_value(value)
def to_python(self, value):
if value in validators.EMPTY_VALUES:
return None
asset_pk, asset_type = value
model = get_model('assets', asset_type)
filters = {
self.pk_field_name: value[0]
}
try:
return model.objects.get(**filters)
except model.DoesNotExist:
return None
def compress(self, data_list):
return self.to_python(data_list)
| from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
pk_field_name = 'id'
default_fields = {
'asset_pk': IntegerField,
'asset_type': CharField,
}
def __init__(self, *args, **kwargs):
kwargs.pop('queryset', None)
self.pk_field_name = kwargs.pop('to_field_name', self.pk_field_name)
fields = (
self.default_fields['asset_pk'](),
self.default_fields['asset_type'](),
)
super(AssetField, self).__init__(fields, *args, **kwargs)
def prepare_value(self, value):
return super(AssetField, self).prepare_value(value)
def to_python(self, value):
if value in validators.EMPTY_VALUES:
return None
asset_pk, asset_type = value
model = get_model('assets', asset_type)
filters = {
self.pk_field_name: value[0]
}
try:
return model.objects.get(**filters)
except model.DoesNotExist:
return None
def compress(self, data_list):
return self.to_python(data_list)
| Use default PK field name for Asset form field | Use default PK field name for Asset form field
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages | ---
+++
@@ -8,6 +8,7 @@
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
+ pk_field_name = 'id'
default_fields = {
'asset_pk': IntegerField,
'asset_type': CharField,
@@ -15,7 +16,7 @@
def __init__(self, *args, **kwargs):
kwargs.pop('queryset', None)
- self.pk_field_name = kwargs.pop('to_field_name')
+ self.pk_field_name = kwargs.pop('to_field_name', self.pk_field_name)
fields = (
self.default_fields['asset_pk'](),
self.default_fields['asset_type'](), |
64d9a15f84257988b371a2d12f1137f7b9f41b02 | python/009_palindrome_number.py | python/009_palindrome_number.py | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if you have solved the
problem "Reverse Integer", you know that the reversed integer might
overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
elif x<10:
return True
elif x%10==0:
return False
revx=0
tmpx=x
while tmpx>0:
revx=revx*10+tmpx%10
tmpx//=10
return revx==x
| """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if you have solved the
problem "Reverse Integer", you know that the reversed integer might
overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x < 10:
return True
elif x % 10 == 0:
return False
revx = 0
tmpx = x
while tmpx > 0:
revx = revx * 10 + tmpx % 10
tmpx //= 10
return revx == x
a = Solution()
print(a.isPalindrome(-1) == False)
print(a.isPalindrome(1) == True)
print(a.isPalindrome(121) == True)
print(a.isPalindrome(1221) == True)
print(a.isPalindrome(10021) == False)
| Revise 009, add test cases | Revise 009, add test cases
| Python | mit | ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln | ---
+++
@@ -19,15 +19,22 @@
:type x: int
:rtype: bool
"""
- if x<0:
+ if x < 0:
return False
- elif x<10:
+ elif x < 10:
return True
- elif x%10==0:
+ elif x % 10 == 0:
return False
- revx=0
- tmpx=x
- while tmpx>0:
- revx=revx*10+tmpx%10
- tmpx//=10
- return revx==x
+ revx = 0
+ tmpx = x
+ while tmpx > 0:
+ revx = revx * 10 + tmpx % 10
+ tmpx //= 10
+ return revx == x
+
+a = Solution()
+print(a.isPalindrome(-1) == False)
+print(a.isPalindrome(1) == True)
+print(a.isPalindrome(121) == True)
+print(a.isPalindrome(1221) == True)
+print(a.isPalindrome(10021) == False) |
0d84bed2f1254887c7e352a6b173b7f554dac5f7 | timepiece/context_processors.py | timepiece/context_processors.py | from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
'FAMFAMFAM_URL': famfamfam_url,
}
return context
def quick_search(request):
return {
'quick_search_form': QuickSearchForm(),
}
def active_entries(request):
active_entries = timepiece.Entry.objects.filter(
end_time__isnull=True,
).exclude(
user=request.user,
).select_related('user', 'project', 'activity')
return {
'active_entries': active_entries,
}
def extra_nav(request):
context = {
'extra_nav': getattr(settings, 'EXTRA_NAV', {})
}
return context
| from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
'FAMFAMFAM_URL': famfamfam_url,
}
return context
def quick_search(request):
return {
'quick_search_form': QuickSearchForm(),
}
def active_entries(request):
active_entries = None
if request.user.is_authenticated():
active_entries = timepiece.Entry.objects.filter(
end_time__isnull=True,
).exclude(
user=request.user,
).select_related('user', 'project', 'activity')
return {
'active_entries': active_entries,
}
def extra_nav(request):
context = {
'extra_nav': getattr(settings, 'EXTRA_NAV', {})
}
return context
| Check request.user before using it | Check request.user before using it
| Python | mit | josesanch/django-timepiece,josesanch/django-timepiece,dannybrowne86/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,gaga3966/django-timepiece,gaga3966/django-timepiece,BocuStudio/django-timepiece,dannybrowne86/django-timepiece,gaga3966/django-timepiece,josesanch/django-timepiece,dannybrowne86/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece,BocuStudio/django-timepiece,caktus/django-timepiece | ---
+++
@@ -20,11 +20,14 @@
def active_entries(request):
- active_entries = timepiece.Entry.objects.filter(
- end_time__isnull=True,
- ).exclude(
- user=request.user,
- ).select_related('user', 'project', 'activity')
+ active_entries = None
+
+ if request.user.is_authenticated():
+ active_entries = timepiece.Entry.objects.filter(
+ end_time__isnull=True,
+ ).exclude(
+ user=request.user,
+ ).select_related('user', 'project', 'activity')
return {
'active_entries': active_entries, |
cb0c4b7af5efc16d1ca5da9722d9e29cae527fec | acme/utils/signals.py | acme/utils/signals.py | # Copyright 2018 DeepMind Technologies Limited. 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.
"""A thin wrapper around Python's builtin signal.signal()."""
import signal
import types
from typing import Any, Callable
_Handler = Callable[[], Any]
def add_handler(signo: signal.Signals, fn: _Handler):
def _wrapped(signo: signal.Signals, frame: types.FrameType):
del signo, frame
return fn()
signal.signal(signo, _wrapped)
| # Copyright 2018 DeepMind Technologies Limited. 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.
"""A thin wrapper around Python's builtin signal.signal()."""
import signal
import types
from typing import Any, Callable
_Handler = Callable[[], Any]
def add_handler(signo: signal.Signals, fn: _Handler):
# The function signal.signal expects the handler to take an int rather than a
# signal.Signals.
def _wrapped(signo: int, frame: types.FrameType):
del signo, frame
return fn()
signal.signal(signo.value, _wrapped)
| Fix pytype issue in signal handling code. | Fix pytype issue in signal handling code.
PiperOrigin-RevId: 408605103
Change-Id: If724504629a50d5cb7a099cf0263ba642e95345d
| Python | apache-2.0 | deepmind/acme,deepmind/acme | ---
+++
@@ -21,8 +21,11 @@
def add_handler(signo: signal.Signals, fn: _Handler):
- def _wrapped(signo: signal.Signals, frame: types.FrameType):
+
+ # The function signal.signal expects the handler to take an int rather than a
+ # signal.Signals.
+ def _wrapped(signo: int, frame: types.FrameType):
del signo, frame
return fn()
- signal.signal(signo, _wrapped)
+ signal.signal(signo.value, _wrapped) |
d74fb6c7f9d0bf194b44443a13114ff1d5bb0756 | scrape_PASS_FTN.py | scrape_PASS_FTN.py | """
A script to scrape all the function exports from the PASS_FTN.FOR
By Ian Bell, NIST, January 2018
"""
import os
from generate_header import generate_interface_file, generate_function_dict
if __name__=='__main__':
generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python')
funcs = generate_function_dict('REFPROP.PYF')
for func in sorted(funcs):
print(' X(' + func + ') \\')
for func in sorted(funcs):
string_lengths = []
types = []
for arg in funcs[func]['argument_list']:
if len(arg) == 3:
name, _type, size = arg
else:
name, _type = arg
size = 0
if _type == 'double *' and size == 0:
types.append('DOUBLE_REF')
elif _type == 'double *' and size != 0:
types.append('double *')
elif _type == 'int *' and size == 0:
types.append('INT_REF')
elif _type == 'int *' and size != 0:
types.append('int *')
elif _type == 'char *':
types.append('char *')
string_lengths.append('RP_SIZE_T')
else:
print(types)
raise ValueError()
print('#define '+func+'_ARGS '+','.join(types+string_lengths)) | """
A script to scrape all the function exports from the PASS_FTN.FOR
By Ian Bell, NIST, January 2018
"""
import os
from generate_header import generate_interface_file, generate_function_dict
if __name__=='__main__':
generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python')
funcs = generate_function_dict('REFPROP.PYF')
for func in sorted(funcs):
print(' X(' + func + ') \\')
for func in sorted(funcs):
string_lengths = []
types = []
for arg in funcs[func]['argument_list']:
if len(arg) == 3:
name, _type, size = arg
else:
name, _type = arg
size = 0
if _type == 'double *' and size == 0:
types.append('DOUBLE_REF')
elif _type == 'double *' and size != 0:
types.append('double *')
elif _type == 'int *' and size == 0:
types.append('INT_REF')
elif _type == 'int *' and size != 0:
types.append('int *')
elif _type == 'char *':
types.append('char *')
string_lengths.append('RP_SIZE_T')
else:
print(types)
raise ValueError()
print(' '*4+'#define '+func+'_ARGS '+','.join(types+string_lengths)) | Add a few spaces for easier copy-paste | Add a few spaces for easier copy-paste
| Python | mit | CoolProp/REFPROP-headers,CoolProp/REFPROP-headers,CoolProp/REFPROP-headers,CoolProp/REFPROP-headers | ---
+++
@@ -35,4 +35,4 @@
else:
print(types)
raise ValueError()
- print('#define '+func+'_ARGS '+','.join(types+string_lengths))
+ print(' '*4+'#define '+func+'_ARGS '+','.join(types+string_lengths)) |
1db5fefc1752b71bf11fbf63853f7c93bcc526f5 | tests/macaroon_property_tests.py | tests/macaroon_property_tests.py | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
ascii_text_stategy = strategy(text_type).map(
lambda s: s.encode('ascii', 'ignore')
)
ascii_bin_strategy = strategy(binary_type).map(
lambda s: s.decode('ascii', 'ignore')
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_stategy, ascii_bin_strategy)),
loc=one_of((ascii_text_stategy, ascii_bin_strategy)),
key=one_of((ascii_text_stategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
| from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampled_from(map(chr, range(0, 128)))]
).map(lambda c: ''.join(c))
ascii_bin_strategy = strategy(ascii_text_strategy).map(
lambda s: convert_to_bytes(s)
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_strategy, ascii_bin_strategy)),
loc=one_of((ascii_text_strategy, ascii_bin_strategy)),
key=one_of((ascii_text_strategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
| Improve strategies in property tests | Improve strategies in property tests
| Python | mit | matrix-org/pymacaroons,matrix-org/pymacaroons,ecordell/pymacaroons,illicitonion/pymacaroons | ---
+++
@@ -7,14 +7,15 @@
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
+from pymacaroons.utils import convert_to_bytes
-ascii_text_stategy = strategy(text_type).map(
- lambda s: s.encode('ascii', 'ignore')
-)
+ascii_text_strategy = strategy(
+ [sampled_from(map(chr, range(0, 128)))]
+).map(lambda c: ''.join(c))
-ascii_bin_strategy = strategy(binary_type).map(
- lambda s: s.decode('ascii', 'ignore')
+ascii_bin_strategy = strategy(ascii_text_strategy).map(
+ lambda s: convert_to_bytes(s)
)
@@ -24,9 +25,9 @@
pass
@given(
- key_id=one_of((ascii_text_stategy, ascii_bin_strategy)),
- loc=one_of((ascii_text_stategy, ascii_bin_strategy)),
- key=one_of((ascii_text_stategy, ascii_bin_strategy))
+ key_id=one_of((ascii_text_strategy, ascii_bin_strategy)),
+ loc=one_of((ascii_text_strategy, ascii_bin_strategy)),
+ key=one_of((ascii_text_strategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key) |
6e8f35b83fc563c8349cb3be040c61a0588ca745 | rplugin/python3/LanguageClient/logger.py | rplugin/python3/LanguageClient/logger.py | import logging
logger = logging.getLogger("LanguageClient")
fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S"))
logger.addHandler(fileHandler)
logger.setLevel(logging.WARN)
| import logging
import tempfile
logger = logging.getLogger("LanguageClient")
with tempfile.NamedTemporaryFile(
prefix="LanguageClient-",
suffix=".log", delete=False) as tmp:
tmpname = tmp.name
fileHandler = logging.FileHandler(filename=tmpname)
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S"))
logger.addHandler(fileHandler)
logger.setLevel(logging.WARN)
| Use tempfile lib for log file | Use tempfile lib for log file
The fixed name for the log file causes issues for multiple users. The
tempfile library will create temporary files that don't conflict.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim | ---
+++
@@ -1,7 +1,12 @@
import logging
+import tempfile
logger = logging.getLogger("LanguageClient")
-fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
+with tempfile.NamedTemporaryFile(
+ prefix="LanguageClient-",
+ suffix=".log", delete=False) as tmp:
+ tmpname = tmp.name
+fileHandler = logging.FileHandler(filename=tmpname)
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s", |
1a8f67ec1eaa97aebe25d7d6625a237f8e1ce151 | example/tests/integration/test_includes.py | example/tests/integration/test_includes.py | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
assert [x.get('type') for x in included] == ['comments'], 'List included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
assert comment_count == expected_comment_count, 'List comment count is incorrect'
def test_included_data_on_detail(single_entry, client):
response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=comments')
included = load_json(response.content).get('included')
assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
assert comment_count == single_entry.comment_set.count(), 'Detail comment count is incorrect'
| import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
assert [x.get('type') for x in included] == ['comments', 'comments'], 'List included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
assert comment_count == expected_comment_count, 'List comment count is incorrect'
def test_included_data_on_detail(single_entry, client):
response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=comments')
included = load_json(response.content).get('included')
assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = single_entry.comment_set.count()
assert comment_count == expected_comment_count, 'Detail comment count is incorrect'
| Fix for test included_data_on_list included types check | Fix for test included_data_on_list included types check
| Python | bsd-2-clause | django-json-api/rest_framework_ember,scottfisk/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,leo-naeka/rest_framework_ember,abdulhaq-e/django-rest-framework-json-api | ---
+++
@@ -11,7 +11,7 @@
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
- assert [x.get('type') for x in included] == ['comments'], 'List included types are incorrect'
+ assert [x.get('type') for x in included] == ['comments', 'comments'], 'List included types are incorrect'
comment_count = len([resource for resource in included if resource["type"] == "comments"])
expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
@@ -23,5 +23,7 @@
included = load_json(response.content).get('included')
assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'
+
comment_count = len([resource for resource in included if resource["type"] == "comments"])
- assert comment_count == single_entry.comment_set.count(), 'Detail comment count is incorrect'
+ expected_comment_count = single_entry.comment_set.count()
+ assert comment_count == expected_comment_count, 'Detail comment count is incorrect' |
382b8df7a25732ee8384c02d776472a93c18a0ea | vcspull/__about__.py | vcspull/__about__.py | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013-2018 Tony Narlock'
| __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__docs__ = 'https://vcspull.git-pull.com'
__tracker__ = 'https://github.com/vcs-python/vcspull/issues'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013-Tony Narlock'
| Add docs / tracker to metadata | Add docs / tracker to metadata
| Python | mit | tony/vcspull,tony/vcspull | ---
+++
@@ -4,7 +4,9 @@
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
+__docs__ = 'https://vcspull.git-pull.com'
+__tracker__ = 'https://github.com/vcs-python/vcspull/issues'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
-__copyright__ = 'Copyright 2013-2018 Tony Narlock'
+__copyright__ = 'Copyright 2013-Tony Narlock' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.