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
244e760f27303fcfad220d364cd2d40f3de1cc99
src/pose.py
src/pose.py
#!/usr/bin/env python import rospy from nav_msgs.msg import Odometry publisher = None def send_computed_control_actions(msg): publisher.publish(msg) if __name__ == '__main__': rospy.init_node('pose') subscriber = rospy.Subscriber('computed_pose', Odometry, send_computed_control_actions) publisher = rospy.Publisher('cmd_vel', Odometry, queue_size=1) rospy.spin()
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist publisher = None def send_computed_control_actions(msg): publisher.publish(msg) if __name__ == '__main__': rospy.init_node('twist') subscriber = rospy.Subscriber('computed_control_actions', Twist, send_computed_control_actions) publisher = rospy.Publisher('cmd_vel', Twist, queue_size=1) rospy.spin()
Change publisher and subscriber message type from Odometry to Twist
Change publisher and subscriber message type from Odometry to Twist
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/env python import rospy -from nav_msgs.msg import Odometry +from geometry_msgs.msg import Twist publisher = None @@ -9,7 +9,7 @@ if __name__ == '__main__': - rospy.init_node('pose') - subscriber = rospy.Subscriber('computed_pose', Odometry, send_computed_control_actions) - publisher = rospy.Publisher('cmd_vel', Odometry, queue_size=1) + rospy.init_node('twist') + subscriber = rospy.Subscriber('computed_control_actions', Twist, send_computed_control_actions) + publisher = rospy.Publisher('cmd_vel', Twist, queue_size=1) rospy.spin()
574a2d98733cbab814050d29d1a24cd5c6563c4f
Tools/scripts/fixps.py
Tools/scripts/fixps.py
#! /usr/bin/env python # Fix Python script(s) to reference the interpreter via /usr/bin/env python. import sys import regex import regsub def main(): for file in sys.argv[1:]: try: f = open(file, 'r+') except IOError: print file, ': can\'t open for update' continue line = f.readline() if regex.match('^#! */usr/local/bin/python', line) < 0: print file, ': not a /usr/local/bin/python script' f.close() continue rest = f.read() line = regsub.sub('/usr/local/bin/python', '/usr/bin/env python', line) print file, ':', `line` f.seek(0) f.write(line) f.write(rest) f.close() main()
#!/usr/bin/env python # Fix Python script(s) to reference the interpreter via /usr/bin/env python. # Warning: this overwrites the file without making a backup. import sys import re def main(): for file in sys.argv[1:]: try: f = open(file, 'r') except IOError, msg: print file, ': can\'t open :', msg continue line = f.readline() if not re.match('^#! */usr/local/bin/python', line): print file, ': not a /usr/local/bin/python script' f.close() continue rest = f.read() f.close() line = re.sub('/usr/local/bin/python', '/usr/bin/env python', line) print file, ':', `line` f = open(file, "w") f.write(line) f.write(rest) f.close() main()
Use re instead of regex. Don't rewrite the file in place. (Reported by Andy Dustman.)
Use re instead of regex. Don't rewrite the file in place. (Reported by Andy Dustman.)
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,29 +1,30 @@ -#! /usr/bin/env python +#!/usr/bin/env python # Fix Python script(s) to reference the interpreter via /usr/bin/env python. +# Warning: this overwrites the file without making a backup. import sys -import regex -import regsub +import re def main(): for file in sys.argv[1:]: try: - f = open(file, 'r+') - except IOError: - print file, ': can\'t open for update' + f = open(file, 'r') + except IOError, msg: + print file, ': can\'t open :', msg continue line = f.readline() - if regex.match('^#! */usr/local/bin/python', line) < 0: + if not re.match('^#! */usr/local/bin/python', line): print file, ': not a /usr/local/bin/python script' f.close() continue rest = f.read() - line = regsub.sub('/usr/local/bin/python', - '/usr/bin/env python', line) + f.close() + line = re.sub('/usr/local/bin/python', + '/usr/bin/env python', line) print file, ':', `line` - f.seek(0) + f = open(file, "w") f.write(line) f.write(rest) f.close()
1bac187d32473e338e34bea5525e3384103113df
fireplace/cards/wog/warlock.py
fireplace/cards/wog/warlock.py
from ..utils import * ## # Minions class OG_121: "Cho'gall" play = Buff(CONTROLLER, "OG_121e") class OG_121e: events = OWN_SPELL_PLAY.on(Destroy(SELF)) update = Refresh(CONTROLLER, {GameTag.SPELLS_COST_HEALTH: True}) ## # Spells class OG_116: "Spreading Madness" play = Hit(RANDOM_CHARACTER, 1) * 9
from ..utils import * ## # Minions class OG_109: "Darkshire Librarian" play = Discard(RANDOM(FRIENDLY_HAND)) deathrattle = Draw(CONTROLLER) class OG_113: "Darkshire Councilman" events = Summon(MINION, CONTROLLER).on(Buff(SELF, "OG_113e")) OG_113e = buff(atk=1) class OG_121: "Cho'gall" play = Buff(CONTROLLER, "OG_121e") class OG_121e: events = OWN_SPELL_PLAY.on(Destroy(SELF)) update = Refresh(CONTROLLER, {GameTag.SPELLS_COST_HEALTH: True}) class OG_241: "Possessed Villager" deathrattle = Summon(CONTROLLER, "OG_241a") ## # Spells class OG_116: "Spreading Madness" play = Hit(RANDOM_CHARACTER, 1) * 9
Implement Darkshire Librarian, Darkshire Councilman, Possessed Villager
Implement Darkshire Librarian, Darkshire Councilman, Possessed Villager
Python
agpl-3.0
NightKev/fireplace,jleclanche/fireplace,beheh/fireplace
--- +++ @@ -3,6 +3,19 @@ ## # Minions + +class OG_109: + "Darkshire Librarian" + play = Discard(RANDOM(FRIENDLY_HAND)) + deathrattle = Draw(CONTROLLER) + + +class OG_113: + "Darkshire Councilman" + events = Summon(MINION, CONTROLLER).on(Buff(SELF, "OG_113e")) + +OG_113e = buff(atk=1) + class OG_121: "Cho'gall" @@ -13,6 +26,11 @@ update = Refresh(CONTROLLER, {GameTag.SPELLS_COST_HEALTH: True}) +class OG_241: + "Possessed Villager" + deathrattle = Summon(CONTROLLER, "OG_241a") + + ## # Spells
1f124ca4c13a0e5ceb9796bb1df95e5f31c5bd04
slot/users/models.py
slot/users/models.py
from flask_login import UserMixin class User(UserMixin): # proxy for a database of users user_database = {"test": ("slot", "test"), "live": ("slot", "live")} def __init__(self, username, password): self.id = username self.password = password @classmethod def get(cls, id): return cls.user_database.get(id)
from flask_login import UserMixin class User(UserMixin): def __init__(self, username, password): self.id = username self.password = password
Remove redundant parts of User class.
Remove redundant parts of User class.
Python
mit
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
--- +++ @@ -2,13 +2,7 @@ class User(UserMixin): - # proxy for a database of users - user_database = {"test": ("slot", "test"), "live": ("slot", "live")} def __init__(self, username, password): self.id = username self.password = password - - @classmethod - def get(cls, id): - return cls.user_database.get(id)
116893350b3618c07e05c671ff52d6f972430565
django_slack_oauth/__init__.py
django_slack_oauth/__init__.py
# -*- coding: utf-8 -*- from django.conf import settings __all__ = ( 'settings', ) default_settings = { 'SLACK_CLIENT_ID': None, 'SLACK_CLIENT_SECRET': None, 'SLACK_AUTHORIZATION_URL': 'https://slack.com/oauth/authorize', 'SLACK_OAUTH_ACCESS_URL': 'https://slack.com/api/oauth.access', 'SLACK_SUCCESS_REDIRECT_URL': '/', 'SLACK_SCOPE': 'identify,read,post', } class Settings(object): def __init__(self, app_settings, defaults): for k, v in defaults.iteritems(): setattr(self, k, getattr(app_settings, k, v)) settings = Settings(settings, default_settings)
# -*- coding: utf-8 -*- from django.conf import settings __all__ = ( 'settings', ) default_settings = { 'SLACK_CLIENT_ID': None, 'SLACK_CLIENT_SECRET': None, 'SLACK_AUTHORIZATION_URL': 'https://slack.com/oauth/authorize', 'SLACK_OAUTH_ACCESS_URL': 'https://slack.com/api/oauth.access', 'SLACK_SUCCESS_REDIRECT_URL': '/', 'SLACK_SCOPE': 'identify,read,post', } class Settings(object): def __init__(self, app_settings, defaults): for k, v in defaults.items(): setattr(self, k, getattr(app_settings, k, v)) settings = Settings(settings, default_settings)
Fix to iterate over dictionary using items instead of iteritems to make it compatible with python3.x.
Fix to iterate over dictionary using items instead of iteritems to make it compatible with python3.x.
Python
mit
izdi/django-slack-oauth,avelis/django-slack-oauth
--- +++ @@ -21,7 +21,7 @@ class Settings(object): def __init__(self, app_settings, defaults): - for k, v in defaults.iteritems(): + for k, v in defaults.items(): setattr(self, k, getattr(app_settings, k, v)) settings = Settings(settings, default_settings)
716282a16cefe1c34ae1bb1f8ffc6bb70879b5c2
wrappers/python/setup.py
wrappers/python/setup.py
from distutils.core import setup setup( name='python3-indy', version='0.0.1', packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=[], tests_require=['pytest', 'pytest-asyncio', 'base58'] )
from distutils.core import setup setup( name='python3-indy', version='0.0.1', packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['pytest', 'pytest-asyncio', 'base58'], tests_require=['pytest', 'pytest-asyncio', 'base58'] )
Revert install requre optimization in python wrapper.
Revert install requre optimization in python wrapper.
Python
apache-2.0
Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,korsimoro/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,korsimoro/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,korsimoro/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,korsimoro/indy-sdk
--- +++ @@ -9,6 +9,6 @@ author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', - install_requires=[], + install_requires=['pytest', 'pytest-asyncio', 'base58'], tests_require=['pytest', 'pytest-asyncio', 'base58'] )
736150f90d82a4583630b9999db94fa6afb47e10
test_samples/test_simple.py
test_samples/test_simple.py
# -*- encoding: utf-8 -*- """ """ import unittest import time class Case1(unittest.TestCase): def test_success(self): time.sleep(0.5) self.assertEqual(1, 1) def test_failure(self): time.sleep(0.5) self.assertEqual(1, 2) @unittest.skip("because") def test_skip(self): time.sleep(0.1) self.assertFalse(True) @unittest.expectedFailure def test_expected_failure(self): time.sleep(0.1) self.assertEqual(1, 0, "broken") @unittest.expectedFailure def test_unexpected_success(self): time.sleep(0.1) self.assertEqual(1, 1, "not broken after all") class Case2(unittest.TestCase): def test_success(self): self.assertTrue(True) class EmptyCase(unittest.TestCase): pass
# -*- encoding: utf-8 -*- """ """ import unittest import time class Case1(unittest.TestCase): def test_success(self): time.sleep(0.5) self.assertEqual(1, 1) def test_failure(self): time.sleep(0.5) self.assertEqual(1, 2) @unittest.skip("because") def test_skip(self): time.sleep(0.1) self.assertFalse(True) @unittest.expectedFailure def test_expected_failure(self): time.sleep(0.1) self.assertEqual(1, 0, "broken") @unittest.expectedFailure def test_unexpected_success(self): time.sleep(0.1) self.assertEqual(1, 1, "not broken after all") def test_error(self): raise RuntimeError("error raised for testing purpose") class Case2(unittest.TestCase): def test_success(self): self.assertTrue(True) class EmptyCase(unittest.TestCase): pass
Add a sample of erroneous test.
Add a sample of erroneous test.
Python
bsd-2-clause
nicolasdespres/hunittest
--- +++ @@ -31,6 +31,9 @@ time.sleep(0.1) self.assertEqual(1, 1, "not broken after all") + def test_error(self): + raise RuntimeError("error raised for testing purpose") + class Case2(unittest.TestCase): def test_success(self):
5dec9add35697dc77e2351bb076da90c6b56ea8d
oauth2_provider/utils.py
oauth2_provider/utils.py
import uuid import hashlib def short_hash(): """ Generate a unique short hash (40 bytes) which is suitable as a token, secret or id """ return hashlib.sha1(uuid.uuid1().get_bytes()).hexdigest() def long_hash(): """ Generate a unique long hash (128 bytes) which is suitable as a token, secret or id """ return hashlib.sha512(uuid.uuid1().get_bytes()).hexdigest()
import uuid import hashlib def short_hash(): """ Generate a unique short hash (40 bytes) which is suitable as a token, secret or id """ return hashlib.sha1(uuid.uuid1().bytes).hexdigest() def long_hash(): """ Generate a unique long hash (128 bytes) which is suitable as a token, secret or id """ return hashlib.sha512(uuid.uuid1().bytes).hexdigest()
Use bytes property with UUID objects
Use bytes property with UUID objects
Python
bsd-2-clause
JensTimmerman/django-oauth-toolkit,trbs/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,Gr1N/django-oauth-toolkit,cheif/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,Natgeoed/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,jensadne/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,Knotis/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,lzen/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,lzen/django-oauth-toolkit,trbs/django-oauth-toolkit,svetlyak40wt/django-oauth-toolkit,andrefsp/django-oauth-toolkit,natgeo/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,Knotis/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,jensadne/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,andrefsp/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,cheif/django-oauth-toolkit,Gr1N/django-oauth-toolkit
--- +++ @@ -6,11 +6,11 @@ """ Generate a unique short hash (40 bytes) which is suitable as a token, secret or id """ - return hashlib.sha1(uuid.uuid1().get_bytes()).hexdigest() + return hashlib.sha1(uuid.uuid1().bytes).hexdigest() def long_hash(): """ Generate a unique long hash (128 bytes) which is suitable as a token, secret or id """ - return hashlib.sha512(uuid.uuid1().get_bytes()).hexdigest() + return hashlib.sha512(uuid.uuid1().bytes).hexdigest()
f8292dced6aef64950280a33e9980a7998f07104
tests/services/shop/base.py
tests/services/shop/base.py
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from testfixtures.shop_article import create_article from testfixtures.shop_shop import create_shop from tests.base import AbstractAppTestCase from tests.helpers import DEFAULT_EMAIL_CONFIG_ID class ShopTestBase(AbstractAppTestCase): # -------------------------------------------------------------------- # # helpers def create_shop( self, shop_id='shop-1', email_config_id=DEFAULT_EMAIL_CONFIG_ID ): shop = create_shop(shop_id, email_config_id) self.db.session.add(shop) self.db.session.commit() return shop def create_article(self, shop_id, **kwargs): article = create_article(shop_id, **kwargs) self.db.session.add(article) self.db.session.commit() return article
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.article import service as article_service from testfixtures.shop_article import create_article from testfixtures.shop_shop import create_shop from tests.base import AbstractAppTestCase from tests.helpers import DEFAULT_EMAIL_CONFIG_ID class ShopTestBase(AbstractAppTestCase): # -------------------------------------------------------------------- # # helpers def create_shop( self, shop_id='shop-1', email_config_id=DEFAULT_EMAIL_CONFIG_ID ): shop = create_shop(shop_id, email_config_id) self.db.session.add(shop) self.db.session.commit() return shop def create_article(self, shop_id, **kwargs): article = create_article(shop_id, **kwargs) return article_service.create_article( shop_id, article.item_number, article.description, article.price, article.tax_rate, article.quantity, )
Create test articles via service
Create test articles via service
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
--- +++ @@ -2,6 +2,8 @@ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ + +from byceps.services.shop.article import service as article_service from testfixtures.shop_article import create_article from testfixtures.shop_shop import create_shop @@ -28,7 +30,11 @@ def create_article(self, shop_id, **kwargs): article = create_article(shop_id, **kwargs) - self.db.session.add(article) - self.db.session.commit() - - return article + return article_service.create_article( + shop_id, + article.item_number, + article.description, + article.price, + article.tax_rate, + article.quantity, + )
5d36f84fe96eb250760073ab186edc881217ae07
tests/test_iati_standard.py
tests/test_iati_standard.py
from web_test_base import * class TestIATIStandard(WebTestBase): """ TODO: Add tests to assert that: - the number of activities and publishers roughly matches those displayed on the Registry - the newsletter form is present - a key string appears on the homepage """ requests_to_load = { 'IATI Standard Homepage - no www': { 'url': 'http://iatistandard.org' }, 'IATI Standard Homepage - with www': { 'url': 'http://www.iatistandard.org' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) # Selection of header links assert "/en/news/" in result assert "/en/about/" in result assert "/en/iati-standard/" in result assert "/en/using-data/" in result # Selection of footer links assert "/en/contact/" in result assert "/en/terms-and-conditions/" in result assert "/en/privacy-policy/" in result
from web_test_base import * class TestIATIStandard(WebTestBase): """ TODO: Add tests to assert that: - the number of activities and publishers roughly matches those displayed on the Registry - a key string appears on the homepage """ requests_to_load = { 'IATI Standard Homepage - no www': { 'url': 'http://iatistandard.org' }, 'IATI Standard Homepage - with www': { 'url': 'http://www.iatistandard.org' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) # Selection of header links assert "/en/news/" in result assert "/en/about/" in result assert "/en/iati-standard/" in result assert "/en/using-data/" in result # Selection of footer links assert "/en/contact/" in result assert "/en/terms-and-conditions/" in result assert "/en/privacy-policy/" in result def test_newsletter_signup_form(self, loaded_request): """ Tests to confirm that there is always a form to subscribe to the newsletter within the footer. """ xpath = '//*[@id="mc-embedded-subscribe-form"]' result = utility.locate_xpath_result(loaded_request, xpath) assert len(result) == 1
Add iatistandard.org homepage test for the newsletter signup
Add iatistandard.org homepage test for the newsletter signup
Python
mit
IATI/IATI-Website-Tests
--- +++ @@ -4,7 +4,6 @@ """ TODO: Add tests to assert that: - the number of activities and publishers roughly matches those displayed on the Registry - - the newsletter form is present - a key string appears on the homepage """ requests_to_load = { @@ -33,4 +32,12 @@ assert "/en/terms-and-conditions/" in result assert "/en/privacy-policy/" in result + def test_newsletter_signup_form(self, loaded_request): + """ + Tests to confirm that there is always a form to subscribe to the newsletter within the footer. + """ + xpath = '//*[@id="mc-embedded-subscribe-form"]' + result = utility.locate_xpath_result(loaded_request, xpath) + + assert len(result) == 1
a7fdc9f834dec480236c397c03e7b929e74ccd80
shuup/default_reports/mixins.py
shuup/default_reports/mixins.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.db.models import Q from shuup.core.models import Order class OrderReportMixin(object): def get_objects(self): queryset = Order.objects.filter( shop=self.shop, order_date__range=(self.start_date, self.end_date)) creator = self.options.get("creator") orderer = self.options.get("orderer") customer = self.options.get("customer") filters = Q() if creator: filters &= Q(creator__in=creator) if orderer: filters &= Q(orderer__in=orderer) if customer: filters &= Q(customer__in=customer) return queryset.filter(filters).valid().paid().order_by("order_date")
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from datetime import timedelta from django.db.models import Q from shuup.core.models import Order from shuup.utils.dates import to_aware class OrderReportMixin(object): def get_objects(self): start = to_aware(self.start_date) # 0:00 on start_date end = to_aware(self.end_date) + timedelta(days=1) # 24:00 on end_date queryset = Order.objects.filter( shop=self.shop, order_date__range=(start, end)) creator = self.options.get("creator") orderer = self.options.get("orderer") customer = self.options.get("customer") filters = Q() if creator: filters &= Q(creator__in=creator) if orderer: filters &= Q(orderer__in=orderer) if customer: filters &= Q(customer__in=customer) return queryset.filter(filters).valid().paid().order_by("order_date")
Include orders which are made during selected end date in reports
Include orders which are made during selected end date in reports Comparing DateTimeField with date causes lack of precision which can occur with range. This causes orders which order_date is the same date than end_date will be not included in the queryset. Fix this problem with adding one extra day to the end_date value and so order made during the selected end date will be also included in the reports.
Python
agpl-3.0
shoopio/shoop,shoopio/shoop,shoopio/shoop
--- +++ @@ -5,17 +5,20 @@ # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. +from datetime import timedelta from django.db.models import Q from shuup.core.models import Order +from shuup.utils.dates import to_aware class OrderReportMixin(object): def get_objects(self): + start = to_aware(self.start_date) # 0:00 on start_date + end = to_aware(self.end_date) + timedelta(days=1) # 24:00 on end_date queryset = Order.objects.filter( - shop=self.shop, - order_date__range=(self.start_date, self.end_date)) + shop=self.shop, order_date__range=(start, end)) creator = self.options.get("creator") orderer = self.options.get("orderer") customer = self.options.get("customer")
1c9ce82c954ab206ec1b5387ef5cb49ab9c96208
additional_scripts/image-get-datastore-list.py
additional_scripts/image-get-datastore-list.py
#!/bin/python3 import os import xml.etree.ElementTree as ET oneimage = os.popen("oneimage list --xml") tree = ET.fromstring(oneimage.read()) #print(tree.tag) for image in tree.findall('./IMAGE'): imageid = image.find('./ID') print(imageid.text) for vmid in image.findall('./VMS/ID'): print(imageid.text+" "+vmid.text)
#!/bin/python3 import os import xml.etree.ElementTree as ET oneimage = os.popen("oneimage list --xml") tree = ET.fromstring(oneimage.read()) #print(tree.tag) for image in tree.findall('./IMAGE'): imageid = image.find('./ID') print(imageid.text) is_persistent = image.find('./PERSISTENT') if is_persistent.text == '1': continue for vmid in image.findall('./VMS/ID'): print(imageid.text+" "+vmid.text)
Exclude persistent images in list
Exclude persistent images in list
Python
apache-2.0
zhtlancer/addon-iscsi,zhtlancer/addon-iscsi
--- +++ @@ -12,6 +12,9 @@ for image in tree.findall('./IMAGE'): imageid = image.find('./ID') print(imageid.text) + is_persistent = image.find('./PERSISTENT') + if is_persistent.text == '1': + continue for vmid in image.findall('./VMS/ID'): print(imageid.text+" "+vmid.text)
66503b8d59a8bb5128bd05966c81fa949b4e5097
__init__.py
__init__.py
######################################################################## # # # This script was written by Thomas Heavey in 2017. # # theavey@bu.edu thomasjheavey@gmail.com # # # # Copyright 2017 Thomas J. Heavey IV # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # # implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ######################################################################## from __future__ import absolute_import from . import energyHisto from . import para_temp_setup from . import CoordinateAnalysis
######################################################################## # # # This script was written by Thomas Heavey in 2017. # # theavey@bu.edu thomasjheavey@gmail.com # # # # Copyright 2017 Thomas J. Heavey IV # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # # implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ######################################################################## from __future__ import absolute_import import sys from . import para_temp_setup if sys.version_info.major == 2: # These (at this point) require python 2 because of gromacs and MDAnalysis from . import energyHisto from . import CoordinateAnalysis
Check python version and possibly only import some things
Check python version and possibly only import some things
Python
apache-2.0
theavey/ParaTemp,theavey/ParaTemp
--- +++ @@ -23,6 +23,9 @@ ######################################################################## from __future__ import absolute_import -from . import energyHisto +import sys from . import para_temp_setup -from . import CoordinateAnalysis +if sys.version_info.major == 2: + # These (at this point) require python 2 because of gromacs and MDAnalysis + from . import energyHisto + from . import CoordinateAnalysis
72298e52d3621740f7f7b02098080caa56da19e8
asyncpgsa/__init__.py
asyncpgsa/__init__.py
from .pool import create_pool from .pgsingleton import PG from .connection import compile_query __version__ = '0.11.0' pg = PG()
from .pool import create_pool from .pgsingleton import PG from .connection import compile_query __version__ = '0.12.0' pg = PG()
Bump version to fix previous bad version
Bump version to fix previous bad version
Python
apache-2.0
CanopyTax/asyncpgsa
--- +++ @@ -2,6 +2,6 @@ from .pgsingleton import PG from .connection import compile_query -__version__ = '0.11.0' +__version__ = '0.12.0' pg = PG()
09dc09d88d04d2926e3ffc116cf5606aaf3dc681
salt/modules/win_wusa.py
salt/modules/win_wusa.py
# -*- coding: utf-8 -*- ''' Microsoft Update files management via wusa.exe :maintainer: Thomas Lemarchand :platform: Windows :depends: PowerShell ''' # Import python libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.platform log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'win_wusa' def __virtual__(): ''' Load only on Windows ''' if not salt.utils.platform.is_windows(): return False, 'Only available on Windows systems' powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=True) if not powershell_info['installed']: return False, 'PowerShell not available' return __virtualname__ def is_installed(kb): get_hotfix_result = __salt__['cmd.powershell_all']('Get-HotFix -Id {0}'.format(kb), ignore_retcode=True) return get_hotfix_result['retcode'] == 0 def install(path): return __salt__['cmd.run_all']('wusa.exe {0} /quiet /norestart'.format(path), ignore_retcode=True) def uninstall(kb): return __salt__['cmd.run_all']('wusa.exe /uninstall /kb:{0} /quiet /norestart'.format(kb[2:]), ignore_retcode=True)
# -*- coding: utf-8 -*- ''' Microsoft Update files management via wusa.exe :maintainer: Thomas Lemarchand :platform: Windows :depends: PowerShell ''' # Import python libs from __future__ import absolute_import import logging # Import salt libs import salt.utils.platform log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'win_wusa' def __virtual__(): ''' Load only on Windows ''' if not salt.utils.platform.is_windows(): return False, 'Only available on Windows systems' powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False) if not powershell_info['installed']: return False, 'PowerShell not available' return __virtualname__ def is_installed(kb): get_hotfix_result = __salt__['cmd.powershell_all']('Get-HotFix -Id {0}'.format(kb), ignore_retcode=True) return get_hotfix_result['retcode'] == 0 def install(path): return __salt__['cmd.run_all']('wusa.exe {0} /quiet /norestart'.format(path), ignore_retcode=True) def uninstall(kb): return __salt__['cmd.run_all']('wusa.exe /uninstall /kb:{0} /quiet /norestart'.format(kb[2:]), ignore_retcode=True) def list_kbs(): return __salt__['cmd.powershell']('Get-HotFix')
Disable powershell modules list Add list_kbs function
Disable powershell modules list Add list_kbs function
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -28,7 +28,7 @@ if not salt.utils.platform.is_windows(): return False, 'Only available on Windows systems' - powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=True) + powershell_info = __salt__['cmd.shell_info'](shell='powershell', list_modules=False) if not powershell_info['installed']: return False, 'PowerShell not available' @@ -50,3 +50,8 @@ def uninstall(kb): return __salt__['cmd.run_all']('wusa.exe /uninstall /kb:{0} /quiet /norestart'.format(kb[2:]), ignore_retcode=True) + + +def list_kbs(): + + return __salt__['cmd.powershell']('Get-HotFix')
4f67141cfabe99af99434364e13fec91bef291a7
grip/constants.py
grip/constants.py
# The supported extensions, as defined by https://github.com/github/markup supported_extensions = ['.md', '.markdown'] # The default filenames when no file is provided default_filenames = map(lambda ext: 'README' + ext, supported_extensions)
# The supported extensions, as defined by https://github.com/github/markup supported_extensions = [ '.markdown', '.mdown', '.mkdn', '.md', '.textile', '.rdoc', '.org', '.creole', '.mediawiki', '.wiki', '.rst', '.asciidoc', '.adoc', '.asc', '.pod', ] # The default filenames when no file is provided default_filenames = map(lambda ext: 'README' + ext, supported_extensions)
Add the GitHub-supported format extensions.
Add the GitHub-supported format extensions.
Python
mit
ssundarraj/grip,joeyespo/grip,ssundarraj/grip,jbarreras/grip,jbarreras/grip,joeyespo/grip,mgoddard-pivotal/grip,mgoddard-pivotal/grip
--- +++ @@ -1,5 +1,16 @@ # The supported extensions, as defined by https://github.com/github/markup -supported_extensions = ['.md', '.markdown'] +supported_extensions = [ + '.markdown', '.mdown', '.mkdn', '.md', + '.textile', + '.rdoc', + '.org', + '.creole', + '.mediawiki', '.wiki', + '.rst', + '.asciidoc', '.adoc', '.asc', + '.pod', +] + # The default filenames when no file is provided default_filenames = map(lambda ext: 'README' + ext, supported_extensions)
0174384553e22046438305d9accb735cc4a8f273
src/Flask/venv/demo/app/main.py
src/Flask/venv/demo/app/main.py
from flask import Flask, render_template from flask_socketio import SocketIO, send, emit app = Flask(__name__, template_folder='./templates') # Websocket setting app.config['SECRET_KEY'] = '12qwaszx' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') # @app.route('/<string:page_name>/') # def static_page(page_name): # return render_template('%s.html' % page_name) @socketio.on('message') def handle_message(message): print('received message: ' + message) @socketio.on('connect_event') def connected_event(msg): print('Received msg: %s', msg) emit('server_response', {'data': msg['data']}, broadcast=True) @socketio.on('save receipt') def handle_json(json): print('Received json: ' + str(json)) emit('save-reveipt response', {'isSuccess': 'true'}) if __name__=='__main__': socketio.run(app)
from flask import Flask, render_template, request, jsonify from flask_socketio import SocketIO, send, emit import json app = Flask(__name__, template_folder='./templates') # Websocket setting app.config['SECRET_KEY'] = '12qwaszx' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @app.route('/send', methods=['GET', 'POST']) def send(): """Receive a message and brodcast to all connected clients """ jsonobj_content = request.json socketio.emit('server_response', {'data':str(jsonobj_content)}, broadcast=True) return '', 200 # @app.route('/<string:page_name>/') # def static_page(page_name): # return render_template('%s.html' % page_name) @socketio.on('connect_event') def connected_event(msg): """WebSocket connect event This will trigger responsing a message to client by """ print('Received msg: %s', msg) emit('server_response', {'data': msg['data']}) if __name__=='__main__': socketio.run(app)
Create a broadcast api: send
Create a broadcast api: send
Python
mit
KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice
--- +++ @@ -1,5 +1,8 @@ -from flask import Flask, render_template +from flask import Flask, render_template, request, jsonify from flask_socketio import SocketIO, send, emit +import json + + app = Flask(__name__, template_folder='./templates') # Websocket setting @@ -10,24 +13,26 @@ def index(): return render_template('index.html') +@app.route('/send', methods=['GET', 'POST']) +def send(): + """Receive a message and brodcast to all connected clients + """ + jsonobj_content = request.json + socketio.emit('server_response', {'data':str(jsonobj_content)}, broadcast=True) + return '', 200 + # @app.route('/<string:page_name>/') # def static_page(page_name): # return render_template('%s.html' % page_name) -@socketio.on('message') -def handle_message(message): - print('received message: ' + message) - @socketio.on('connect_event') def connected_event(msg): + """WebSocket connect event + This will trigger responsing a message to client by + """ print('Received msg: %s', msg) - emit('server_response', {'data': msg['data']}, broadcast=True) - -@socketio.on('save receipt') -def handle_json(json): - print('Received json: ' + str(json)) - emit('save-reveipt response', {'isSuccess': 'true'}) + emit('server_response', {'data': msg['data']}) if __name__=='__main__': socketio.run(app)
a40415604a9a8bbdc7833d850c4f74d66236d334
systemvm/patches/debian/config/opt/cloud/bin/cs_staticroutes.py
systemvm/patches/debian/config/opt/cloud/bin/cs_staticroutes.py
# -- coding: utf-8 -- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 pprint import pprint def merge(dbag, staticroutes): for route in staticroutes['routes']: key = route['network'] revoke = route['revoke'] if revoke: try: del dbag[key] except KeyError: pass else: dbag[key] = route return dbag
# -- coding: utf-8 -- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 pprint import pprint def merge(dbag, staticroutes): for route in staticroutes['routes']: key = route['network'] dbag[key] = route return dbag
Make deleting static routes in private gw work
CLOUDSTACK-9266: Make deleting static routes in private gw work
Python
apache-2.0
jcshen007/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,wido/cloudstack,jcshen007/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack
--- +++ @@ -21,13 +21,5 @@ def merge(dbag, staticroutes): for route in staticroutes['routes']: key = route['network'] - revoke = route['revoke'] - if revoke: - try: - del dbag[key] - except KeyError: - pass - else: - dbag[key] = route - + dbag[key] = route return dbag
de3218c662f5fa98dac57e7f875cbe49efbc1b78
time_lapse.py
time_lapse.py
#!/usr/bin/env python import time import picamera from settings import Job, IMAGES_DIRECTORY def main(): job = Job() if job.exists(): resolution_x = job.image_settings.resolution_x resolution_y = job.image_settings.resolution_y image_quality = job.image_settings.quality snap_interval = job.snap_settings.interval snap_total = job.snap_settings.total with picamera.PiCamera() as camera: camera.resolution = (resolution_x, resolution_y) time.sleep(2) output_file = IMAGES_DIRECTORY + '/img{counter:03d}.jpg' capture = camera.capture_continuous(output_file, quality=image_quality) for i, _ in enumerate(capture): if i == snap_total - 1: job.archive() break time.sleep(snap_interval) if __name__ == '__main__': while True: main()
#!/usr/bin/env python import time import picamera from settings import Job, IMAGES_DIRECTORY def main(): job = Job() if job.exists(): resolution_x = job.image_settings.resolution_x resolution_y = job.image_settings.resolution_y image_quality = job.image_settings.quality snap_interval = job.snap_settings.interval snap_total = job.snap_settings.total image_file_prefix = job.image_settings.prefix output_file = IMAGES_DIRECTORY + '/' + image_file_prefix + '_{counter:03d}.jpg' with picamera.PiCamera() as camera: camera.resolution = (resolution_x, resolution_y) time.sleep(2) capture = camera.capture_continuous(output_file, quality=image_quality) for i, _ in enumerate(capture): if i == snap_total - 1: job.archive() break time.sleep(snap_interval) if __name__ == '__main__': while True: main()
Add image prefix for job settings
Add image prefix for job settings
Python
mit
projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse
--- +++ @@ -13,10 +13,11 @@ image_quality = job.image_settings.quality snap_interval = job.snap_settings.interval snap_total = job.snap_settings.total + image_file_prefix = job.image_settings.prefix + output_file = IMAGES_DIRECTORY + '/' + image_file_prefix + '_{counter:03d}.jpg' with picamera.PiCamera() as camera: camera.resolution = (resolution_x, resolution_y) time.sleep(2) - output_file = IMAGES_DIRECTORY + '/img{counter:03d}.jpg' capture = camera.capture_continuous(output_file, quality=image_quality) for i, _ in enumerate(capture): if i == snap_total - 1:
fce5d034f007248b74f3d16843d4cdc0d2f50721
postgres/search/views.py
postgres/search/views.py
import json from django.http import HttpResponse from django.core.urlresolvers import reverse from django.utils.html import conditional_escape as escape from .models import Search def uikit(request): searches = Search.objects.filter(term__matches='%s:*' % request.GET['search']) return HttpResponse(json.dumps({ 'results': [ { 'title': escape(search.title), 'url': reverse(search.url_name, kwargs=search.url_kwargs), 'text': escape(search.detail), } for search in searches ] }))
import json from django.http import HttpResponse from django.core.urlresolvers import reverse from django.utils.html import conditional_escape as escape from .models import Search def uikit(request): searches = Search.objects.filter(term__matches='%s:*' % request.GET['search'].lower()) return HttpResponse(json.dumps({ 'results': [ { 'title': escape(search.title), 'url': reverse(search.url_name, kwargs=search.url_kwargs), 'text': escape(search.detail), } for search in searches ] }))
Make search term lower case so capitals match.
Make search term lower case so capitals match.
Python
bsd-3-clause
wlanslovenija/django-postgres
--- +++ @@ -7,7 +7,7 @@ from .models import Search def uikit(request): - searches = Search.objects.filter(term__matches='%s:*' % request.GET['search']) + searches = Search.objects.filter(term__matches='%s:*' % request.GET['search'].lower()) return HttpResponse(json.dumps({ 'results': [
3bd010690bdbc7ba64c1c15709880368fb78b3e8
polyaxon/event_monitors/apps.py
polyaxon/event_monitors/apps.py
from django.apps import AppConfig class EventsConfig(AppConfig): name = 'event_monitors' verbose_name = 'EventMonitors'
from django.apps import AppConfig class EventMonitorsConfig(AppConfig): name = 'event_monitors' verbose_name = 'EventMonitors'
Fix event monitors app config
Fix event monitors app config
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -1,6 +1,6 @@ from django.apps import AppConfig -class EventsConfig(AppConfig): +class EventMonitorsConfig(AppConfig): name = 'event_monitors' verbose_name = 'EventMonitors'
312c699491830daacd33f032a6d6fc6cc6ff0c96
ports/esp32/modules/inisetup.py
ports/esp32/modules/inisetup.py
import uos from flashbdev import bdev def check_bootsec(): buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE bdev.readblocks(0, buf) empty = True for b in buf: if b != 0xFF: empty = False break if empty: return True fs_corrupted() def fs_corrupted(): import time while 1: print( """\ FAT filesystem appears to be corrupted. If you had important data there, you may want to make a flash snapshot to try to recover it. Otherwise, perform factory reprogramming of MicroPython firmware (completely erase flash, followed by firmware programming). """ ) time.sleep(3) def setup(): check_bootsec() print("Performing initial setup") uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/") with open("boot.py", "w") as f: f.write( """\ # This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) #import webrepl #webrepl.start() """ ) return vfs
import uos from flashbdev import bdev def check_bootsec(): buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE bdev.readblocks(0, buf) empty = True for b in buf: if b != 0xFF: empty = False break if empty: return True fs_corrupted() def fs_corrupted(): import time while 1: print( """\ FAT filesystem appears to be corrupted. If you had important data there, you may want to make a flash snapshot to try to recover it. Otherwise, perform factory reprogramming of MicroPython firmware (completely erase flash, followed by firmware programming). """ ) time.sleep(3) def setup(): check_bootsec() print("Performing initial setup") uos.VfsLfs2.mkfs(bdev) vfs = uos.VfsLfs2(bdev) uos.mount(vfs, "/") with open("boot.py", "w") as f: f.write( """\ # This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) #import webrepl #webrepl.start() """ ) return vfs
Change from FAT to littlefs v2 as default filesystem.
esp32: Change from FAT to littlefs v2 as default filesystem. This commit changes the default filesystem type for esp32 to littlefs v2. This port already enables both VfsFat and VfsLfs2, so either can be used for the filesystem, and existing systems that use FAT will still work.
Python
mit
pramasoul/micropython,MrSurly/micropython,tobbad/micropython,MrSurly/micropython,adafruit/circuitpython,MrSurly/micropython,adafruit/circuitpython,kerneltask/micropython,tobbad/micropython,adafruit/circuitpython,selste/micropython,pramasoul/micropython,henriknelson/micropython,henriknelson/micropython,selste/micropython,bvernoux/micropython,MrSurly/micropython,adafruit/circuitpython,MrSurly/micropython,pramasoul/micropython,bvernoux/micropython,selste/micropython,kerneltask/micropython,bvernoux/micropython,selste/micropython,kerneltask/micropython,bvernoux/micropython,henriknelson/micropython,henriknelson/micropython,henriknelson/micropython,kerneltask/micropython,tobbad/micropython,tobbad/micropython,kerneltask/micropython,bvernoux/micropython,pramasoul/micropython,adafruit/circuitpython,tobbad/micropython,pramasoul/micropython,adafruit/circuitpython,selste/micropython
--- +++ @@ -33,8 +33,8 @@ def setup(): check_bootsec() print("Performing initial setup") - uos.VfsFat.mkfs(bdev) - vfs = uos.VfsFat(bdev) + uos.VfsLfs2.mkfs(bdev) + vfs = uos.VfsLfs2(bdev) uos.mount(vfs, "/") with open("boot.py", "w") as f: f.write(
4227bda80f6aa33356e527399e79c633ef018089
mzgtfs/__init__.py
mzgtfs/__init__.py
"""A simple GTFS library. This package is used internally to read and process GTFS files and to create OnestopIds. """ __version__ = '0.10.3'
"""A simple GTFS library. This package is used internally to read and process GTFS files and to create OnestopIds. """ __version__ = 'master'
Set master version to 'master'
Set master version to 'master'
Python
mit
brechtvdv/mapzen-gtfs,brennan-v-/mapzen-gtfs,transitland/mapzen-gtfs
--- +++ @@ -4,4 +4,4 @@ """ -__version__ = '0.10.3' +__version__ = 'master'
760ca4809259df4cf24d77385f35bf41ec1c5383
kolibri/__init__.py
kolibri/__init__.py
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils.version import get_version #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 9, 0, 'alpha', 0) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org' __version__ = str(get_version(VERSION))
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils.version import get_version #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 9, 0, 'beta', 0) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org' __version__ = str(get_version(VERSION))
Update 0.9 from alpha to beta
Update 0.9 from alpha to beta
Python
mit
indirectlylit/kolibri,benjaoming/kolibri,learningequality/kolibri,christianmemije/kolibri,benjaoming/kolibri,benjaoming/kolibri,jonboiser/kolibri,christianmemije/kolibri,DXCanas/kolibri,lyw07/kolibri,indirectlylit/kolibri,learningequality/kolibri,jonboiser/kolibri,benjaoming/kolibri,DXCanas/kolibri,mrpau/kolibri,DXCanas/kolibri,lyw07/kolibri,indirectlylit/kolibri,christianmemije/kolibri,learningequality/kolibri,jonboiser/kolibri,lyw07/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,indirectlylit/kolibri,mrpau/kolibri,DXCanas/kolibri,christianmemije/kolibri,jonboiser/kolibri
--- +++ @@ -6,7 +6,7 @@ #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. -VERSION = (0, 9, 0, 'alpha', 0) +VERSION = (0, 9, 0, 'beta', 0) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org'
ce4ee9558ed0c53e03cb31627c597d5388b56ffa
docs/examples/compute/cloudstack/start_interactive_shell_ikoula.py
docs/examples/compute/cloudstack/start_interactive_shell_ikoula.py
import os from IPython.terminal.embed import InteractiveShellEmbed from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security as sec sec.VERIFY_SSL_CERT = False apikey = os.getenv('IKOULA_API_KEY') secretkey = os.getenv('IKOULA_SECRET_KEY') Driver = get_driver(Provider.IKOULA) conn = Driver(key=apikey, secret=secretkey) shell = InteractiveShellEmbed(banner1='Hello from Libcloud Shell !!') shell()
import os from IPython.terminal.embed import InteractiveShellEmbed from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = os.getenv('IKOULA_API_KEY') secretkey = os.getenv('IKOULA_SECRET_KEY') Driver = get_driver(Provider.IKOULA) conn = Driver(key=apikey, secret=secretkey) shell = InteractiveShellEmbed(banner1='Hello from Libcloud Shell !!') shell()
Update example, no need to disable cert validation.
docs: Update example, no need to disable cert validation.
Python
apache-2.0
briancurtin/libcloud,Cloud-Elasticity-Services/as-libcloud,niteoweb/libcloud,lochiiconnectivity/libcloud,wrigri/libcloud,apache/libcloud,JamesGuthrie/libcloud,atsaki/libcloud,andrewsomething/libcloud,wido/libcloud,cryptickp/libcloud,Itxaka/libcloud,iPlantCollaborativeOpenSource/libcloud,mistio/libcloud,sahildua2305/libcloud,andrewsomething/libcloud,pquentin/libcloud,vongazman/libcloud,sergiorua/libcloud,Scalr/libcloud,munkiat/libcloud,DimensionDataCBUSydney/libcloud,thesquelched/libcloud,marcinzaremba/libcloud,erjohnso/libcloud,dcorbacho/libcloud,schaubl/libcloud,kater169/libcloud,iPlantCollaborativeOpenSource/libcloud,carletes/libcloud,carletes/libcloud,schaubl/libcloud,mtekel/libcloud,smaffulli/libcloud,jerryblakley/libcloud,jimbobhickville/libcloud,ZuluPro/libcloud,watermelo/libcloud,briancurtin/libcloud,marcinzaremba/libcloud,Itxaka/libcloud,SecurityCompass/libcloud,dcorbacho/libcloud,apache/libcloud,sgammon/libcloud,aleGpereira/libcloud,t-tran/libcloud,Cloud-Elasticity-Services/as-libcloud,DimensionDataCBUSydney/libcloud,sergiorua/libcloud,erjohnso/libcloud,ByteInternet/libcloud,thesquelched/libcloud,jerryblakley/libcloud,pantheon-systems/libcloud,ZuluPro/libcloud,iPlantCollaborativeOpenSource/libcloud,aviweit/libcloud,MrBasset/libcloud,cryptickp/libcloud,jerryblakley/libcloud,cloudControl/libcloud,atsaki/libcloud,mathspace/libcloud,mbrukman/libcloud,pquentin/libcloud,SecurityCompass/libcloud,cloudControl/libcloud,vongazman/libcloud,watermelo/libcloud,techhat/libcloud,mgogoulos/libcloud,niteoweb/libcloud,munkiat/libcloud,illfelder/libcloud,NexusIS/libcloud,mtekel/libcloud,aleGpereira/libcloud,wuyuewen/libcloud,smaffulli/libcloud,marcinzaremba/libcloud,smaffulli/libcloud,supertom/libcloud,t-tran/libcloud,Kami/libcloud,techhat/libcloud,Verizon/libcloud,carletes/libcloud,t-tran/libcloud,schaubl/libcloud,wuyuewen/libcloud,atsaki/libcloud,mistio/libcloud,pquentin/libcloud,ByteInternet/libcloud,StackPointCloud/libcloud,mathspace/libcloud,thesquelched/libcloud,Verizon/libcloud,wido/libcloud,sgammon/libcloud,pantheon-systems/libcloud,Kami/libcloud,lochiiconnectivity/libcloud,sergiorua/libcloud,briancurtin/libcloud,wuyuewen/libcloud,illfelder/libcloud,curoverse/libcloud,samuelchong/libcloud,DimensionDataCBUSydney/libcloud,wido/libcloud,MrBasset/libcloud,Scalr/libcloud,JamesGuthrie/libcloud,Verizon/libcloud,JamesGuthrie/libcloud,mtekel/libcloud,samuelchong/libcloud,sfriesel/libcloud,ClusterHQ/libcloud,sfriesel/libcloud,SecurityCompass/libcloud,kater169/libcloud,aviweit/libcloud,sfriesel/libcloud,Kami/libcloud,pantheon-systems/libcloud,munkiat/libcloud,ByteInternet/libcloud,Cloud-Elasticity-Services/as-libcloud,supertom/libcloud,illfelder/libcloud,StackPointCloud/libcloud,StackPointCloud/libcloud,aleGpereira/libcloud,mbrukman/libcloud,lochiiconnectivity/libcloud,NexusIS/libcloud,wrigri/libcloud,curoverse/libcloud,mistio/libcloud,erjohnso/libcloud,supertom/libcloud,ZuluPro/libcloud,andrewsomething/libcloud,jimbobhickville/libcloud,Itxaka/libcloud,MrBasset/libcloud,kater169/libcloud,dcorbacho/libcloud,mgogoulos/libcloud,vongazman/libcloud,Scalr/libcloud,ClusterHQ/libcloud,aviweit/libcloud,niteoweb/libcloud,cryptickp/libcloud,cloudControl/libcloud,NexusIS/libcloud,mbrukman/libcloud,samuelchong/libcloud,mgogoulos/libcloud,jimbobhickville/libcloud,wrigri/libcloud,watermelo/libcloud,curoverse/libcloud,mathspace/libcloud,sahildua2305/libcloud,sahildua2305/libcloud,techhat/libcloud,apache/libcloud
--- +++ @@ -4,9 +4,6 @@ from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver -import libcloud.security as sec - -sec.VERIFY_SSL_CERT = False apikey = os.getenv('IKOULA_API_KEY') secretkey = os.getenv('IKOULA_SECRET_KEY')
a0f9275912d3dfd9edd4e8d0377f04972c919338
lino_book/projects/team/try_people_api.py
lino_book/projects/team/try_people_api.py
import requests from apiclient.discovery import build from lino.api import rt user = rt.models.users.User.objects.get(username='luc') social = user.social_auth.get(provider='google-plus') print(social.provider) response = requests.get( 'https://www.googleapis.com/plus/v1/people/me/people/collection', # 'https://www.googleapis.com/plus/v1/people/me/people/visible', params={'access_token': social.extra_data['access_token']} ) friends = response.json()['items'] print(friends) people_service = build(serviceName='people', version='v1', http=http)
from apiclient.discovery import build from oauth2client.client import OAuth2Credentials from django.conf import settings from datetime import datetime import httplib2 from lino.api import rt user = rt.models.users.User.objects.get(username='8618a3571d8b4237a3e60d25671d8f') social = user.social_auth.get(provider='google-plus') print(social.provider) print (social.extra_data) # response = requests.get( # 'https://www.googleapis.com/plus/v1/people/me/people/collection', # 'https://www.googleapis.com/plus/v1/people/me/people/visible', # params={'access_token': social.extra_data['access_token']} # ) # friends = response.json()['items'] # print(friends) revoke_uri = None user_agent = 'PythonSocialAuth' credentials = OAuth2Credentials( social.extra_data['access_token'], settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY, settings.SOCIAL_AUTH_GOOGLE_PLUS_SECRET, '', datetime.fromtimestamp(social.extra_data['auth_time']), revoke_uri, user_agent, scopes=settings.SOCIAL_AUTH_GOOGLE_PLUS_SCOPE ) http = httplib2.Http() http = credentials.authorize(http) people_service = build(serviceName='people', version='v1', http=http) connections = people_service.people().connections().list( resourceName='people/me', pageSize=10, personFields='names,emailAddresses').execute() # contactToUpdate = people_service.people().get(resourceName=social.extra_data['user_id'],personFields='names,emailAddresses').execute() print (connections)
Make the sample work by retrieving all contacts.
Make the sample work by retrieving all contacts.
Python
unknown
lsaffre/lino_book,khchine5/book,lino-framework/book,lsaffre/lino_book,lino-framework/book,lino-framework/book,lino-framework/book,khchine5/book,khchine5/book,lsaffre/lino_book
--- +++ @@ -1,18 +1,44 @@ -import requests from apiclient.discovery import build - +from oauth2client.client import OAuth2Credentials +from django.conf import settings +from datetime import datetime +import httplib2 from lino.api import rt -user = rt.models.users.User.objects.get(username='luc') +user = rt.models.users.User.objects.get(username='8618a3571d8b4237a3e60d25671d8f') social = user.social_auth.get(provider='google-plus') print(social.provider) -response = requests.get( - 'https://www.googleapis.com/plus/v1/people/me/people/collection', - # 'https://www.googleapis.com/plus/v1/people/me/people/visible', - params={'access_token': social.extra_data['access_token']} +print (social.extra_data) +# response = requests.get( +# 'https://www.googleapis.com/plus/v1/people/me/people/collection', +# 'https://www.googleapis.com/plus/v1/people/me/people/visible', +# params={'access_token': social.extra_data['access_token']} +# ) +# friends = response.json()['items'] +# print(friends) +revoke_uri = None +user_agent = 'PythonSocialAuth' + +credentials = OAuth2Credentials( + social.extra_data['access_token'], + settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY, + settings.SOCIAL_AUTH_GOOGLE_PLUS_SECRET, + '', + datetime.fromtimestamp(social.extra_data['auth_time']), + revoke_uri, + user_agent, + scopes=settings.SOCIAL_AUTH_GOOGLE_PLUS_SCOPE ) -friends = response.json()['items'] -print(friends) + +http = httplib2.Http() +http = credentials.authorize(http) people_service = build(serviceName='people', version='v1', http=http) +connections = people_service.people().connections().list( + resourceName='people/me', + pageSize=10, + personFields='names,emailAddresses').execute() + +# contactToUpdate = people_service.people().get(resourceName=social.extra_data['user_id'],personFields='names,emailAddresses').execute() +print (connections)
5d643a8f4a5e689cb2c5aaa0e98efcf17862fc3e
src/hydro/connectors/vertica.py
src/hydro/connectors/vertica.py
__author__ = 'moshebasanchig' from hydro.connectors.base_classes import DBBaseConnector import pyodbc from hydro.exceptions import HydroException DSN = 'dsn' class VerticaConnector(DBBaseConnector): """ implementation of Vertica connector, base function that need to be implemented are _connect, _close and _execute """ def _connect(self): if self._conf_defs['connection_type'] == DSN: conn_string = 'DSN=%s' % self._conf_defs['connection_string'] self.logger.debug('Connect to {0}'.format(conn_string)) self._conn = pyodbc.connect(conn_string) else: #TODO need to be implemented based on connection string raise HydroException("Vertica connection string connection is not implemented") if __name__ == '__main__': params = { 'source_type': 'vertica', 'connection_type': 'dsn', 'connection_string': 'VerticaDSN', 'db_name': '', 'db_user': '', 'db_password': '' } con = VerticaConnector(params) print con.execute('select 1')
__author__ = 'moshebasanchig' from hydro.connectors.base_classes import DBBaseConnector, DSN import pyodbc from hydro.exceptions import HydroException class VerticaConnector(DBBaseConnector): """ implementation of Vertica connector, base function that need to be implemented are _connect, _close and _execute """ def _connect(self): if self._conf_defs['connection_type'] == DSN: conn_string = 'DSN=%s' % self._conf_defs['connection_string'] self.logger.debug('Connect to {0}'.format(conn_string)) self._conn = pyodbc.connect(conn_string) else: #TODO need to be implemented based on connection string raise HydroException("Vertica connection string connection is not implemented") if __name__ == '__main__': params = { 'source_type': 'vertica', 'connection_type': 'dsn', 'connection_string': 'VerticaDSN', 'db_name': '', 'db_user': '', 'db_password': '' } con = VerticaConnector(params) print con.execute('select 1')
Define the DSN const in a central location
Define the DSN const in a central location
Python
mit
Convertro/Hydro,Convertro/Hydro
--- +++ @@ -1,10 +1,8 @@ __author__ = 'moshebasanchig' -from hydro.connectors.base_classes import DBBaseConnector +from hydro.connectors.base_classes import DBBaseConnector, DSN import pyodbc from hydro.exceptions import HydroException - -DSN = 'dsn' class VerticaConnector(DBBaseConnector):
be2d33152c07594465c9b838c060edeaa8bc6ddc
tests/main.py
tests/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from ParseArticleReferenceTest import ParseArticleReferenceTest from SortReferencesVisitorTest import SortReferencesVisitorTest from ParseEditTest import ParseEditTest from ParseAlineaReferenceTest import ParseAlineaReferenceTest from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest from ParseSentenceDefinitionTest import ParseSentenceDefinitionTest from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from ParseArticleReferenceTest import ParseArticleReferenceTest from SortReferencesVisitorTest import SortReferencesVisitorTest from ParseEditTest import ParseEditTest from ParseAlineaReferenceTest import ParseAlineaReferenceTest from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest if __name__ == '__main__': unittest.main()
Fix broken reference to ParseSentenceDefinitionTest.
Fix broken reference to ParseSentenceDefinitionTest.
Python
mit
Legilibre/duralex
--- +++ @@ -8,7 +8,6 @@ from ParseEditTest import ParseEditTest from ParseAlineaReferenceTest import ParseAlineaReferenceTest from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest -from ParseSentenceDefinitionTest import ParseSentenceDefinitionTest from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest
e73409c17c89ef54f5c7e807059b229517e77617
mailchute/smtpd/mailchute.py
mailchute/smtpd/mailchute.py
import datetime import smtpd from email.parser import Parser from mailchute import db from mailchute import settings from mailchute.model import RawMessage, IncomingEmail from logbook import Logger logger = Logger(__name__) class MessageProcessor(object): def _should_persist(self, recipient): allowed_receiver_domain = settings.RECEIVER_DOMAIN recipient_domain = recipient.split('@')[1].lower() return (allowed_receiver_domain is None or recipient_domain == settings.RECEIVER_DOMAIN) def __call__(self, peer, mailfrom, recipients, data): try: mailfrom = mailfrom.lower() recipients = list(map(str.lower, recipients)) logger.info( "Incoming message from {0} to {1}".format(mailfrom, recipients)) email = Parser().parsestr(data) raw_message = RawMessage(message=data) for recipient in recipients: if self._should_persist(recipient): incoming_email = IncomingEmail( sender=mailfrom, recipient=recipient, raw_message=raw_message, subject=email['subject'], created_at=datetime.datetime.now(), ) db.session.add(incoming_email) else: logger.info('{} is not an allowed recipient. Skip.'.format( recipient)) db.session.commit() logger.info("Message saved") except Exception as e: # pragma: no cover logger.exception(e) db.session.rollback() class MailchuteSMTPServer(smtpd.SMTPServer): process_message = MessageProcessor()
import datetime import smtpd from email.parser import Parser from mailchute import db from mailchute import settings from mailchute.model import RawMessage, IncomingEmail from logbook import Logger logger = Logger(__name__) class MessageProcessor(object): def _should_persist(self, recipient): recipient_domain = recipient.split('@')[1].lower() allowed_receiver_domains = settings.RECEIVER_DOMAIN if allowed_receiver_domains: allowed_receiver_domains = allowed_receiver_domains.split(',') return (allowed_receiver_domains is None or recipient_domain in allowed_receiver_domains) def __call__(self, peer, mailfrom, recipients, data): try: mailfrom = mailfrom.lower() recipients = list(map(str.lower, recipients)) logger.info( "Incoming message from {0} to {1}".format(mailfrom, recipients)) email = Parser().parsestr(data) raw_message = RawMessage(message=data) for recipient in recipients: if self._should_persist(recipient): incoming_email = IncomingEmail( sender=mailfrom, recipient=recipient, raw_message=raw_message, subject=email['subject'], created_at=datetime.datetime.now(), ) db.session.add(incoming_email) else: logger.info('{} is not an allowed recipient. Skip.'.format( recipient)) db.session.commit() logger.info("Message saved") except Exception as e: # pragma: no cover logger.exception(e) db.session.rollback() class MailchuteSMTPServer(smtpd.SMTPServer): process_message = MessageProcessor()
Handle multiple receiver domain properly
Handle multiple receiver domain properly
Python
bsd-3-clause
kevinjqiu/mailchute,kevinjqiu/mailchute
--- +++ @@ -12,10 +12,12 @@ class MessageProcessor(object): def _should_persist(self, recipient): - allowed_receiver_domain = settings.RECEIVER_DOMAIN recipient_domain = recipient.split('@')[1].lower() - return (allowed_receiver_domain is None - or recipient_domain == settings.RECEIVER_DOMAIN) + allowed_receiver_domains = settings.RECEIVER_DOMAIN + if allowed_receiver_domains: + allowed_receiver_domains = allowed_receiver_domains.split(',') + return (allowed_receiver_domains is None + or recipient_domain in allowed_receiver_domains) def __call__(self, peer, mailfrom, recipients, data): try:
cfc9c21121f06007dd582fe6cd0162e4df2a21d5
tests/test_cle_gdb.py
tests/test_cle_gdb.py
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
Test fix. rebase_addr to mapped_base
fix: Test fix. rebase_addr to mapped_base
Python
bsd-2-clause
schieb/angr,iamahuman/angr,iamahuman/angr,f-prettyland/angr,axt/angr,f-prettyland/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,axt/angr,tyb0807/angr,schieb/angr,schieb/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,iamahuman/angr,angr/angr,f-prettyland/angr,axt/angr
--- +++ @@ -9,8 +9,8 @@ def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] - nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) - nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) + nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) + nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """
a3674958a046de711e37445d39afd4e529d8dd09
bin/run_t2r_trainer.py
bin/run_t2r_trainer.py
# coding=utf-8 # Copyright 2020 The Tensor2Robot Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as python3 """Binary for training TFModels with Estimator API.""" from absl import app from absl import flags import gin from tensor2robot.utils import train_eval import tensorflow.compat.v1 as tf FLAGS = flags.FLAGS def main(unused_argv): gin.parse_config_files_and_bindings(FLAGS.gin_configs, FLAGS.gin_bindings) train_eval.train_eval_model() if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) app.run(main)
# coding=utf-8 # Copyright 2020 The Tensor2Robot Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as python3 """Binary for training TFModels with Estimator API.""" from absl import app from absl import flags import gin from tensor2robot.utils import train_eval import tensorflow.compat.v1 as tf FLAGS = flags.FLAGS def main(unused_argv): gin.parse_config_files_and_bindings( FLAGS.gin_configs, FLAGS.gin_bindings, print_includes_and_imports=True) train_eval.train_eval_model() if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) app.run(main)
Print gin config includes and imports when starting training.
Print gin config includes and imports when starting training. PiperOrigin-RevId: 342367820
Python
apache-2.0
google-research/tensor2robot
--- +++ @@ -27,7 +27,8 @@ def main(unused_argv): - gin.parse_config_files_and_bindings(FLAGS.gin_configs, FLAGS.gin_bindings) + gin.parse_config_files_and_bindings( + FLAGS.gin_configs, FLAGS.gin_bindings, print_includes_and_imports=True) train_eval.train_eval_model()
0068c9da4b8af1d51928ce3d2f326130dbf342f2
_scripts/cfdoc_bootstrap.py
_scripts/cfdoc_bootstrap.py
#!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2013 CFEngine AS # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import cfdoc_environment as environment import cfdoc_git as git import sys config = environment.validate() try: git.createData(config) except: print "cfdoc_preprocess: Fatal error generating git tags" sys.stdout.write(" Exception: ") print sys.exc_info() exit(1) exit(0)
#!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2013 CFEngine AS # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import cfdoc_environment as environment import cfdoc_git as git import sys config = environment.validate(sys.argv[1]) try: git.createData(config) except: print "cfdoc_preprocess: Fatal error generating git tags" sys.stdout.write(" Exception: ") print sys.exc_info() exit(1) exit(0)
Fix environment.validate() being called without branch name.
Fix environment.validate() being called without branch name.
Python
mit
michaelclelland/documentation-generator,stweil/documentation-generator,stweil/documentation-generator,nickanderson/documentation-generator,cfengine/documentation-generator,michaelclelland/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,michaelclelland/documentation-generator,cfengine/documentation-generator,stweil/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,stweil/documentation-generator,cfengine/documentation-generator,nickanderson/documentation-generator,stweil/documentation-generator,michaelclelland/documentation-generator,nickanderson/documentation-generator,michaelclelland/documentation-generator
--- +++ @@ -26,7 +26,7 @@ import cfdoc_git as git import sys -config = environment.validate() +config = environment.validate(sys.argv[1]) try: git.createData(config)
3364747195f0f3d2711169fb92c250fc10823d82
default_settings.py
default_settings.py
# Copyright 2014 0xc0170 # # 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. import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: pass
# Copyright 2014 0xc0170 # # 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. import logging import os UV4 = os.path.join("C:","Keil","UV4","UV4.exe") IARBUILD = os.path.join('C:','Program Files (x86)','IAR Systems','Embedded Workbench 7.0','common','bin','IarBuild.exe') # Be able to locate project generator anywhere in a project # By default it's tools/project_generator (2 folders deep from root) PROJECT_ROOT= os.path.join('..','..') if os.name == "posix": # Expects either arm-none-eabi to be installed here, or # even better, a symlink from /usr/local/arm-none-eabi to the most recent # version. gcc_bin_path = "/usr/local/arm-none-eabi/bin/" elif os.name == "nt": gcc_bin_path = "" try: from user_settings import * except: logging.info("Using default settings.")
Add message if you're using default settings
Add message if you're using default settings
Python
apache-2.0
0xc0170/valinor,sarahmarshy/project_generator,autopulated/valinor,ARMmbed/valinor,sg-/project_generator,ohagendorf/project_generator,molejar/project_generator,aethaniel/project_generator,0xc0170/project_generator,sg-/project_generator,project-generator/project_generator,hwfwgrp/project_generator
--- +++ @@ -32,4 +32,4 @@ try: from user_settings import * except: - pass + logging.info("Using default settings.")
7f1ae8ac882dff05332e9f98f5b6396224392723
api/libs/spec_validation.py
api/libs/spec_validation.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.core.exceptions import ValidationError from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError from polyaxon_schemas.polyaxonfile.specification import GroupSpecification def validate_spec_content(content): try: return GroupSpecification.read(content) except (PolyaxonfileError, PolyaxonConfigurationError): raise ValidationError('Received non valid specification content.')
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.core.exceptions import ValidationError from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError from polyaxon_schemas.polyaxonfile.specification import GroupSpecification def validate_spec_content(content): try: spec = GroupSpecification.read(content) except (PolyaxonfileError, PolyaxonConfigurationError): raise ValidationError('Received non valid specification content.') if spec.is_local: raise ValidationError('Received specification content for a local environment run.') return spec
Raise validation error if spec is in local run mode
Raise validation error if spec is in local run mode
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -8,6 +8,11 @@ def validate_spec_content(content): try: - return GroupSpecification.read(content) + spec = GroupSpecification.read(content) except (PolyaxonfileError, PolyaxonConfigurationError): raise ValidationError('Received non valid specification content.') + + if spec.is_local: + raise ValidationError('Received specification content for a local environment run.') + + return spec
dc251707fdcd9fe021b6f8627ffbb139d42423b3
cairis/test/CairisDaemonTestCase.py
cairis/test/CairisDaemonTestCase.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 time import sleep import unittest import os import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisDaemonTestCase(unittest.TestCase): cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh" os.system(cmd) app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 time import sleep import unittest import os import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisDaemonTestCase(unittest.TestCase): srcRoot = os.environ['CAIRIS_SRC'] createDbSql = srcRoot + '/test/createdb.sql' sqlDir = srcRoot + '/sql' initSql = sqlDir + '/init.sql' procsSql = sqlDir + '/procs.sql' cmd = "/usr/bin/mysql --user=root --password='' < " + createDbSql os.system(cmd) cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + initSql os.system(cmd) cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + procsSql os.system(cmd) app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
Change database init script for daemon tests
Change database init script for daemon tests
Python
apache-2.0
nathanbjenx/cairis,nathanbjenx/cairis,nathanbjenx/cairis,failys/CAIRIS,failys/CAIRIS,failys/CAIRIS,nathanbjenx/cairis
--- +++ @@ -24,7 +24,16 @@ class CairisDaemonTestCase(unittest.TestCase): - cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh" + srcRoot = os.environ['CAIRIS_SRC'] + createDbSql = srcRoot + '/test/createdb.sql' + sqlDir = srcRoot + '/sql' + initSql = sqlDir + '/init.sql' + procsSql = sqlDir + '/procs.sql' + cmd = "/usr/bin/mysql --user=root --password='' < " + createDbSql + os.system(cmd) + cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + initSql + os.system(cmd) + cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + procsSql os.system(cmd) app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
d705c4ffbe60a11a0cde55f5caa2324349366bab
irctest/optional_extensions.py
irctest/optional_extensions.py
import unittest import operator import itertools class NotImplementedByController(unittest.SkipTest, NotImplementedError): def __str__(self): return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): """Small wrapper around unittest.TextTestRunner that reports the number of tests that were skipped because the software does not support an optional feature.""" def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in sorted(msg_to_tests): print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
import unittest import operator import collections class NotImplementedByController(unittest.SkipTest, NotImplementedError): def __str__(self): return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): """Small wrapper around unittest.TextTestRunner that reports the number of tests that were skipped because the software does not support an optional feature.""" def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional ' 'specifications/mechanisms are not supported:') msg_to_count = collections.defaultdict(lambda: 0) for (test, msg) in result.skipped: msg_to_count[msg] += 1 for (msg, count) in sorted(msg_to_count.items()): print('\t{} ({} test(s))'.format(msg, count)) return result
Fix output of skipped tests.
Fix output of skipped tests.
Python
mit
ProgVal/irctest
--- +++ @@ -1,6 +1,6 @@ import unittest import operator -import itertools +import collections class NotImplementedByController(unittest.SkipTest, NotImplementedError): def __str__(self): @@ -22,10 +22,11 @@ result = super().run(test) if result.skipped: print() - print('Some tests were skipped because the following optional' + print('Some tests were skipped because the following optional ' 'specifications/mechanisms are not supported:') - msg_to_tests = itertools.groupby(result.skipped, - key=operator.itemgetter(1)) - for (msg, tests) in sorted(msg_to_tests): - print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) + msg_to_count = collections.defaultdict(lambda: 0) + for (test, msg) in result.skipped: + msg_to_count[msg] += 1 + for (msg, count) in sorted(msg_to_count.items()): + print('\t{} ({} test(s))'.format(msg, count)) return result
448f412790220a48a26c595c9dd6f6a5f412d995
pylons/__init__.py
pylons/__init__.py
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.config import config __all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = g = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = c = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = g = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = c = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
Fix an import error. pylons.config doesn't exist anymore, use pylons.configuration
Fix an import error. pylons.config doesn't exist anymore, use pylons.configuration
Python
bsd-3-clause
obeattie/pylons,obeattie/pylons
--- +++ @@ -1,7 +1,7 @@ """Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy -from pylons.config import config +from pylons.configuration import config __all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response', 'session', 'tmpl_context', 'url']
69f0b89c306b6a616e3db2716669a2aa04453222
cogs/default.py
cogs/default.py
import time from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" msg = await ctx.send("Pong! :ping_pong:") before = time.monotonic() await (await ctx.bot.ws.ping()) after = time.monotonic() ping_time = (after - before) * 1000 await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
Use bot.latency for ping time
Use bot.latency for ping time
Python
mit
BeatButton/beattie,BeatButton/beattie-bot
--- +++ @@ -1,5 +1,3 @@ -import time - from discord.ext import commands @@ -7,14 +5,7 @@ @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" - msg = await ctx.send("Pong! :ping_pong:") - - before = time.monotonic() - await (await ctx.bot.ws.ping()) - after = time.monotonic() - ping_time = (after - before) * 1000 - - await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') + await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') @commands.command() async def source(self, ctx):
e40e30170b76ce7761a398d6c9ee7bac1f18a621
organizer/forms.py
organizer/forms.py
from django import forms from django.core.exceptions import ValidationError from .models import Tag class TagForm(forms.ModelForm): class Meta: model = Tag exclude = tuple() def clean_name(self): return self.cleaned_data['name'].lower() def clean_slug(self): new_slug = ( self.cleaned_data['slug'].lower()) if new_slug == 'create': raise ValidationError( 'Slug may not be "create".') return new_slug
from django import forms from django.core.exceptions import ValidationError from .models import Tag class TagForm(forms.ModelForm): class Meta: model = Tag fields = '__all__' def clean_name(self): return self.cleaned_data['name'].lower() def clean_slug(self): new_slug = ( self.cleaned_data['slug'].lower()) if new_slug == 'create': raise ValidationError( 'Slug may not be "create".') return new_slug
Revert TagForm Meta fields option.
Ch07: Revert TagForm Meta fields option.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
--- +++ @@ -7,7 +7,7 @@ class TagForm(forms.ModelForm): class Meta: model = Tag - exclude = tuple() + fields = '__all__' def clean_name(self): return self.cleaned_data['name'].lower()
ad7d39c472130e7f06c30d06a5aed465d2e5ab2c
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}: {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)
Reformat cmd to go under 120 character limit
Reformat cmd to go under 120 character limit
Python
mit
SublimeLinter/SublimeLinter-cppcheck
--- +++ @@ -2,7 +2,14 @@ class Cppcheck(Linter): - cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}') + 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+'
cf948bd38a57b459db9f37ac584207f36cb3610e
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Contributors: Francis Gulotta, Josh Hagins # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Contributors: Francis Gulotta, Josh Hagins # Copyright (c) 2013 Aparajita Fishman # # License: MIT # """This module exports the Rubocop plugin class.""" from SublimeLinter.lint import RubyLinter class Rubocop(RubyLinter): """Provides an interface to rubocop.""" syntax = ('ruby', 'ruby on rails', 'rspec', 'betterruby', 'ruby experimental') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.15.0' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(:?(?P<warning>[RCW])|(?P<error>[EF])): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', '.rubocop.yml')
Add support for RubyNext and RubyExperimental
Add support for RubyNext and RubyExperimental
Python
mit
SublimeLinter/SublimeLinter-rubocop
--- +++ @@ -18,7 +18,7 @@ """Provides an interface to rubocop.""" - syntax = ('ruby', 'ruby on rails', 'rspec') + syntax = ('ruby', 'ruby on rails', 'rspec', 'betterruby', 'ruby experimental') cmd = 'ruby -S rubocop --format emacs' version_args = '-S rubocop --version' version_re = r'(?P<version>\d+\.\d+\.\d+)'
2e9527d00358027a3f85d3087734ab4e87441fc4
reporting_scripts/user_info.py
reporting_scripts/user_info.py
''' This module will retrieve info about students registered in the course Usage: python user_info.py ''' from collections import defaultdict from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile') collection = connection.get_access_to_collection() documents = collection['auth_userprofile'].find() result = [] for document in documents: user_id = document['user_id'] try: final_grade = collection['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade'] except: print user_id result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']]) output = CSV(result, ['User ID','Username', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City'], output_file='atoc185x_user_info.csv') output.generate_csv()
''' This module will retrieve info about students registered in the course Usage: python user_info.py ''' from collections import defaultdict from base_edx import EdXConnection from generate_csv_report import CSV connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile') collection = connection.get_access_to_collection() documents = collection['auth_userprofile'].find() result = [] for document in documents: user_id = document['user_id'] try: final_grade = collection['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade'] result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']]) except: # Handle users with no grades pass output = CSV(result, ['User ID','Username', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City'], output_file='atoc185x_user_info.csv') output.generate_csv()
Update to handle users with no final grade
Update to handle users with no final grade
Python
mit
andyzsf/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
--- +++ @@ -23,9 +23,10 @@ user_id = document['user_id'] try: final_grade = collection['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade'] + result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']]) except: - print user_id - result.append([user_id, document['name'], final_grade, document['gender'], document['year_of_birth'], document['level_of_education'], document['country'], document['city']]) + # Handle users with no grades + pass output = CSV(result, ['User ID','Username', 'Final Grade', 'Gender', 'Year of Birth', 'Level of Education', 'Country', 'City'], output_file='atoc185x_user_info.csv') output.generate_csv()
aada9a317eb8aed5dcd8ff6731692ef25ff52a67
packtets/graph/generator.py
packtets/graph/generator.py
import igraph def packing_graph(tets, vx, vy, vz, independent = 0): N = len(tets) g = igraph.Graph() g.add_vertices(N) for i in range(N): for j in range(max(i, independent),N): for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)): if tets[i].collision(s): g.add_edge(i,j) break edges = g.get_edgelist() for i in range(N, -1, -1): if (i,i) in edges: g.delete_vertices(g.vs[i]) del tets[i] return g
import igraph def packing_graph(tets, vx, vy, vz, independent = 0): N = len(tets) for i in range(N-1, independent-1, -1): for s in tets[i].get_symetry(vx, vy, vz, include_self=False): if tets[i].collision(s): del tets[i] break N = len(tets) g = igraph.Graph() g.add_vertices(N) for i in range(N): for j in range(max(i, independent),N): for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)): if tets[i].collision(s): g.add_edge(i,j) break return g
Remove self-touching tets first to reduce collision load.
Remove self-touching tets first to reduce collision load.
Python
mit
maxhutch/packtets,maxhutch/packtets
--- +++ @@ -1,6 +1,13 @@ import igraph def packing_graph(tets, vx, vy, vz, independent = 0): + N = len(tets) + for i in range(N-1, independent-1, -1): + for s in tets[i].get_symetry(vx, vy, vz, include_self=False): + if tets[i].collision(s): + del tets[i] + break + N = len(tets) g = igraph.Graph() g.add_vertices(N) @@ -10,9 +17,5 @@ if tets[i].collision(s): g.add_edge(i,j) break - edges = g.get_edgelist() - for i in range(N, -1, -1): - if (i,i) in edges: - g.delete_vertices(g.vs[i]) - del tets[i] + return g
a72cf5997439533d7ce74d6c4fc50d1189466c1b
peloid/app/shell/service.py
peloid/app/shell/service.py
from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace)
from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace)
Set initial mode to lobby.
Set initial mode to lobby.
Python
mit
oubiwann/peloid
--- +++ @@ -3,6 +3,7 @@ from carapace.util import ssh as util +from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell @@ -17,6 +18,7 @@ These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() + game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal)
4c2cc3c8a37082fe4d87f0a522e440cead8d2b4f
geotrek/common/migrations/0011_attachment_add_is_image.py
geotrek/common/migrations/0011_attachment_add_is_image.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2020-02-28 17:30 from __future__ import unicode_literals from django.db import migrations import mimetypes def forward(apps, schema_editor): AttachmentModel = apps.get_model('common', 'Attachment') for attachment in AttachmentModel.objects.all(): if mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0].split('/')[0].startswith('image'): attachment.is_image = True attachment.save() class Migration(migrations.Migration): dependencies = [ ('common', '0010_attachment_is_image'), ] operations = [ migrations.RunPython(forward), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2020-02-28 17:30 from __future__ import unicode_literals from django.db import migrations import mimetypes def forward(apps, schema_editor): AttachmentModel = apps.get_model('common', 'Attachment') for attachment in AttachmentModel.objects.all(): mt = mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0] if mt is not None and mt.split('/')[0].startswith('image'): attachment.is_image = True attachment.save() class Migration(migrations.Migration): dependencies = [ ('common', '0010_attachment_is_image'), ] operations = [ migrations.RunPython(forward), ]
Check if mt is None before spliting it
Check if mt is None before spliting it
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin
--- +++ @@ -10,7 +10,8 @@ def forward(apps, schema_editor): AttachmentModel = apps.get_model('common', 'Attachment') for attachment in AttachmentModel.objects.all(): - if mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0].split('/')[0].startswith('image'): + mt = mimetypes.guess_type(attachment.attachment_file.name, strict=True)[0] + if mt is not None and mt.split('/')[0].startswith('image'): attachment.is_image = True attachment.save()
8c19549071782f3a07f1a6f1656817bb36b00dbe
manage.py
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feed_to_kippt.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import re def read_env(): """Pulled from Honcho code with minor updates, reads local default environment variables from a .env file located in the project root directory. """ try: with open('.env') as f: content = f.read() except IOError: content = '' for line in content.splitlines(): m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) if m1: key, val = m1.group(1), m1.group(2) m2 = re.match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', r'\1', m3.group(1)) os.environ.setdefault(key, val) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feed_to_kippt.settings") from django.core.management import execute_from_command_line read_env() execute_from_command_line(sys.argv)
Read from local environment file if available
Read from local environment file if available
Python
mit
jpadilla/feedleap,jpadilla/feedleap
--- +++ @@ -1,10 +1,37 @@ #!/usr/bin/env python import os import sys +import re + + +def read_env(): + """Pulled from Honcho code with minor updates, reads local default + environment variables from a .env file located in the project root + directory. + + """ + try: + with open('.env') as f: + content = f.read() + except IOError: + content = '' + + for line in content.splitlines(): + m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) + if m1: + key, val = m1.group(1), m1.group(2) + m2 = re.match(r"\A'(.*)'\Z", val) + if m2: + val = m2.group(1) + m3 = re.match(r'\A"(.*)"\Z', val) + if m3: + val = re.sub(r'\\(.)', r'\1', m3.group(1)) + os.environ.setdefault(key, val) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "feed_to_kippt.settings") from django.core.management import execute_from_command_line + read_env() execute_from_command_line(sys.argv)
64c31f5630975a30a8187ad51566b4ff723b4d28
nengo_spinnaker/simulator.py
nengo_spinnaker/simulator.py
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None, use_serial=False): # Build the model self.builder = builder.Builder(use_serial=use_serial) self.dao = self.builder(model, dt, seed) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None, use_serial=False): # Build the model self.builder = builder.Builder() self.dao = self.builder(model, dt, seed, use_serial=use_serial) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
Correct `Builder.__call__` parameters when called by the `Simulator`
Correct `Builder.__call__` parameters when called by the `Simulator`
Python
mit
ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014
--- +++ @@ -9,8 +9,8 @@ class Simulator(object): def __init__(self, model, dt=0.001, seed=None, use_serial=False): # Build the model - self.builder = builder.Builder(use_serial=use_serial) - self.dao = self.builder(model, dt, seed) + self.builder = builder.Builder() + self.dao = self.builder(model, dt, seed, use_serial=use_serial) self.dao.writeTextSpecs = True def run(self, time):
71d227e96eeeac09dc7fc25298600f159cf338a0
categories/serializers.py
categories/serializers.py
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories') class CategorySimpleSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight')
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories') class CategorySimpleSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required')
Add comment_required to category simple serializer
Add comment_required to category simple serializer
Python
apache-2.0
belatrix/BackendAllStars
--- +++ @@ -38,4 +38,4 @@ class CategorySimpleSerializer(serializers.ModelSerializer): class Meta: model = Category - fields = ('pk', 'name', 'weight') + fields = ('pk', 'name', 'weight', 'comment_required')
8fce8e72f5ff40e51605f3b14bcde5006f4eaa71
molly/utils/i18n.py
molly/utils/i18n.py
from django.utils.translation import get_language from django.db.models import Model from django.conf import settings try: from django.utils.translation import override except ImportError: from django.utils.translation import activate, deactivate class override(object): def __init__(self, language, deactivate=False): self.language = language self.deactivate = deactivate self.old_language = get_language() def __enter__(self): activate(self.language) def __exit__(self, exc_type, exc_value, traceback): if self.deactivate: deactivate() else: activate(self.old_language) def name_in_language(obj, field): try: return getattr(obj.names.get(language_code=get_language()), field) except Model.DoesNotExist: try: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE), field) except Model.DoesNotExist: if '-' in settings.LANGUAGE_CODE: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE.split('-')[0]), field) else: raise
from django.utils.translation import get_language from django.db.models import Model from django.conf import settings from django.core.exceptions import ObjectDoesNotExist try: from django.utils.translation import override except ImportError: from django.utils.translation import activate, deactivate class override(object): def __init__(self, language, deactivate=False): self.language = language self.deactivate = deactivate self.old_language = get_language() def __enter__(self): activate(self.language) def __exit__(self, exc_type, exc_value, traceback): if self.deactivate: deactivate() else: activate(self.old_language) def name_in_language(obj, field): try: return getattr(obj.names.get(language_code=get_language()), field) except ObjectDoesNotExist: try: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE), field) except ObjectDoesNotExist: if '-' in settings.LANGUAGE_CODE: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE.split('-')[0]), field) else: raise
Fix bug in exception handling
Fix bug in exception handling
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
--- +++ @@ -1,6 +1,7 @@ from django.utils.translation import get_language from django.db.models import Model from django.conf import settings +from django.core.exceptions import ObjectDoesNotExist try: from django.utils.translation import override @@ -25,10 +26,10 @@ def name_in_language(obj, field): try: return getattr(obj.names.get(language_code=get_language()), field) - except Model.DoesNotExist: + except ObjectDoesNotExist: try: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE), field) - except Model.DoesNotExist: + except ObjectDoesNotExist: if '-' in settings.LANGUAGE_CODE: return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE.split('-')[0]), field) else:
57d95df9147de57be3652e633de394095b0de54f
test/bindertest/testdbconfig.py
test/bindertest/testdbconfig.py
from binder import Sqlite3Connection from binder import MysqlConnection import os # sqlite3 _bindertest_dir = os.path.dirname( __file__ ) DBFILE = os.path.join(_bindertest_dir, "test.db3") def connect_sqlite3(read_only=None): return Sqlite3Connection(DBFILE, read_only) # MySQL - modify as needed MYSQL_TESTDB = { "host": "localhost", "user": "bindertest", "passwd": "binderpassword", "db": "bindertestdb", } def connect_mysql(read_only=None, isolation_level=None): d = dict(MYSQL_TESTDB) d['read_only'] = read_only if isolation_level: d['isolation_level'] = isolation_level return MysqlConnection(**d) # Test DB - modify as needed #connect = connect_sqlite3 connect = connect_mysql
from binder import Sqlite3Connection from binder import MysqlConnection import os # sqlite3 _bindertest_dir = os.path.dirname( __file__ ) DBFILE = os.path.join(_bindertest_dir, "test.db3") def connect_sqlite3(read_only=None): return Sqlite3Connection(DBFILE, read_only) # MySQL - modify as needed MYSQL_TESTDB = { "host": "localhost", "user": "bindertest", "passwd": "binderpassword", "db": "bindertestdb", } def connect_mysql(read_only=None, isolation_level=None): d = dict(MYSQL_TESTDB) d['read_only'] = read_only if isolation_level: d['isolation_level'] = isolation_level return MysqlConnection(**d) # Test DB - modify as needed connect = connect_sqlite3 #connect = connect_mysql
Make SQLite the default test setup
Make SQLite the default test setup
Python
mit
divtxt/binder
--- +++ @@ -26,6 +26,6 @@ # Test DB - modify as needed -#connect = connect_sqlite3 -connect = connect_mysql +connect = connect_sqlite3 +#connect = connect_mysql
4148feec637dbc1b6619cd45ed14b4d4fb6f4148
sequencefinding.py
sequencefinding.py
"""Finding a sequence. Usage: sequencefinding.py NUMBERS... Arguments: NUMBERS your sequence of numbers """ import docopt def differences(a): return [t - s for s, t in zip(a, a[1:])] def constant_difference(a): if len(a) <= 1: return None if all(a[1] - a[0] == x for x in differences(a)): return a[1] - a[0] else: return None def linear_difference(a): depth = 1 while len(a) > 0: cdiff = constant_difference(a) if cdiff is not None: return cdiff, depth a = differences(a) depth += 1 return None args = docopt.docopt(__doc__) numbers = list(map(int, args['NUMBERS'])) lin_diff = linear_difference(numbers) if lin_diff is not None: print("Found a linear difference of {} on layer {}.".format(*lin_diff))
"""Finding a sequence. Usage: sequencefinding.py NUMBERS... Arguments: NUMBERS your sequence of numbers """ import docopt def differences(a): return [t - s for s, t in zip(a, a[1:])] def constant_difference(a): if len(a) <= 1: return None if all(a[1] - a[0] == x for x in differences(a)): return a[1] - a[0] else: return None def linear_difference(a): depth = 1 while len(a) > 0: cdiff = constant_difference(a) if cdiff is not None: return cdiff, depth a = differences(a) depth += 1 return None args = docopt.docopt(__doc__) numbers = list(map(int, args['NUMBERS'])) lin_diff = linear_difference(numbers) if lin_diff is not None: print("Found a linear difference of {} on layer {}.".format(*lin_diff)) else: print("No sequence found.")
Add fallback message when no sequence was found
Add fallback message when no sequence was found
Python
mit
joostrijneveld/sequencefinder
--- +++ @@ -38,3 +38,5 @@ if lin_diff is not None: print("Found a linear difference of {} on layer {}.".format(*lin_diff)) +else: + print("No sequence found.")
715e304de7a61e4cd14f26afe819d1eeb1d72f2e
server/api/serializers/rides.py
server/api/serializers/rides.py
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = RideRiders fields = ('ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = RideRiders fields = ('id', 'ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
Send RideRegistration id through with api response
Send RideRegistration id through with api response
Python
mit
Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers
--- +++ @@ -23,7 +23,7 @@ class Meta: model = RideRiders - fields = ('ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') + fields = ('id', 'ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(),
0e8bd8248cc649637b7c392616887c50986427a0
telethon/__init__.py
telethon/__init__.py
from .client.telegramclient import TelegramClient from .network import connection from .tl import types, functions, custom from .tl.custom import Button from . import version, events, utils, errors __version__ = version.__version__ __all__ = [ 'TelegramClient', 'Button', 'types', 'functions', 'custom', 'errors', 'events', 'utils', 'connection' ]
from .client.telegramclient import TelegramClient from .network import connection from .tl import types, functions, custom from .tl.custom import Button from .tl import patched as _ # import for its side-effects from . import version, events, utils, errors __version__ = version.__version__ __all__ = [ 'TelegramClient', 'Button', 'types', 'functions', 'custom', 'errors', 'events', 'utils', 'connection' ]
Fix patched module was never automatically imported
Fix patched module was never automatically imported Closes #1701. It has to be imported late in the process of `import telethon` for its side-effects.
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon
--- +++ @@ -2,6 +2,7 @@ from .network import connection from .tl import types, functions, custom from .tl.custom import Button +from .tl import patched as _ # import for its side-effects from . import version, events, utils, errors __version__ = version.__version__
2992bb8abc6844c2086ceee59a9b586b5e9a3aff
tests/integration/wheel/key.py
tests/integration/wheel/key.py
# coding: utf-8 # Import Salt Testing libs from __future__ import absolute_import import integration # Import Salt libs import salt.wheel class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn): def setUp(self): self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config'))) def test_list_all(self): ret = self.wheel.cmd('key.list_all', print_event=False) for host in ['minion', 'sub_minion']: self.assertIn(host, ret['minions']) def test_gen(self): ret = self.wheel.cmd('key.gen', id_='soundtechniciansrock', print_event=False) self.assertIn('pub', ret) self.assertIn('priv', ret) self.assertTrue( ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----')) self.assertTrue( ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----')) if __name__ == '__main__': from integration import run_tests run_tests(KeyWheelModuleTest, needs_daemon=True)
# coding: utf-8 # Import Salt Testing libs from __future__ import absolute_import import integration # Import Salt libs import salt.wheel class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn): def setUp(self): self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config'))) def test_list_all(self): ret = self.wheel.cmd('key.list_all', print_event=False) for host in ['minion', 'sub_minion']: self.assertIn(host, ret['minions']) def test_gen(self): ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False) self.assertIn('pub', ret) self.assertIn('priv', ret) self.assertTrue( ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----')) self.assertTrue( ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----')) if __name__ == '__main__': from integration import run_tests run_tests(KeyWheelModuleTest, needs_daemon=True)
Fix args err in wheel test
Fix args err in wheel test
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -18,7 +18,7 @@ self.assertIn(host, ret['minions']) def test_gen(self): - ret = self.wheel.cmd('key.gen', id_='soundtechniciansrock', print_event=False) + ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False) self.assertIn('pub', ret) self.assertIn('priv', ret)
aec36263dac9037afa0343dcef87ae97530e1ad3
semanticizest/_semanticizer.py
semanticizest/_semanticizer.py
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): targets.sort(key=operator.itemgetter(1)) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) targets = ((t, count / total) for t, count in targets) self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
Return commonness instead of raw counts
Return commonness instead of raw counts
Python
apache-2.0
semanticize/semanticizest
--- +++ @@ -13,12 +13,12 @@ for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): - targets.sort(key=operator.itemgetter(1)) + # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) - targets = ((t, count / total) for t, count in targets) + commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N
6ba3ae92d1bf72f5076ebf35b2b370cfebb8f390
tkp/utility/redirect_stream.py
tkp/utility/redirect_stream.py
import os from tempfile import SpooledTemporaryFile from contextlib import contextmanager @contextmanager def redirect_stream(output_stream, destination): """ Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or ``sys.stdout``) to ``destination`` for the duration of this context. ``destination`` must provide a ``write()`` method. """ old_stream = os.dup(output_stream.fileno()) with SpooledTemporaryFile() as s: os.dup2(s.fileno(), output_stream.fileno()) yield s.seek(0) destination.write(s.read()) os.dup2(old_stream, output_stream.fileno())
import os from tempfile import SpooledTemporaryFile from contextlib import contextmanager @contextmanager def redirect_stream(output_stream, destination): """ Redirect anything written to ``output_stream`` (typically ``sys.stdin`` or ``sys.stdout``) to ``destination`` for the duration of this context. ``destination`` must provide a ``write()`` method. """ while not isinstance(output_stream, file): # Looks like this is an XUnit Tee object. Try and find the "real" # stderr in its history. output_stream = output_stream._streams[-1] old_stream = os.dup(output_stream.fileno()) with SpooledTemporaryFile() as s: os.dup2(s.fileno(), output_stream.fileno()) yield s.seek(0) destination.write(s.read()) os.dup2(old_stream, output_stream.fileno())
Work around XUnit assumptions about streams.
Work around XUnit assumptions about streams. Fixes #4735.
Python
bsd-2-clause
bartscheers/tkp,transientskp/tkp,mkuiack/tkp,transientskp/tkp,bartscheers/tkp,mkuiack/tkp
--- +++ @@ -10,6 +10,11 @@ ``destination`` must provide a ``write()`` method. """ + while not isinstance(output_stream, file): + # Looks like this is an XUnit Tee object. Try and find the "real" + # stderr in its history. + output_stream = output_stream._streams[-1] + old_stream = os.dup(output_stream.fileno()) with SpooledTemporaryFile() as s: os.dup2(s.fileno(), output_stream.fileno())
2d4aebc6f4ce658395304a407de6519c55679029
matchzoo/engine/base_metric.py
matchzoo/engine/base_metric.py
import abc class BaseMetric(abc.ABC): ALIAS = 'base_metric' @abc.abstractmethod def __call__(self, y_true, y_pred): """""" def __repr__(self): return self.ALIAS def parse_metric(metric): if isinstance(metric, BaseMetric): return metric elif isinstance(metric, str): for subclass in BaseMetric.__subclasses__(): if metric == subclass.ALIAS or metric in subclass.ALIAS: return subclass() return metric # keras native metrics elif issubclass(metric, BaseMetric): return metric() def compute_metric_on_groups(groups, metric): return groups.apply( lambda l: metric(l['y_true'], l['y_pred'])).mean()
import abc class BaseMetric(abc.ABC): ALIAS = 'base_metric' @abc.abstractmethod def __call__(self, y_true, y_pred): """""" def __repr__(self): return self.ALIAS def parse_metric(metric): if isinstance(metric, BaseMetric): return metric elif isinstance(metric, str): for subclass in BaseMetric.__subclasses__(): if metric.lower() == subclass.ALIAS or metric in subclass.ALIAS: return subclass() return metric # keras native metrics elif issubclass(metric, BaseMetric): return metric() def compute_metric_on_groups(groups, metric): return groups.apply( lambda l: metric(l['y_true'], l['y_pred'])).mean()
Add case insensitive metric parsing
Add case insensitive metric parsing
Python
apache-2.0
faneshion/MatchZoo,faneshion/MatchZoo
--- +++ @@ -17,7 +17,7 @@ return metric elif isinstance(metric, str): for subclass in BaseMetric.__subclasses__(): - if metric == subclass.ALIAS or metric in subclass.ALIAS: + if metric.lower() == subclass.ALIAS or metric in subclass.ALIAS: return subclass() return metric # keras native metrics elif issubclass(metric, BaseMetric):
5e6fc0017d6e4c35338455496924616b12d4b9e1
tests/test_simple.py
tests/test_simple.py
#!/usr/bin/env python3 from nose.tools import eq_ from resumable import rebuild, split def test_simple(): @rebuild def function(original): return split(str.upper)(original) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return split(lambda s: s + 'b')(b) return split(second['second'])(a) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
#!/usr/bin/env python3 from nose.tools import eq_ from resumable import rebuild, value def test_simple(): @rebuild def function(original): return value(original.upper()) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return value(b + 'b') return value(second['second'](a)) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
Revise tests to reflect removed split
Revise tests to reflect removed split
Python
mit
Mause/resumable
--- +++ @@ -1,13 +1,13 @@ #!/usr/bin/env python3 from nose.tools import eq_ -from resumable import rebuild, split +from resumable import rebuild, value def test_simple(): @rebuild def function(original): - return split(str.upper)(original) + return value(original.upper()) original = 'hello' @@ -33,8 +33,8 @@ def first(a): @rebuild def second(b): - return split(lambda s: s + 'b')(b) - return split(second['second'])(a) + return value(b + 'b') + return value(second['second'](a)) original = 'ba'
d0d823e8639c8c8c69960a2dc64ce3edfb1a7dcf
halaqat/settings/shaha.py
halaqat/settings/shaha.py
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['shaha-halaqat.herokuapp.com', '0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ # STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['shaha-halaqat.herokuapp.com', '0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ # STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'loaders': [ ( 'django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] ), ], 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.i18n', ], }, }, ] LANGUAGE_CODE = 'ar'
Add cached tempaltes and standard language is Ar
Add cached tempaltes and standard language is Ar
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
--- +++ @@ -18,3 +18,31 @@ # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ # STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' + + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': ['templates'], + 'APP_DIRS': True, + 'OPTIONS': { + 'loaders': [ + ( + 'django.template.loaders.cached.Loader', [ + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ] + ), + ], + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + 'django.template.context_processors.media', + 'django.template.context_processors.i18n', + ], + }, + }, +] + +LANGUAGE_CODE = 'ar'
22c56941d054e083b1d406b1440efd8c0ecc5f11
tests/test_oai_harvester.py
tests/test_oai_harvester.py
from __future__ import unicode_literals import httpretty from scrapi.base import OAIHarvester from scrapi.linter import RawDocument from .utils import TEST_OAI_DOC class TestHarvester(OAIHarvester): base_url = '' long_name = 'Test' short_name = 'test' url = 'test' property_list = ['type', 'source', 'publisher', 'format', 'date'] @httpretty.activate def harvest(self, days_back=1): start_date = '2015-03-14' end_date = '2015-03-16' request_url = 'http://validAI.edu/?from={}&to={}'.format(start_date, end_date) httpretty.register_uri(httpretty.GET, request_url, body=TEST_OAI_DOC, content_type="application/XML") records = self.get_records(request_url, start_date, end_date) return [RawDocument({ 'doc': str(TEST_OAI_DOC), 'source': 'crossref', 'filetype': 'XML', 'docID': "1" }) for record in records] class TestOAIHarvester(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest() ] for res in results: assert res['title'] == 'Test'
from __future__ import unicode_literals import httpretty from scrapi.base import OAIHarvester from scrapi.linter import RawDocument from .utils import TEST_OAI_DOC class TestHarvester(OAIHarvester): base_url = '' long_name = 'Test' short_name = 'test' url = 'test' property_list = ['type', 'source', 'publisher', 'format', 'date'] @httpretty.activate def harvest(self, start_date='2015-03-14', end_date='2015-03-16'): request_url = 'http://validAI.edu/?from={}&to={}'.format(start_date, end_date) httpretty.register_uri(httpretty.GET, request_url, body=TEST_OAI_DOC, content_type="application/XML") records = self.get_records(request_url, start_date, end_date) return [RawDocument({ 'doc': str(TEST_OAI_DOC), 'source': 'crossref', 'filetype': 'XML', 'docID': "1" }) for record in records] class TestOAIHarvester(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest() ] for res in results: assert res['title'] == 'Test'
Add dates to test OAI harvester
Add dates to test OAI harvester
Python
apache-2.0
erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,fabianvf/scrapi,mehanig/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,felliott/scrapi,jeffreyliu3230/scrapi,ostwald/scrapi,erinspace/scrapi,fabianvf/scrapi
--- +++ @@ -16,10 +16,7 @@ property_list = ['type', 'source', 'publisher', 'format', 'date'] @httpretty.activate - def harvest(self, days_back=1): - - start_date = '2015-03-14' - end_date = '2015-03-16' + def harvest(self, start_date='2015-03-14', end_date='2015-03-16'): request_url = 'http://validAI.edu/?from={}&to={}'.format(start_date, end_date)
e38f7d46626f96cb033360764c269aa5c69dda76
moto/sns/utils.py
moto/sns/utils.py
import uuid def make_arn_for_topic(account_id, name): return "arn:aws:sns:us-east-1:{}:{}".format(account_id, name) def make_arn_for_subscription(topic_arn): subscription_id = uuid.uuid4() return "{}:{}".format(topic_arn, subscription_id)
import uuid def make_arn_for_topic(account_id, name): return "arn:aws:sns:us-east-1:{0}:{1}".format(account_id, name) def make_arn_for_subscription(topic_arn): subscription_id = uuid.uuid4() return "{0}:{1}".format(topic_arn, subscription_id)
Fix string formatting for py26
Fix string formatting for py26
Python
apache-2.0
okomestudio/moto,whummer/moto,tootedom/moto,ZuluPro/moto,araines/moto,DataDog/moto,spulec/moto,heddle317/moto,Brett55/moto,andresriancho/moto,im-auld/moto,dbfr3qs/moto,gjtempleton/moto,braintreeps/moto,Brett55/moto,gjtempleton/moto,dbfr3qs/moto,botify-labs/moto,okomestudio/moto,gjtempleton/moto,okomestudio/moto,jrydberg/moto,IlyaSukhanov/moto,jszwedko/moto,Affirm/moto,ImmobilienScout24/moto,ZuluPro/moto,whummer/moto,william-richard/moto,spulec/moto,william-richard/moto,botify-labs/moto,Brett55/moto,william-richard/moto,zonk1024/moto,rocky4570/moto,ZuluPro/moto,pior/moto,spulec/moto,ZuluPro/moto,rocky4570/moto,botify-labs/moto,kefo/moto,2rs2ts/moto,alexdebrie/moto,rocky4570/moto,riccardomc/moto,heddle317/moto,Affirm/moto,dbfr3qs/moto,kennethd/moto,2rs2ts/moto,william-richard/moto,kefo/moto,okomestudio/moto,rocky4570/moto,okomestudio/moto,william-richard/moto,heddle317/moto,Affirm/moto,heddle317/moto,2rs2ts/moto,2rs2ts/moto,whummer/moto,Brett55/moto,Affirm/moto,2rs2ts/moto,ZuluPro/moto,rouge8/moto,spulec/moto,behanceops/moto,dbfr3qs/moto,botify-labs/moto,botify-labs/moto,whummer/moto,rocky4570/moto,Brett55/moto,whummer/moto,Brett55/moto,spulec/moto,Affirm/moto,dbfr3qs/moto,gjtempleton/moto,heddle317/moto,EarthmanT/moto,whummer/moto,silveregg/moto,dbfr3qs/moto,mrucci/moto,kefo/moto,spulec/moto,okomestudio/moto,rocky4570/moto,kefo/moto,ludia/moto,Affirm/moto,william-richard/moto,2mf/moto,botify-labs/moto,gjtempleton/moto,jotes/moto,ZuluPro/moto,kefo/moto
--- +++ @@ -2,9 +2,9 @@ def make_arn_for_topic(account_id, name): - return "arn:aws:sns:us-east-1:{}:{}".format(account_id, name) + return "arn:aws:sns:us-east-1:{0}:{1}".format(account_id, name) def make_arn_for_subscription(topic_arn): subscription_id = uuid.uuid4() - return "{}:{}".format(topic_arn, subscription_id) + return "{0}:{1}".format(topic_arn, subscription_id)
56879634bda7c6c7024d0b9b4bf77c99e703f4f3
server.py
server.py
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListsApi, BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListsApi, '/bucketlists/') api.add_resource(BucketListApi, '/bucketlists/<id>/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
Create BucketList & BucketLists endpoints.
[Feature] Create BucketList & BucketLists endpoints.
Python
mit
andela-akiura/bucketlist
--- +++ @@ -6,7 +6,7 @@ from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ - BucketListApi, UserLogin, UserRegister + BucketListsApi, BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') @@ -15,7 +15,8 @@ # add resources api.add_resource(TestResource, '/') -api.add_resource(BucketListApi, '/bucketlists/') +api.add_resource(BucketListsApi, '/bucketlists/') +api.add_resource(BucketListApi, '/bucketlists/<id>/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/')
cbe07cd63d07f021ccd404cba2bcfe2a6933457b
tests/test_misc.py
tests/test_misc.py
# -*- coding: utf-8 -*- import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs')
# -*- coding: utf-8 -*- import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400)
Add test for tests function
Add test for tests function
Python
mit
guoguo12/billboard-charts,guoguo12/billboard-charts
--- +++ @@ -23,10 +23,16 @@ chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" - + def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') + def test_charts(self): + """Checks that the function for listing all charts returns reasonable + results.""" + charts = billboard.charts() + self.assertTrue('hot-100' in charts) + self.assertTrue(200 <= len(charts) <= 400)
efc19658e081dc66e387f8e26c310943eacf21e7
tqdm/tests/tests_version.py
tqdm/tests/tests_version.py
def test_version(): from tqdm import __version__ assert len(__version__.split('.')) == 4
def test_version(): from tqdm import __version__ assert 3 <= len(__version__.split('.')) <= 4
Fix test_version() to support 3 or 4 elements
Fix test_version() to support 3 or 4 elements Signed-off-by: Stephen L. <bede04c5d6a425d8c5798b0cfa1ed9b901b16a3b@gmail.com>
Python
mit
lrq3000/tqdm
--- +++ @@ -1,3 +1,3 @@ def test_version(): from tqdm import __version__ - assert len(__version__.split('.')) == 4 + assert 3 <= len(__version__.split('.')) <= 4
94f1d4af970076005d7271c1e91b8b9a148a018d
painindex/settings/settings_prod.py
painindex/settings/settings_prod.py
import os from painindex.settings.settings_base import * # This file is NOT part of our repo. It contains sensitive settings like secret key # and db setup. from env import * DEBUG = False TEMPLATE_DEBUG = False # Apps used specifically for production INSTALLED_APPS += ( 'gunicorn', ) # Configure production emails. # These people will get error emails in production ADMINS = ( ('Xan', 'xan.vong@gmail.com'), ) # Set this to match the domains of the production site. ALLOWED_HOSTS = [ 'www.thepainindex.com', 'thepainindex.com', 'http://still-taiga-5292.herokuapp.com', 'localhost' ] # Define place my static files will be collected and served from. # See https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-STATIC_ROOT # STATIC_ROOT = "" # MEDIA_ROOT = ""
import os import dj_database_url from painindex.settings.settings_base import * # This file is NOT part of our repo. It contains sensitive settings like secret key # and db setup. from env import * DEBUG = False TEMPLATE_DEBUG = False # Apps used specifically for production INSTALLED_APPS += ( 'gunicorn', ) # These people will get error emails in production ADMINS = ( ('Xan', 'xan.vong@gmail.com'), ) # Set this to match the domains of the production site. ALLOWED_HOSTS = [ 'www.thepainindex.com', 'thepainindex.com', 'http://still-taiga-5292.herokuapp.com', 'localhost' ] ################### # Heroku settings # ################### # See https://devcenter.heroku.com/articles/getting-started-with-django DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Heroku instructions allow all hosts. # If I have a problem, try this. # ALLOWED_HOSTS = ['*'] STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static') )
Add basic heroku production settings
Add basic heroku production settings
Python
mit
xanv/painindex
--- +++ @@ -1,4 +1,5 @@ import os +import dj_database_url from painindex.settings.settings_base import * # This file is NOT part of our repo. It contains sensitive settings like secret key @@ -9,21 +10,15 @@ DEBUG = False TEMPLATE_DEBUG = False - # Apps used specifically for production INSTALLED_APPS += ( 'gunicorn', ) - -# Configure production emails. - - # These people will get error emails in production ADMINS = ( ('Xan', 'xan.vong@gmail.com'), ) - # Set this to match the domains of the production site. ALLOWED_HOSTS = [ @@ -32,8 +27,21 @@ 'localhost' ] -# Define place my static files will be collected and served from. -# See https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-STATIC_ROOT -# STATIC_ROOT = "" +################### +# Heroku settings # +################### -# MEDIA_ROOT = "" +# See https://devcenter.heroku.com/articles/getting-started-with-django + +DATABASES['default'] = dj_database_url.config() +SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') + +# Heroku instructions allow all hosts. +# If I have a problem, try this. +# ALLOWED_HOSTS = ['*'] + +STATIC_ROOT = 'staticfiles' +STATIC_URL = '/static/' +STATICFILES_DIRS = ( + os.path.join(BASE_DIR, 'static') +)
f50d1834580f0b516035b3a5693b45bf4689bed3
test/test_rules.py
test/test_rules.py
import unittest from src import rules class TestRules(unittest.TestCase): def test_good_value_1(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('1') self.assertEqual(result, 1) def test_good_value_3(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('3') self.assertEqual(result, 3) def test_upper_value_10(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('10') self.assertEqual(result, 0) def test_lower_value_5(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('-5') self.assertEqual(result, 0) def test_bad_value(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('qq') self.assertEqual(result, 0)
""" Tests for the rules module """ import unittest from src import rules class TestRules(unittest.TestCase): """ Tests for the rules module """ def test_good_value_1(self): """ Test a known good value""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('1') self.assertEqual(result, 1) def test_good_value_3(self): """ Test a known good value""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('3') self.assertEqual(result, 3) def test_upper_value_10(self): """ Test a value that should be too high""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('10') self.assertEqual(result, 0) def test_lower_value_5(self): """ Test a value that should be too low""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('-5') self.assertEqual(result, 0) def test_bad_value(self): """ Test a value that isn't an int""" rules_obj = rules.Rules(debug=True) result = rules_obj.convertCharToInt('qq') self.assertEqual(result, 0)
Add docstrings to rules unit tests
Add docstrings to rules unit tests
Python
mit
blairck/jaeger
--- +++ @@ -1,28 +1,37 @@ +""" Tests for the rules module """ + import unittest from src import rules class TestRules(unittest.TestCase): - def test_good_value_1(self): - rules_obj = rules.Rules() - result = rules_obj.convertCharToInt('1') - self.assertEqual(result, 1) + """ Tests for the rules module """ - def test_good_value_3(self): - rules_obj = rules.Rules() - result = rules_obj.convertCharToInt('3') - self.assertEqual(result, 3) + def test_good_value_1(self): + """ Test a known good value""" + rules_obj = rules.Rules() + result = rules_obj.convertCharToInt('1') + self.assertEqual(result, 1) - def test_upper_value_10(self): - rules_obj = rules.Rules() - result = rules_obj.convertCharToInt('10') - self.assertEqual(result, 0) + def test_good_value_3(self): + """ Test a known good value""" + rules_obj = rules.Rules() + result = rules_obj.convertCharToInt('3') + self.assertEqual(result, 3) - def test_lower_value_5(self): - rules_obj = rules.Rules() - result = rules_obj.convertCharToInt('-5') - self.assertEqual(result, 0) + def test_upper_value_10(self): + """ Test a value that should be too high""" + rules_obj = rules.Rules() + result = rules_obj.convertCharToInt('10') + self.assertEqual(result, 0) - def test_bad_value(self): - rules_obj = rules.Rules() - result = rules_obj.convertCharToInt('qq') - self.assertEqual(result, 0) + def test_lower_value_5(self): + """ Test a value that should be too low""" + rules_obj = rules.Rules() + result = rules_obj.convertCharToInt('-5') + self.assertEqual(result, 0) + + def test_bad_value(self): + """ Test a value that isn't an int""" + rules_obj = rules.Rules(debug=True) + result = rules_obj.convertCharToInt('qq') + self.assertEqual(result, 0)
476d8663b8b85ca902703eeee697ae5be0eefabb
lc0118_pascal_triangle.py
lc0118_pascal_triangle.py
"""Leetcode 118. Pascal's Triangle Easy URL: https://leetcode.com/problems/pascals-triangle/ Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] Time complexity: O(n^2). Space complexity: O(n). """ if numRows == 0: return [] # Create base of Pascal triangle. triangle = [[1] * (r + 1) for r in range(numRows)] if numRows <= 2: return triangle for r in range(2, numRows): last_row = triangle[r - 1] current_row = triangle[r] # In middle of current row, sum last row's two numbers. for i in range(1, r): current_row[i] = last_row[i - 1] + last_row[i] return triangle def main(): numRows = 5 print('Pascal\'s triangle:\n{}'.format( Solution().generate(numRows))) if __name__ == '__main__': main()
"""Leetcode 118. Pascal's Triangle Easy URL: https://leetcode.com/problems/pascals-triangle/ Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] Time complexity: O(n^2). Space complexity: O(n). """ if numRows == 0: return [] # Create base of Pascal triangle. T = [[1] * (r + 1) for r in range(numRows)] if numRows <= 2: return T # For each row >= 3, update middle numers by last row. for r in range(2, numRows): for i in range(1, r): T[r][i] = T[r - 1][i - 1] + T[r - 1][i] return T def main(): numRows = 5 print('Pascal\'s triangle:\n{}'.format( Solution().generate(numRows))) if __name__ == '__main__': main()
Refactor by using array T
Refactor by using array T
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -34,20 +34,17 @@ return [] # Create base of Pascal triangle. - triangle = [[1] * (r + 1) for r in range(numRows)] + T = [[1] * (r + 1) for r in range(numRows)] if numRows <= 2: - return triangle + return T + # For each row >= 3, update middle numers by last row. for r in range(2, numRows): - last_row = triangle[r - 1] - current_row = triangle[r] + for i in range(1, r): + T[r][i] = T[r - 1][i - 1] + T[r - 1][i] - # In middle of current row, sum last row's two numbers. - for i in range(1, r): - current_row[i] = last_row[i - 1] + last_row[i] - - return triangle + return T def main():
e1f8f0b9e898521b9f25611ec7e6b8ecc8f1af8d
app/lib/json_schema_utils.py
app/lib/json_schema_utils.py
from jsonschema import validate, ValidationError from flask import current_app import json import os def validate_schema(data, schema_name): """ Validate the provided data against the provided JSON schema. :param data: JSON data to be validated :param schema_name: Name of the schema :return: Boolean """ with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name, '.json'), 'r') as fp: schema = json.load(fp) try: validate(data, schema) return True except ValidationError as e: current_app.logger.info("Failed to validate {}\n{}".format(json.dumps(data), e)) return False
from jsonschema import validate, ValidationError from flask import current_app import json import os def validate_schema(data, schema_name): """ Validate the provided data against the provided JSON schema. :param data: JSON data to be validated :param schema_name: Name of the schema :return: Boolean """ with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name + '.schema'), 'r') as fp: schema = json.load(fp) try: validate(data, schema) return True except ValidationError as e: current_app.logger.info("Failed to validate {}\n{}".format(json.dumps(data), e)) return False
Fix to validate schema function
Fix to validate schema function
Python
apache-2.0
CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords
--- +++ @@ -12,7 +12,7 @@ :param schema_name: Name of the schema :return: Boolean """ - with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name, '.json'), 'r') as fp: + with open(os.path.join(current_app.config['JSON_SCHEMA_DIRECTORY'], schema_name + '.schema'), 'r') as fp: schema = json.load(fp) try:
c7372b1fa7f631fbad6381b8ceeadafa0ec02f36
kpi/migrations/0020_add_validate_submissions_permission_to_asset.py
kpi/migrations/0020_add_validate_submissions_permission_to_asset.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('kpi', '0017_assetversion_uid_aliases_20170608'), ] operations = [ migrations.AlterModelOptions( name='asset', options={'ordering': ('-date_modified',), 'permissions': (('view_asset', 'Can view asset'), ('share_asset', "Can change asset's sharing settings"), ('add_submissions', 'Can submit data to asset'), ('view_submissions', 'Can view submitted data for asset'), ('change_submissions', 'Can modify submitted data for asset'), ('delete_submissions', 'Can delete submitted data for asset'), ('share_submissions', "Can change sharing settings for asset's submitted data"), ('validate_submissions', 'Can validate submitted data asset'), ('from_kc_only', 'INTERNAL USE ONLY; DO NOT ASSIGN'))}, ), migrations.AlterField( model_name='asset', name='_deployment_data', field=jsonfield.fields.JSONField(default=dict), ), migrations.AlterField( model_name='asset', name='asset_type', field=models.CharField(default=b'survey', max_length=20, choices=[(b'text', b'text'), (b'question', b'question'), (b'block', b'block'), (b'survey', b'survey'), (b'empty', b'empty')]), ), migrations.AlterField( model_name='assetsnapshot', name='details', field=jsonfield.fields.JSONField(default=dict), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('kpi', '0019_add_report_custom_field'), ] operations = [ migrations.AlterModelOptions( name='asset', options={'ordering': ('-date_modified',), 'permissions': (('view_asset', 'Can view asset'), ('share_asset', "Can change asset's sharing settings"), ('add_submissions', 'Can submit data to asset'), ('view_submissions', 'Can view submitted data for asset'), ('change_submissions', 'Can modify submitted data for asset'), ('delete_submissions', 'Can delete submitted data for asset'), ('share_submissions', "Can change sharing settings for asset's submitted data"), ('validate_submissions', 'Can validate submitted data asset'), ('from_kc_only', 'INTERNAL USE ONLY; DO NOT ASSIGN'))}, ), ]
Rename conflicting migration and remove extra
Rename conflicting migration and remove extra changes autogenerated by `./manage.py makemigrations`
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi,onaio/kpi,onaio/kpi,kobotoolbox/kpi,kobotoolbox/kpi,onaio/kpi,kobotoolbox/kpi
--- +++ @@ -8,7 +8,7 @@ class Migration(migrations.Migration): dependencies = [ - ('kpi', '0017_assetversion_uid_aliases_20170608'), + ('kpi', '0019_add_report_custom_field'), ] operations = [ @@ -16,19 +16,4 @@ name='asset', options={'ordering': ('-date_modified',), 'permissions': (('view_asset', 'Can view asset'), ('share_asset', "Can change asset's sharing settings"), ('add_submissions', 'Can submit data to asset'), ('view_submissions', 'Can view submitted data for asset'), ('change_submissions', 'Can modify submitted data for asset'), ('delete_submissions', 'Can delete submitted data for asset'), ('share_submissions', "Can change sharing settings for asset's submitted data"), ('validate_submissions', 'Can validate submitted data asset'), ('from_kc_only', 'INTERNAL USE ONLY; DO NOT ASSIGN'))}, ), - migrations.AlterField( - model_name='asset', - name='_deployment_data', - field=jsonfield.fields.JSONField(default=dict), - ), - migrations.AlterField( - model_name='asset', - name='asset_type', - field=models.CharField(default=b'survey', max_length=20, choices=[(b'text', b'text'), (b'question', b'question'), (b'block', b'block'), (b'survey', b'survey'), (b'empty', b'empty')]), - ), - migrations.AlterField( - model_name='assetsnapshot', - name='details', - field=jsonfield.fields.JSONField(default=dict), - ), ]
f813f72ad02bbf4b8e4ad0b190064879f6c3df3e
toolbox/metrics.py
toolbox/metrics.py
import keras.backend as K import numpy as np def psnr(y_true, y_pred): """Peak signal-to-noise ratio averaged over samples and channels.""" mse = K.mean(K.square(y_true - y_pred), axis=(1, 2)) return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10)) def ssim(y_true, y_pred): """structural similarity measurement system.""" ## K1, K2 are two constants, much smaller than 1 K1 = 0.04 K2 = 0.06 ## mean, std, correlation mu_x = K.mean(y_pred) mu_y = K.mean(y_true) sig_x = K.std(y_pred) sig_y = K.std(y_true) sig_xy = (sig_x * sig_y) ** 0.5 ## L, number of pixels, C1, C2, two constants L = 33 C1 = (K1 * L) ** 2 C2 = (K2 * L) ** 2 ssim = (2 * mu_x * mu_y + C1) * (2 * sig_xy * C2) * 1.0 / ((mu_x ** 2 + mu_y ** 2 + C1) * (sig_x ** 2 + sig_y ** 2 + C2)) return ssim
import keras.backend as K import numpy as np def psnr(y_true, y_pred): """Peak signal-to-noise ratio averaged over samples.""" mse = K.mean(K.square(y_true - y_pred), axis=(-3, -2, -1)) return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10)) def ssim(y_true, y_pred): """structural similarity measurement system.""" ## K1, K2 are two constants, much smaller than 1 K1 = 0.04 K2 = 0.06 ## mean, std, correlation mu_x = K.mean(y_pred) mu_y = K.mean(y_true) sig_x = K.std(y_pred) sig_y = K.std(y_true) sig_xy = (sig_x * sig_y) ** 0.5 ## L, number of pixels, C1, C2, two constants L = 33 C1 = (K1 * L) ** 2 C2 = (K2 * L) ** 2 ssim = (2 * mu_x * mu_y + C1) * (2 * sig_xy * C2) * 1.0 / ((mu_x ** 2 + mu_y ** 2 + C1) * (sig_x ** 2 + sig_y ** 2 + C2)) return ssim
Change how PSNR is computed
Change how PSNR is computed
Python
mit
qobilidop/srcnn,qobilidop/srcnn
--- +++ @@ -3,8 +3,8 @@ def psnr(y_true, y_pred): - """Peak signal-to-noise ratio averaged over samples and channels.""" - mse = K.mean(K.square(y_true - y_pred), axis=(1, 2)) + """Peak signal-to-noise ratio averaged over samples.""" + mse = K.mean(K.square(y_true - y_pred), axis=(-3, -2, -1)) return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10))
886b064fb22400b1fa8706a740b738ec057d4117
src/map_manager.py
src/map_manager.py
""" This file contains the code needed for dealing with some of the mappings. Usually a map is just a dictionary that needs to be loaded inside a variable. This file carries the function to parse the files and the variables containing the dictionaries themselves. """ import yaml def load_mapping(filename): """ Load a map from a file. The format must be something that resembles the python dictionary.abs We use the yaml library for that, as using eval() may be dangerous. It will return the data loaded as a dictionary. """ with open(filename) as file: content = yaml.load(file.read()) return content # Loaded data go here tk_color_codes = load_mapping('maps/color_code_mapping.txt') midi_notes = load_mapping('maps/midi_to_note_mapping.txt') scale_notes = load_mapping('maps/note_to_midi_mapping.txt') volume_positions = load_mapping('maps/volume_positions.txt') volume_colors = load_mapping('maps/volume_colors.txt') pad_notes = load_mapping('maps/pad_notes.txt') layouts = load_mapping('maps/layouts.txt')
""" This file contains the code needed for dealing with some of the mappings. Usually a map is just a dictionary that needs to be loaded inside a variable. This file carries the function to parse the files and the variables containing the dictionaries themselves. """ import yaml def load_mapping(filename): """ Load a map from a file. The format must be something that resembles the python dictionary.abs We use the yaml library for that, as using eval() may be dangerous. It will return the data loaded as a dictionary. """ with open(filename) as file: content = yaml.safe_load(file.read()) return content # Loaded data go here tk_color_codes = load_mapping('maps/color_code_mapping.txt') midi_notes = load_mapping('maps/midi_to_note_mapping.txt') scale_notes = load_mapping('maps/note_to_midi_mapping.txt') volume_positions = load_mapping('maps/volume_positions.txt') volume_colors = load_mapping('maps/volume_colors.txt') pad_notes = load_mapping('maps/pad_notes.txt') layouts = load_mapping('maps/layouts.txt')
Use safe load for yaml.
Use safe load for yaml.
Python
mit
danodic/pianopad
--- +++ @@ -15,7 +15,7 @@ """ with open(filename) as file: - content = yaml.load(file.read()) + content = yaml.safe_load(file.read()) return content
a14a911ae49d8354f61426cee2925b2a24a9b521
Alerters/nc.py
Alerters/nc.py
try: import pync pync_available = True except ImportError: pync_available = False from .alerter import Alerter class NotificationCenterAlerter(Alerter): """Send alerts to the Mac OS X Notification Center.""" def __init__(self, config_options): Alerter.__init__(self, config_options) if not pync_available: self.alerter_logger.critical("Pync package is not available, cannot use NotificationCenterAlerter.") self.alerter_logger.critical("Try: pip install -r requirements.txt") return def send_alert(self, name, monitor): """Send the message.""" alert_type = self.should_alert(monitor) message = "" if alert_type == "": return elif alert_type == "failure": message = "Monitor {} failed!".format(name) elif alert_type == "success": message = "Monitor {} succeeded.".format(name) else: self.alerter_logger.error("Unknown alert type: {}".format(alert_type)) return if not self.dry_run: pync.notify(message=message, title="SimpleMonitor") else: self.alerter_logger.info("dry_run: would send message: {}".format(message))
try: import pync pync_available = True except ImportError: pync_available = False import platform from .alerter import Alerter class NotificationCenterAlerter(Alerter): """Send alerts to the Mac OS X Notification Center.""" def __init__(self, config_options): Alerter.__init__(self, config_options) if not pync_available: self.alerter_logger.critical("Pync package is not available, which is necessary to use NotificationCenterAlerter.") self.alerter_logger.critical("Try: pip install -r requirements.txt") return if platform.system() != "Darwin": self.alerter_logger.critical("This alerter (currently) only works on Mac OS X!") return def send_alert(self, name, monitor): """Send the message.""" alert_type = self.should_alert(monitor) message = "" if alert_type == "": return elif alert_type == "failure": message = "Monitor {} failed!".format(name) elif alert_type == "success": message = "Monitor {} succeeded.".format(name) else: self.alerter_logger.error("Unknown alert type: {}".format(alert_type)) return if not self.dry_run: pync.notify(message=message, title="SimpleMonitor") else: self.alerter_logger.info("dry_run: would send message: {}".format(message))
Add check for running on Mac OS X
Add check for running on Mac OS X
Python
bsd-3-clause
jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor
--- +++ @@ -3,6 +3,8 @@ pync_available = True except ImportError: pync_available = False + +import platform from .alerter import Alerter @@ -12,8 +14,12 @@ def __init__(self, config_options): Alerter.__init__(self, config_options) if not pync_available: - self.alerter_logger.critical("Pync package is not available, cannot use NotificationCenterAlerter.") + self.alerter_logger.critical("Pync package is not available, which is necessary to use NotificationCenterAlerter.") self.alerter_logger.critical("Try: pip install -r requirements.txt") + return + + if platform.system() != "Darwin": + self.alerter_logger.critical("This alerter (currently) only works on Mac OS X!") return def send_alert(self, name, monitor):
e3c1819b6b5ddec1ff326c3693d48ec8a8b3a834
fantail/tests/__init__.py
fantail/tests/__init__.py
# This is imported from setup.py and the test script tests_require = [ 'pytest', 'pytest-capturelog', 'pytest-cov', ]
# This is imported from setup.py and the test script tests_require = [ 'coveralls', 'pytest', 'pytest-capturelog', 'pytest-cov', ]
Add coveralls to test requirements
Add coveralls to test requirements
Python
bsd-2-clause
sjkingo/fantail,sjkingo/fantail,sjkingo/fantail
--- +++ @@ -1,5 +1,6 @@ # This is imported from setup.py and the test script tests_require = [ + 'coveralls', 'pytest', 'pytest-capturelog', 'pytest-cov',
8dc27ef7eae79992e8db94e580faf7e16c03e949
scripts/base_interaction.py
scripts/base_interaction.py
#! /usr/bin/env python import logging logger = logging.getLogger("robots") logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(console) import time import Queue as queue import pyoro import robots from robots import desires human = "HERAKLES_HUMAN1" pr2 = robots.PR2() oro = pyoro.Oro() incoming_desires = queue.Queue() def ondesires(e): logger.info("Incomig desires:" + str(e)) for d in e: incoming_desires.put(d) oro.subscribe([human + " desires ?d"], ondesires) try: logger.info("Waiting for desires...") while True: sit = incoming_desires.get(False) if sit: desire = desires.desire_factory(sit, oro, pr2) desire.perform() time.sleep(0.1) except KeyboardInterrupt: pass oro.close() pr2.close()
#! /usr/bin/env python import logging logger = logging.getLogger("robots") logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(console) import time import Queue as queue import pyoro import robots from robots import desires human = "HERAKLES_HUMAN1" incoming_desires = queue.Queue() def ondesires(e): logger.info("Incomig desires:" + str(e)) for d in e: incoming_desires.put(d) with robots.PR2(knowledge = pyoro.Oro()) as pr2: pr2.knowledge.subscribe([human + " desires ?d"], ondesires) try: logger.info("Waiting for desires...") while True: sit = incoming_desires.get() if sit: desire = desires.desire_factory(sit, pr2) desire.perform() time.sleep(0.1) except KeyboardInterrupt: pass
Use the 'with' statement to create the PR2 object
Use the 'with' statement to create the PR2 object
Python
isc
chili-epfl/pyrobots,chili-epfl/pyrobots-nao
--- +++ @@ -19,11 +19,7 @@ import robots from robots import desires - human = "HERAKLES_HUMAN1" - -pr2 = robots.PR2() -oro = pyoro.Oro() incoming_desires = queue.Queue() @@ -32,20 +28,20 @@ for d in e: incoming_desires.put(d) +with robots.PR2(knowledge = pyoro.Oro()) as pr2: -oro.subscribe([human + " desires ?d"], ondesires) - -try: - logger.info("Waiting for desires...") - while True: - sit = incoming_desires.get(False) - - if sit: - desire = desires.desire_factory(sit, oro, pr2) - desire.perform() - time.sleep(0.1) -except KeyboardInterrupt: - pass - -oro.close() -pr2.close() + + pr2.knowledge.subscribe([human + " desires ?d"], ondesires) + + try: + logger.info("Waiting for desires...") + while True: + sit = incoming_desires.get() + + if sit: + desire = desires.desire_factory(sit, pr2) + desire.perform() + time.sleep(0.1) + except KeyboardInterrupt: + pass +
319d6cb62c55d4eec124d9872d491aebaaad468a
froide/publicbody/search_indexes.py
froide/publicbody/search_indexes.py
from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex)
from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex)
Make Public Body document search an EdgeNgram Field to improve search
Make Public Body document search an EdgeNgram Field to improve search
Python
mit
ryankanno/froide,stefanw/froide,fin/froide,okfse/froide,LilithWittmann/froide,CodeforHawaii/froide,catcosmo/froide,catcosmo/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,catcosmo/froide,okfse/froide,LilithWittmann/froide,stefanw/froide,catcosmo/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,fin/froide,stefanw/froide,ryankanno/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,okfse/froide,okfse/froide,CodeforHawaii/froide
--- +++ @@ -5,7 +5,7 @@ class PublicBodyIndex(indexes.SearchIndex): - text = indexes.CharField(document=True, use_template=True) + text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') @@ -16,6 +16,5 @@ """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() - site.register(PublicBody, PublicBodyIndex)
5556c3c0b4fc55f17de1f3d8d96288746a36775a
src/server/main.py
src/server/main.py
from twisted.internet.task import LoopingCall from twisted.python import log as twistedLog from src.shared import config from src.server.game_state_manager import GameStateManager from src.server.networking import runServer, ConnectionManager from src.server.stdio import setupStdio def main(args): connections = ConnectionManager() gameStateManager = GameStateManager(connections) connections.setGameStateHandler(gameStateManager) setupStdio(gameStateManager) loop = LoopingCall(gameStateManager.tick) deferred = loop.start(config.TICK_LENGTH) deferred.addErrback(twistedLog.err) runServer(args.port, connections)
from twisted.internet import reactor from twisted.internet.task import LoopingCall from twisted.python import log as twistedLog from src.shared import config from src.server.game_state_manager import GameStateManager from src.server.networking import runServer, ConnectionManager from src.server.stdio import setupStdio def unhandledError(reason): twistedLog.err(reason, "Aborting due to unhandled error.") reactor.stop() def main(args): connections = ConnectionManager() gameStateManager = GameStateManager(connections) connections.setGameStateHandler(gameStateManager) setupStdio(gameStateManager) loop = LoopingCall(gameStateManager.tick) deferred = loop.start(config.TICK_LENGTH) deferred.addErrback(unhandledError) runServer(args.port, connections)
Bring down the server on (some?) uncaught errors.
Bring down the server on (some?) uncaught errors. I added an errback to the LoopingCall for gameStateManager.tick, so it'll be called if any exception gets raised out of one of those calls. The errback just prints a traceback and then brings down the server, ensuring that other clients get disconnected as well. This is at least some progress on #31, though it's hard to know if the issue is really fully fixed.
Python
mit
CheeseLord/warts,CheeseLord/warts
--- +++ @@ -1,3 +1,4 @@ +from twisted.internet import reactor from twisted.internet.task import LoopingCall from twisted.python import log as twistedLog @@ -5,6 +6,10 @@ from src.server.game_state_manager import GameStateManager from src.server.networking import runServer, ConnectionManager from src.server.stdio import setupStdio + +def unhandledError(reason): + twistedLog.err(reason, "Aborting due to unhandled error.") + reactor.stop() def main(args): connections = ConnectionManager() @@ -14,7 +19,7 @@ loop = LoopingCall(gameStateManager.tick) deferred = loop.start(config.TICK_LENGTH) - deferred.addErrback(twistedLog.err) + deferred.addErrback(unhandledError) runServer(args.port, connections)
f4f65dd62e5f70a17cecbddf960fa7a0c9699820
setup.py
setup.py
from setuptools import setup long_description = '''\ image-diet2 is a Django application for removing unnecessary bytes from image files. It optimizes images without changing their look or visual quality ("losslessly"). It works on images in JPEG, GIF and PNG formats and will leave others unchanged. Provides a seemless integration with easy_thumbnails app, but can work with others too.''' setup( author="Marko Samastur", author_email="markos@gaivo.net", name='image-diet2', version='0.7.1', description='Remove unnecessary bytes from images', long_description=long_description, url='https://github.com/samastur/image-diet2/', platforms=['OS Independent'], license='MIT License', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', 'Topic :: Utilities', ], install_requires=[ 'pyimagediet>=0.5', ], include_package_data=True, packages=['image_diet'], zip_safe=False )
from setuptools import setup long_description = '''\ image-diet2 is a Django application for removing unnecessary bytes from image files. It optimizes images without changing their look or visual quality ("losslessly"). It works on images in JPEG, GIF and PNG formats and will leave others unchanged. Provides a seemless integration with easy_thumbnails app, but can work with others too.''' setup( author="Marko Samastur", author_email="markos@gaivo.net", name='image-diet2', version='0.7.1', description='Remove unnecessary bytes from images', long_description=long_description, url='https://github.com/samastur/image-diet2/', platforms=['OS Independent'], license='MIT License', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', 'Topic :: Utilities', ], install_requires=[ 'pyimagediet>=0.9', ], include_package_data=True, packages=['image_diet'], zip_safe=False )
Use version 0.9 of pyimagediet
Use version 0.9 of pyimagediet
Python
mit
samastur/image-diet2
--- +++ @@ -29,7 +29,7 @@ 'Topic :: Utilities', ], install_requires=[ - 'pyimagediet>=0.5', + 'pyimagediet>=0.9', ], include_package_data=True, packages=['image_diet'],
443a66e04c18de2653791710b387220bf456380d
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'pandas', 'numpy', 'rasterio', 'pyyaml' ] setup(name='niche_vlaanderen', version="0.0.1", description='NICHE Vlaanderen: hydro-ecological model for valley-ecosystems in Flanders', url='https://github.com/INBO/niche_vlaanderen', author='Johan Van de Wauw', author_email='johan.vandewauw@inbo.be', license='MIT', install_requires=requirements, packages=['niche_vlaanderen'], classifiers=[ 'Development Status :: 1 - Planning', 'Inteded Audience :: Science/Research', 'License :: OSI Approved :: MIT License', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], include_package_data=True, tests_require=['pytest'], entry_points=''' [console_scripts] niche=niche_vlaanderen.cli:cli ''' )
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read()s requirements = [ 'pandas', 'numpy', 'rasterio', 'pyyaml' ] setup(name='niche_vlaanderen', version="0.0.1", description='NICHE Vlaanderen: hydro-ecological model for valley-ecosystems in Flanders', url='https://github.com/INBO/niche_vlaanderen', author='Johan Van de Wauw', author_email='johan.vandewauw@inbo.be', license='MIT', install_requires=requirements, packages=['niche_vlaanderen'], classifiers=[ 'Development Status :: 1 - Planning', 'Inteded Audience :: Science/Research', 'License :: OSI Approved :: MIT License', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], include_package_data=True, tests_require=['pytest'], entry_points=''' [console_scripts] niche=niche_vlaanderen.cli:cli ''' )
Fix bug on history file
Fix bug on history file
Python
mit
johanvdw/niche_vlaanderen
--- +++ @@ -6,10 +6,7 @@ with open('README.rst') as readme_file: - readme = readme_file.read() - -with open('HISTORY.rst') as history_file: - history = history_file.read() + readme = readme_file.read()s requirements = [ 'pandas',
a25e6fb5f9e63ffa30a6c655a6775eead4206bcb
setup.py
setup.py
from distutils.core import setup import os, glob, string, shutil # Packages packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap'] def main(): setup (name = 'neuroimaging', version = '0.01a', description = 'This is a neuroimaging python package', author = 'Various, one of whom is Jonathan Taylor', author_email = 'jonathan.taylor@stanford.edu', ext_package = 'neuroimaging', packages=packages, package_dir = {'neuroimaging': 'lib'}, url = 'http://neuroimaging.scipy.org', long_description = ''' ''') if __name__ == "__main__": main()
import os, glob, string, shutil from distutils.core import setup # Packages packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap'] def main(): setup (name = 'neuroimaging', version = '0.01a', description = 'This is a neuroimaging python package', author = 'Various, one of whom is Jonathan Taylor', author_email = 'jonathan.taylor@stanford.edu', ext_package = 'neuroimaging', packages=packages, package_dir = {'neuroimaging': 'lib'}, url = 'http://neuroimaging.scipy.org', long_description = ''' ''') if __name__ == "__main__": main()
Test edit - to check svn email hook
Test edit - to check svn email hook
Python
bsd-3-clause
gef756/statsmodels,kiyoto/statsmodels,hainm/statsmodels,wdurhamh/statsmodels,detrout/debian-statsmodels,kiyoto/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,alekz112/statsmodels,hainm/statsmodels,bsipocz/statsmodels,phobson/statsmodels,huongttlan/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,josef-pkt/statsmodels,nguyentu1602/statsmodels,ChadFulton/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,waynenilsen/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,DonBeo/statsmodels,detrout/debian-statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,bavardage/statsmodels,musically-ut/statsmodels,pprett/statsmodels,yarikoptic/pystatsmodels,wzbozon/statsmodels,cbmoore/statsmodels,YihaoLu/statsmodels,bert9bert/statsmodels,saketkc/statsmodels,astocko/statsmodels,bert9bert/statsmodels,wwf5067/statsmodels,astocko/statsmodels,pprett/statsmodels,bavardage/statsmodels,nvoron23/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,jstoxrocky/statsmodels,ChadFulton/statsmodels,wesm/statsmodels,wdurhamh/statsmodels,waynenilsen/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bsipocz/statsmodels,jseabold/statsmodels,wwf5067/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,huongttlan/statsmodels,wesm/statsmodels,wkfwkf/statsmodels,bzero/statsmodels,wdurhamh/statsmodels,adammenges/statsmodels,bashtage/statsmodels,rgommers/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,bzero/statsmodels,saketkc/statsmodels,wkfwkf/statsmodels,astocko/statsmodels,alekz112/statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,saketkc/statsmodels,detrout/debian-statsmodels,wwf5067/statsmodels,jstoxrocky/statsmodels,YihaoLu/statsmodels,yarikoptic/pystatsmodels,pprett/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,yl565/statsmodels,kiyoto/statsmodels,hainm/statsmodels,bzero/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,edhuckle/statsmodels,wzbozon/statsmodels,josef-pkt/statsmodels,musically-ut/statsmodels,bashtage/statsmodels,musically-ut/statsmodels,hlin117/statsmodels,saketkc/statsmodels,wkfwkf/statsmodels,gef756/statsmodels,YihaoLu/statsmodels,adammenges/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,bzero/statsmodels,cbmoore/statsmodels,pprett/statsmodels,hlin117/statsmodels,bavardage/statsmodels,huongttlan/statsmodels,wwf5067/statsmodels,phobson/statsmodels,alekz112/statsmodels,hlin117/statsmodels,Averroes/statsmodels,wzbozon/statsmodels,statsmodels/statsmodels,astocko/statsmodels,nguyentu1602/statsmodels,adammenges/statsmodels,jseabold/statsmodels,edhuckle/statsmodels,YihaoLu/statsmodels,alekz112/statsmodels,hainm/statsmodels,bashtage/statsmodels,bzero/statsmodels,yl565/statsmodels,phobson/statsmodels,DonBeo/statsmodels,wesm/statsmodels,adammenges/statsmodels,phobson/statsmodels,yarikoptic/pystatsmodels,yl565/statsmodels,josef-pkt/statsmodels,YihaoLu/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,statsmodels/statsmodels,bert9bert/statsmodels,saketkc/statsmodels,gef756/statsmodels,DonBeo/statsmodels,Averroes/statsmodels,josef-pkt/statsmodels,yl565/statsmodels,rgommers/statsmodels,gef756/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,wzbozon/statsmodels,jseabold/statsmodels,bashtage/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,rgommers/statsmodels,wdurhamh/statsmodels,waynenilsen/statsmodels,detrout/debian-statsmodels,huongttlan/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,bavardage/statsmodels,bavardage/statsmodels,josef-pkt/statsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,Averroes/statsmodels,DonBeo/statsmodels,rgommers/statsmodels,phobson/statsmodels,hlin117/statsmodels,nvoron23/statsmodels
--- +++ @@ -1,5 +1,5 @@ +import os, glob, string, shutil from distutils.core import setup -import os, glob, string, shutil # Packages
2251ef09b75b60268b6d28ff4ec5a04e8eef209f
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup import os from deflect import __version__ as version def read_file(filename): """ Utility function to read a provided filename. """ return open(os.path.join(os.path.dirname(__file__), filename)).read() packages = [ 'deflect', 'deflect.tests', ] package_data = { '': ['LICENSE', 'README.rst'], } setup( name='django-deflect', version=version, description='A Django short URL redirection application', long_description=read_file('README.rst'), author='Jason Bittel', author_email='jason.bittel@gmail.com', url='https://github.com/jbittel/django-deflect', download_url='https://github.com/jbittel/django-deflect/downloads', package_dir={'deflect': 'deflect'}, packages=packages, package_data=package_data, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Programming Language :: Python', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords=['django'], )
#!/usr/bin/env python from distutils.core import setup import os from deflect import __version__ as version def read_file(filename): """ Utility function to read a provided filename. """ return open(os.path.join(os.path.dirname(__file__), filename)).read() packages = [ 'deflect', 'deflect.tests', ] package_data = { '': ['LICENSE', 'README.rst'], } setup( name='django-deflect', version=version, description='A Django short URL redirection application', long_description=read_file('README.rst'), author='Jason Bittel', author_email='jason.bittel@gmail.com', url='https://github.com/jbittel/django-deflect', download_url='https://github.com/jbittel/django-deflect/downloads', package_dir={'deflect': 'deflect'}, packages=packages, package_data=package_data, license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords=['django', 'url', 'short url', 'redirect', 'redirection'], )
Expand trove classifiers and keywords
Expand trove classifiers and keywords
Python
bsd-3-clause
jbittel/django-deflect
--- +++ @@ -36,14 +36,16 @@ package_data=package_data, license='BSD', classifiers=[ - 'Development Status :: 2 - Pre-Alpha', + 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', ], - keywords=['django'], + keywords=['django', 'url', 'short url', 'redirect', 'redirection'], )
2cadcdbe2c9226547e95247a228aeec397a0f311
setup.py
setup.py
import subprocess import sys from setuptools import setup, Command import restle class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) setup( name='restle', description='A REST client framework', keywords='rest,mapper,client', version=restle.__version__, packages=['restle'], requires=['six', 'requests'], url='https://github.com/consbio/restle', license='BSD', tests_require=['pytest', 'httpretty==0.8.6', 'mock'], cmdclass={'test': PyTest} )
import subprocess import sys from setuptools import setup, Command import restle class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call(['py.test', 'test_restle.py']) raise SystemExit(errno) setup( name='restle', description='A REST client framework', keywords='rest,mapper,client', version=restle.__version__, packages=['restle'], requires=['six', 'requests'], url='https://github.com/consbio/restle', license='BSD', tests_require=['pytest', 'httpretty==0.8.6', 'mock'], cmdclass={'test': PyTest} )
Use py.test directly instead of through runtests.py
Use py.test directly instead of through runtests.py
Python
bsd-3-clause
consbio/restle
--- +++ @@ -15,7 +15,7 @@ pass def run(self): - errno = subprocess.call([sys.executable, 'runtests.py']) + errno = subprocess.call(['py.test', 'test_restle.py']) raise SystemExit(errno) setup(
2fc2a0a216d4d57e8157622c69b59fe566b885a2
setup.py
setup.py
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import os, sys from setuptools import setup, find_packages setup( name='towncrier', maintainer='Amber Brown', maintainer_email='hawkowl@twistedmatrix.com', url="https://github.com/hawkowl/towncrier", classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], use_incremental=True, setup_requires=['incremental'], install_requires=[ 'Click', 'incremental', 'jinja2', 'toml', ], package_dir={"": "src"}, packages=find_packages('src'), license="MIT", zip_safe=False, include_package_data=True, description='Building newsfiles for your project.', long_description=open('README.rst').read(), entry_points={ 'console_scripts': [ 'towncrier = towncrier:_main', ], } )
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import os, sys from setuptools import setup, find_packages setup( name='towncrier', maintainer='Amber Brown', maintainer_email='hawkowl@twistedmatrix.com', url="https://github.com/hawkowl/towncrier", classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], use_incremental=True, setup_requires=['incremental'], install_requires=[ 'Click', 'incremental', 'jinja2', 'toml', ], package_dir={"": "src"}, packages=find_packages('src'), license="MIT", zip_safe=False, include_package_data=True, description='Building newsfiles for your project.', long_description=open('README.rst').read(), entry_points={ 'console_scripts': [ 'towncrier = towncrier:_main', ], } )
Stop being a legacy owl
Stop being a legacy owl
Python
mit
hawkowl/towncrier
--- +++ @@ -20,6 +20,7 @@ "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", ], use_incremental=True, setup_requires=['incremental'],
9295a2937e4d8dfa031d8153755e25fddf34aac4
setup.py
setup.py
from setuptools import setup setup( name='discord-curious', version='0.1.1', packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses', 'curious.ext'], url='https://github.com/SunDwarf/curious', license='MIT', author='Laura Dickinson', author_email='l@veriny.tf', description='A curio library for the Discord API', install_requires=[ "cuiows>=0.1.10", "curio==0.4.0", "h11==0.7.0", "multidict==2.1.4", "pylru==1.0.9", "yarl==0.8.1", ], extras_require={ "voice": ["opuslib==1.1.0", "PyNaCL==1.0.1",] } )
from setuptools import setup setup( name='discord-curious', version='0.1.1', packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses'], namespace_packages=['curious.ext'], url='https://github.com/SunDwarf/curious', license='MIT', author='Laura Dickinson', author_email='l@veriny.tf', description='A curio library for the Discord API', install_requires=[ "cuiows>=0.1.10", "curio==0.4.0", "h11==0.7.0", "multidict==2.1.4", "pylru==1.0.9", "yarl==0.8.1", ], extras_require={ "voice": ["opuslib==1.1.0", "PyNaCL==1.0.1",] } )
Add `curious.ext` as a namespace package correctly.
Add `curious.ext` as a namespace package correctly.
Python
mit
SunDwarf/curious
--- +++ @@ -3,7 +3,8 @@ setup( name='discord-curious', version='0.1.1', - packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses', 'curious.ext'], + packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses'], + namespace_packages=['curious.ext'], url='https://github.com/SunDwarf/curious', license='MIT', author='Laura Dickinson',
3218ddfbfcc53f21a6985d445a2cccb186f79977
setup.py
setup.py
from setuptools import setup files = ["journal_files/*"] readme = open('README.md','r') README_TEXT = readme.read() readme.close() setup( name="journalabbrev", version="0.1.1", packages=["journalabbrev"], scripts=["bin/journalabbrev"], long_description = README_TEXT, install_requires=["bibtexparser"], data_files=[ ("/opt/journalabbreviation/", ["static/db_abbrev.json"]) ], licencse="GPL-3.0", description="Abbreviates journal names inside in a given bibtex file", author="Bruno Messias", author_email="contato@brunomessias.com", download_url="https://github.com/devmessias/journalabbrev/archive/0.1.tar.gz", keywords=["bibtex", "abbreviate", "science","scientific-journals"], classifiers=[ 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Topic :: Text Processing :: Markup :: LaTeX', ], url="https://github.com/devmessias/journalabbrev" )
from setuptools import setup files = ["journal_files/*"] readme = open('README.md','r') README_TEXT = readme.read() readme.close() setup( name="journalabbrev", version="0.1.1", packages=["journalabbrev"], scripts=["bin/journalabbrev"], long_description = README_TEXT, install_requires=["bibtexparser"], data_files=[ ("/opt/journalabbreviation/", ["static/db_abbrev.json"]) ], licencse="GPL-3.0", description="Abbreviates journal names inside in a given bibtex file", author="Bruno Messias", author_email="contato@brunomessias.com", download_url="https://github.com/devmessias/journalabbrev/archive/0.1.1.tar.gz", keywords=["bibtex", "abbreviate", "science","scientific-journals"], classifiers=[ 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Topic :: Text Processing :: Markup :: LaTeX', ], url="https://github.com/devmessias/journalabbrev" )
Update some information for pypi package
Update some information for pypi package
Python
agpl-3.0
bibcure/bibcure
--- +++ @@ -20,7 +20,7 @@ description="Abbreviates journal names inside in a given bibtex file", author="Bruno Messias", author_email="contato@brunomessias.com", - download_url="https://github.com/devmessias/journalabbrev/archive/0.1.tar.gz", + download_url="https://github.com/devmessias/journalabbrev/archive/0.1.1.tar.gz", keywords=["bibtex", "abbreviate", "science","scientific-journals"], classifiers=[ 'Intended Audience :: Science/Research',
73da02cc3cc33f287a78f9d7d0c7904058ec8c01
setup.py
setup.py
from setuptools import setup setup( name='nchp', version='0.1', description='NGINX based Configurable HTTP Proxy for use with jupyterhub', url='http://github.com/yuvipanda/jupyterhub-nginx-chp', author='Yuvi Panda', author_email='yuvipanda@riseup.net', license='BSD', packages=['nchp'], entry_points={ 'console_scripts': [ 'nchp = nchp.__main__:main' ] } )
from setuptools import setup setup( name='nchp', version='0.1', description='NGINX based Configurable HTTP Proxy for use with jupyterhub', url='http://github.com/yuvipanda/jupyterhub-nginx-chp', author='Yuvi Panda', author_email='yuvipanda@riseup.net', license='BSD', packages=['nchp'], include_package_data=True, entry_points={ 'console_scripts': [ 'nchp = nchp.__main__:main' ] } )
Make sure that pip will install the template files too
Make sure that pip will install the template files too
Python
bsd-3-clause
yuvipanda/jupyterhub-nginx-chp
--- +++ @@ -9,6 +9,7 @@ author_email='yuvipanda@riseup.net', license='BSD', packages=['nchp'], + include_package_data=True, entry_points={ 'console_scripts': [ 'nchp = nchp.__main__:main'
6eba2b16f91b679384503af46bda82233e1f8f65
setup.py
setup.py
from setuptools import setup import sys version = '2.0.0' if sys.version_info >= (3,): python_dateutils_version = 'python-dateutil>=2.0' else: python_dateutils_version = 'python-dateutil<2.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', install_requires=[ 'six', ], tests_require=[ python_dateutils_version, 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] )
from setuptools import setup import sys version = '2.0.0' if sys.version_info >= (3,): python_dateutils_version = 'python-dateutil>=2.0' else: python_dateutils_version = 'python-dateutil<2.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', install_requires=[ 'six', ], tests_require=[ python_dateutils_version, 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] )
Add classifiers to indicate that the package works with python 3.
Add classifiers to indicate that the package works with python 3.
Python
mit
piran/pyactiveresource,hockeybuggy/pyactiveresource,metric-collective/pyactiveresource,varesa/pyactiveresource
--- +++ @@ -27,11 +27,17 @@ ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', - 'Topic :: Software Development :: Libraries', + 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] )
b8688879de84b405d8c54add3ca793df54e2f39a
bin/finnpos-restore-lemma.py
bin/finnpos-restore-lemma.py
#! /usr/bin/env python3 from sys import stdin for line in stdin: line = line.strip() if line == '': print('') else: wf, feats, lemma, label, ann = line.split('\t') lemmas = ann if ann.find(' ') != -1: lemmas = ann[:ann.find(' ')] ann = [ann.find(' '):] lemma_dict = dict(eval(ann)) if label in lemma_dict: lemma = lemma_dict[label] lemma = lemma.lower() lemma = lemma.replace('#','') print('%s\t%s\t%s\t%s\t%s' % (wf, feats, lemma, label, ann))
#! /usr/bin/env python3 from sys import stdin def part_count(lemma): return lemma.count('#') def compile_dict(label_lemma_pairs): res = {} for label, lemma in label_lemma_pairs: if label in res: old_lemma = res[label] if part_count(old_lemma) > part_count(lemma): res[label] = lemma else: res[label] = lemma return res for line in stdin: line = line.strip() if line == '': print('') else: wf, feats, lemma, label, ann = line.split('\t') lemmas = ann if ann.find(' ') != -1: lemmas = ann[:ann.find(' ')] ann = ann[ann.find(' ') + 1:] else: ann = '_' lemma_dict = {} if lemmas != '_': lemma_dict = compile_dict(eval(lemmas)) if label in lemma_dict: lemma = lemma_dict[label] lemma = lemma.lower() lemma = lemma.replace('#','') print('%s\t%s\t%s\t%s\t%s' % (wf, feats, lemma, label, ann))
Choose lemma with fewest parts.
Choose lemma with fewest parts.
Python
apache-2.0
mpsilfve/FinnPos,mpsilfve/FinnPos,mpsilfve/FinnPos,mpsilfve/FinnPos
--- +++ @@ -1,6 +1,23 @@ #! /usr/bin/env python3 from sys import stdin + +def part_count(lemma): + return lemma.count('#') + +def compile_dict(label_lemma_pairs): + res = {} + + for label, lemma in label_lemma_pairs: + if label in res: + old_lemma = res[label] + + if part_count(old_lemma) > part_count(lemma): + res[label] = lemma + else: + res[label] = lemma + + return res for line in stdin: line = line.strip() @@ -13,9 +30,13 @@ lemmas = ann if ann.find(' ') != -1: lemmas = ann[:ann.find(' ')] - ann = [ann.find(' '):] - - lemma_dict = dict(eval(ann)) + ann = ann[ann.find(' ') + 1:] + else: + ann = '_' + + lemma_dict = {} + if lemmas != '_': + lemma_dict = compile_dict(eval(lemmas)) if label in lemma_dict: lemma = lemma_dict[label]
f40fca40d5e09d7ae64acab1258f58cea6810662
setup.py
setup.py
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, author = 'Ryan May', author_email = 'rmay31@gmail.com', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, version='0.8', author = 'Ryan May', author_email = 'rmay31@gmail.com', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
Add a version number for scattering.
Add a version number for scattering.
Python
bsd-2-clause
dopplershift/Scattering
--- +++ @@ -7,6 +7,7 @@ def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, + version='0.8', author = 'Ryan May', author_email = 'rmay31@gmail.com', platforms = ['Linux'],
cd05732abb9d8d6c5dbacb5fea0b3bb01d066e0b
setup.py
setup.py
from trakt.version import __version__ from setuptools import setup, find_packages setup( name='trakt.py', version=__version__, license='MIT', url='https://github.com/fuzeman/trakt.py', author='Dean Gardiner', author_email='me@dgardiner.net', description='Python interface for the trakt.tv API', packages=find_packages(exclude=[ 'examples' ]), platforms='any', install_requires=[ 'arrow', 'requests>=2.4.0', 'six' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
from setuptools import setup, find_packages import os base_dir = os.path.dirname(__file__) version = {} with open(os.path.join(base_dir, "trakt", "version.py")) as f: exec(f.read(), version) setup( name='trakt.py', version=version['__version__'], license='MIT', url='https://github.com/fuzeman/trakt.py', author='Dean Gardiner', author_email='me@dgardiner.net', description='Python interface for the trakt.tv API', packages=find_packages(exclude=[ 'examples' ]), platforms='any', install_requires=[ 'arrow', 'requests>=2.4.0', 'six' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
Read the `__version__` parameter by directly running
Read the `__version__` parameter by directly running [trakt/version.py]
Python
mit
shad7/trakt.py,fuzeman/trakt.py
--- +++ @@ -1,10 +1,15 @@ -from trakt.version import __version__ +from setuptools import setup, find_packages +import os -from setuptools import setup, find_packages +base_dir = os.path.dirname(__file__) + +version = {} +with open(os.path.join(base_dir, "trakt", "version.py")) as f: + exec(f.read(), version) setup( name='trakt.py', - version=__version__, + version=version['__version__'], license='MIT', url='https://github.com/fuzeman/trakt.py',
4ffaf3d689dcb56d61c7e687b9d56e588c6ac9b6
setup.py
setup.py
from os.path import abspath, dirname, join, normpath from setuptools import find_packages, setup setup( # Basic package information: name = 'django-twilio', version = '0.1', packages = find_packages(), # Packaging options: zip_safe = False, include_package_data = True, # Package dependencies: install_requires = ['twilio==3.2.3', 'Django>=1.1'], tests_require = ['django-nose==0.1.3', 'django-coverage==1.2.1'], # Metadata for PyPI: author = 'Randall Degges', author_email = 'rdegges@gmail.com', license = 'UNLICENSE', url = 'http://twilio.com/', keywords = 'twilio telephony call phone voip sms', description = 'A simple library for building twilio-powered Django webapps.', long_description = open(normpath(join(dirname(abspath(__file__)), 'README'))).read() )
from os.path import abspath, dirname, join, normpath from setuptools import find_packages, setup setup( # Basic package information: name = 'django-twilio', version = '0.1', packages = find_packages(), # Packaging options: zip_safe = False, include_package_data = True, # Package dependencies: install_requires = ['twilio==3.2.3', 'Django>=1.1'], tests_require = ['django-nose>=0.1.3', 'coverage>=3.5'], # Metadata for PyPI: author = 'Randall Degges', author_email = 'rdegges@gmail.com', license = 'UNLICENSE', url = 'http://twilio.com/', keywords = 'twilio telephony call phone voip sms', description = 'A simple library for building twilio-powered Django webapps.', long_description = open(normpath(join(dirname(abspath(__file__)), 'README'))).read() )
Revert "Changing our ``coverage`` test dependency to ``django-coverage``."
Revert "Changing our ``coverage`` test dependency to ``django-coverage``." This reverts commit 68e8555cd2e07c4352ea06121ab262b19b3c2413. Conflicts: setup.py
Python
unlicense
rdegges/django-twilio,aditweb/django-twilio
--- +++ @@ -16,7 +16,7 @@ # Package dependencies: install_requires = ['twilio==3.2.3', 'Django>=1.1'], - tests_require = ['django-nose==0.1.3', 'django-coverage==1.2.1'], + tests_require = ['django-nose>=0.1.3', 'coverage>=3.5'], # Metadata for PyPI: author = 'Randall Degges',
32f6acb989ea5bcf7df1ad1dbc6385c48f443d3e
setup.py
setup.py
from setuptools import setup, find_packages extras_require = { 'backends': ('peewee', "redis"), } setup( name='huey', version=__import__('huey').__version__, description='huey, a little task queue', author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/huey/', packages=find_packages(), extras_require=extras_require, package_data={ 'huey': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], test_suite='runtests.runtests', entry_points={ 'console_scripts': [ 'huey_consumer = huey.bin.huey_consumer:consumer_main' ] }, scripts=['huey/bin/huey_consumer.py'], )
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fh: readme = fh.read() extras_require = { 'backends': ('peewee', "redis"), } setup( name='huey', version=__import__('huey').__version__, description='huey, a little task queue', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/huey/', packages=find_packages(), extras_require=extras_require, package_data={ 'huey': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], test_suite='runtests.runtests', entry_points={ 'console_scripts': [ 'huey_consumer = huey.bin.huey_consumer:consumer_main' ] }, scripts=['huey/bin/huey_consumer.py'], )
Add full description to package.
Add full description to package.
Python
mit
pombredanne/huey,rsalmaso/huey,coleifer/huey
--- +++ @@ -1,5 +1,9 @@ +import os from setuptools import setup, find_packages + +with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fh: + readme = fh.read() extras_require = { 'backends': ('peewee', "redis"), @@ -9,6 +13,7 @@ name='huey', version=__import__('huey').__version__, description='huey, a little task queue', + long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/huey/',
bc9814efad3050f522ad103603f681b8d74fca5c
setup.py
setup.py
""" Script to install Souma on OsX, Windows, and Unix Usage: python setup.py py2app """ import ez_setup ez_setup.use_setuptools() import sys from setuptools import setup APP = ['run.py'] if sys.platform == 'darwin': extra_options = dict( setup_requires=['py2app'], app=APP, options=dict(py2app=dict(argv_emulation=True)), ) elif sys.platform == 'win32': extra_options = dict( setup_requires=['py2exe'], app=APP, ) else: extra_options = dict( scripts=APP) setup( name="Souma", version="0.2", author="Cognitive Networks Group", author_email="cognitive-networks@googlegroups.com", packages=["soma.nucleus", "soma.web_ui", "soma.synapse"], scripts=["run.py"], license="Apache License 2.0", description="A Cognitive Network for Groups", long_description=open("README.md").read(), install_requires=[], **extra_options )
""" Script to install Souma on OsX, Windows, and Unix Usage: python setup.py py2app """ import ez_setup ez_setup.use_setuptools() import sys from setuptools import setup APP = ['run.py'] if sys.platform == 'darwin': extra_options = dict( setup_requires=['py2app'], app=APP, options=dict(py2app={ "argv_emulation": True, "bdist_base": "../build", "dist_dir": "../dist" }), ) elif sys.platform == 'win32': extra_options = dict( setup_requires=['py2exe'], app=APP, ) else: extra_options = dict( scripts=APP) setup( name="Souma", version="0.2", author="Cognitive Networks Group", author_email="cognitive-networks@googlegroups.com", packages=["nucleus", "web_ui", "synapse", "astrolab"], scripts=["run.py"], license="Apache License 2.0", description="A Cognitive Network for Groups", long_description=open("README.md").read(), install_requires=[], **extra_options )
Create build/dist directories in ./..
Create build/dist directories in ./..
Python
apache-2.0
ciex/souma,ciex/souma,ciex/souma
--- +++ @@ -16,7 +16,11 @@ extra_options = dict( setup_requires=['py2app'], app=APP, - options=dict(py2app=dict(argv_emulation=True)), + options=dict(py2app={ + "argv_emulation": True, + "bdist_base": "../build", + "dist_dir": "../dist" + }), ) elif sys.platform == 'win32': extra_options = dict( @@ -32,7 +36,7 @@ version="0.2", author="Cognitive Networks Group", author_email="cognitive-networks@googlegroups.com", - packages=["soma.nucleus", "soma.web_ui", "soma.synapse"], + packages=["nucleus", "web_ui", "synapse", "astrolab"], scripts=["run.py"], license="Apache License 2.0", description="A Cognitive Network for Groups",
997bebada0ff6e3f9b9110a4c583ca5ef59238f0
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages readme = open('README.rst').read() requirements = map(str.strip, open('requirements.txt').readlines()) VERSION = open('VERSION').read().strip() setup( name='sqlcop', version=VERSION, description='A cli tool to check and guard against anti-patterns', long_description=readme + '\n\n', author='Kevin Qiu', author_email='kevin@freshbooks.com', url='https://github.com/freshbooks/sqlcop', packages=find_packages(exclude=['test*']), include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='sqlcop', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], test_suite='tests', entry_points={ 'console_scripts': [ 'sqlcop=sqlcop.cli:main', ] }, )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages readme = open('README.rst').read() requirements = open('./requirements.txt', 'r').readlines() VERSION = open('VERSION').read().strip() setup( name='sqlcop', version=VERSION, description='A cli tool to check and guard against anti-patterns', long_description=readme + '\n\n', author='Kevin Qiu', author_email='kevin@freshbooks.com', url='https://github.com/freshbooks/sqlcop', packages=find_packages(exclude=['test*']), include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='sqlcop', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], test_suite='tests', entry_points={ 'console_scripts': [ 'sqlcop=sqlcop.cli:main', ] }, )
Update the way we fetch requirements, it wasn't resolving dependencies before.
Update the way we fetch requirements, it wasn't resolving dependencies before.
Python
bsd-3-clause
freshbooks/sqlcop
--- +++ @@ -10,7 +10,7 @@ readme = open('README.rst').read() -requirements = map(str.strip, open('requirements.txt').readlines()) +requirements = open('./requirements.txt', 'r').readlines() VERSION = open('VERSION').read().strip()
5e9818c17b94be9c60271e756e7e88aedc63cb7a
setup.py
setup.py
from setuptools import setup, find_packages setup( name='akanda-rug', version='0.1.5', description='Akanda Router Update Generator manages tenant routers', author='DreamHost', author_email='dev-community@dreamhost.com', url='http://github.com/dreamhost/akanda-rug', license='BSD', install_requires=[ 'netaddr>=0.7.5', 'httplib2>=0.7.2', 'python-quantumclient>=2.1', 'oslo.config' ], namespace_packages=['akanda'], packages=find_packages(), include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'akanda-rug-service=akanda.rug.service:main' ] }, )
from setuptools import setup, find_packages setup( name='akanda-rug', version='0.1.5', description='Akanda Router Update Generator manages tenant routers', author='DreamHost', author_email='dev-community@dreamhost.com', url='http://github.com/dreamhost/akanda-rug', license='BSD', install_requires=[ 'netaddr>=0.7.5', 'httplib2>=0.7.2', 'python-quantumclient>=2.1', 'oslo.config' ], namespace_packages=['akanda'], packages=find_packages(exclude=['test']), include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'akanda-rug-service=akanda.rug.service:main' ] }, )
Exclude test folder from package
Exclude test folder from package DHC-1102 Ignore the test directory when looking for python packages to avoid having the files installed Change-Id: Ia30e821109c0f75f0f0c51bb995b2099aa30e063 Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
Python
apache-2.0
dreamhost/akanda-rug,openstack/akanda-rug,markmcclain/astara,stackforge/akanda-rug,stackforge/akanda-rug,openstack/akanda-rug
--- +++ @@ -15,7 +15,7 @@ 'oslo.config' ], namespace_packages=['akanda'], - packages=find_packages(), + packages=find_packages(exclude=['test']), include_package_data=True, zip_safe=False, entry_points={
6fd8bf7a3113c82c88325dd04fe610ba10049855
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup long_description = ''' This module allows you to perform IP subnet calculations, there is support for both IPv4 and IPv6 CIDR notation. ''' setup(name='ipcalc', version='0.4', description='IP subnet calculator', long_description=long_description, author='Wijnand Modderman', author_email='python@tehmaze.com', url='http://dev.tehmaze.com/projects/ipcalc', packages = [''], package_dir = {'': 'src'}, )
#!/usr/bin/env python from distutils.core import setup setup(name='ipcalc', version='0.4', description='IP subnet calculator', long_description=file('README.rst').read(), author='Wijnand Modderman', author_email='python@tehmaze.com', url='http://dev.tehmaze.com/projects/ipcalc', packages = [''], package_dir = {'': 'src'}, )
Read README.rst for the long description
Read README.rst for the long description
Python
bsd-2-clause
panaceya/ipcalc,tehmaze/ipcalc
--- +++ @@ -2,15 +2,10 @@ from distutils.core import setup -long_description = ''' -This module allows you to perform IP subnet calculations, there is support -for both IPv4 and IPv6 CIDR notation. -''' - setup(name='ipcalc', version='0.4', description='IP subnet calculator', - long_description=long_description, + long_description=file('README.rst').read(), author='Wijnand Modderman', author_email='python@tehmaze.com', url='http://dev.tehmaze.com/projects/ipcalc',
f66a205ad14bdd55011abb2b2e9c821162358e8e
setup.py
setup.py
import wsgi_intercept from setuptools import setup, find_packages CLASSIFIERS = """ Environment :: Web Environment Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.6 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 Topic :: Internet :: WWW/HTTP :: WSGI Topic :: Software Development :: Testing """.strip().splitlines() META = { 'name': 'wsgi_intercept', 'version': wsgi_intercept.__version__, 'author': 'Titus Brown, Kumar McMillan, Chris Dent', 'author_email': 'cdent@peermore.com', 'description': 'wsgi_intercept installs a WSGI application in place of a real URI for testing.', # What will the name be? 'url': 'http://pypi.python.org/pypi/wsgi_intercept', 'long_description': wsgi_intercept.__doc__, 'license': 'MIT License', 'classifiers': CLASSIFIERS, 'packages': find_packages(), 'extras_require': { 'testing': [ 'pytest>=2.4', 'httplib2', 'requests>=2.0.1' ], }, } if __name__ == '__main__': setup(**META)
import wsgi_intercept from setuptools import setup, find_packages CLASSIFIERS = """ Environment :: Web Environment Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.6 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 Programming Language :: Python :: 3.4 Topic :: Internet :: WWW/HTTP :: WSGI Topic :: Software Development :: Testing """.strip().splitlines() META = { 'name': 'wsgi_intercept', 'version': wsgi_intercept.__version__, 'author': 'Titus Brown, Kumar McMillan, Chris Dent', 'author_email': 'cdent@peermore.com', 'description': 'wsgi_intercept installs a WSGI application in place of a real URI for testing.', # What will the name be? 'url': 'http://pypi.python.org/pypi/wsgi_intercept', 'long_description': wsgi_intercept.__doc__, 'license': 'MIT License', 'classifiers': CLASSIFIERS, 'packages': find_packages(), 'extras_require': { 'testing': [ 'pytest>=2.4', 'httplib2', 'requests>=2.0.1' ], }, } if __name__ == '__main__': setup(**META)
Add trove classifier for Python 3.4 support
Add trove classifier for Python 3.4 support
Python
mit
cdent/wsgi-intercept,sileht/python3-wsgi-intercept
--- +++ @@ -12,6 +12,7 @@ Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.3 +Programming Language :: Python :: 3.4 Topic :: Internet :: WWW/HTTP :: WSGI Topic :: Software Development :: Testing """.strip().splitlines()
d38d26d1d613ba9550bb247eaed8af62bbd99d16
setup.py
setup.py
import subprocess import sys from distutils.core import setup, Command class TestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, 'test_facebook.py']) raise SystemExit(errno) setup( name='facebook-ads-api', version='0.1.40', author='Chee-Hyung Yoon', author_email='yoonchee@gmail.com', py_modules=['facebook', ], url='http://github.com/narrowcast/facebook-ads-api', license='LICENSE', description='Python client for the Facebook Ads API', long_description=open('README.md').read(), cmdclass={'test': TestCommand}, )
import subprocess import sys from distutils.core import setup, Command class TestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, 'test_facebook.py']) raise SystemExit(errno) setup( name='facebook-ads-api', version='0.1.41', author='Chee-Hyung Yoon', author_email='yoonchee@gmail.com', py_modules=['facebook', ], url='http://github.com/narrowcast/facebook-ads-api', license='LICENSE', description='Python client for the Facebook Ads API', long_description=open('README.md').read(), cmdclass={'test': TestCommand}, )
Add method for adding users to a custom audience.
Add method for adding users to a custom audience.
Python
mit
GallopLabs/facebook-ads-api,narrowcast/facebook-ads-api,taenyon/facebook-ads-api
--- +++ @@ -18,7 +18,7 @@ setup( name='facebook-ads-api', - version='0.1.40', + version='0.1.41', author='Chee-Hyung Yoon', author_email='yoonchee@gmail.com', py_modules=['facebook', ],
de26cffafb9aba0e4981be2bd40617719052b438
setup.py
setup.py
""" Copyright 2017 BlazeMeter Inc. 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 setuptools import setup setup( name="apiritif", packages=['apiritif'], version="0.6.1", description='Python framework for API testing', license='Apache 2.0', platform='any', author='Dimitri Pribysh', author_email='pribysh@blazemeter.com', url='https://github.com/Blazemeter/apiritif', download_url='https://github.com/Blazemeter/apiritif', docs_url='https://github.com/Blazemeter/apiritif', install_requires=['requests>=2.11.1', 'jsonpath-rw', 'lxml'], )
""" Copyright 2017 BlazeMeter Inc. 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 setuptools import setup setup( name="apiritif", packages=['apiritif'], version="0.6.1", description='Python framework for API testing', long_description=open('README.md').read(), long_description_content_type='text/markdown', license='Apache 2.0', platform='any', author='Dimitri Pribysh', author_email='pribysh@blazemeter.com', url='https://github.com/Blazemeter/apiritif', download_url='https://github.com/Blazemeter/apiritif', docs_url='https://github.com/Blazemeter/apiritif', install_requires=['requests>=2.11.1', 'jsonpath-rw', 'lxml'], )
Add long description for PyPI
Add long description for PyPI
Python
apache-2.0
Blazemeter/apiritif,Blazemeter/apiritif
--- +++ @@ -21,6 +21,8 @@ packages=['apiritif'], version="0.6.1", description='Python framework for API testing', + long_description=open('README.md').read(), + long_description_content_type='text/markdown', license='Apache 2.0', platform='any', author='Dimitri Pribysh',
736963683e57256bbcd6e2c7d620f8651946c40a
setup.py
setup.py
from distutils.core import setup setup( name='permission', version='0.2.0', author='Zhipeng Liu', author_email='hustlzp@qq.com', url='https://github.com/hustlzp/permission', packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
from distutils.core import setup setup( name='permission', version='0.2.0', author='Zhipeng Liu', author_email='hustlzp@qq.com', url='https://github.com/hustlzp/permission', packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Use README.rst instead od README.md for doc.
Use README.rst instead od README.md for doc.
Python
mit
hustlzp/permission
--- +++ @@ -9,7 +9,7 @@ packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', - long_description=open('README.md').read(), + long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment',
2c5e1c0803675df0f93b62f09eb355b2cd43f907
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup import os from setuptools import find_packages name = 'Mikko Korpela' # I might be just a little bit too much afraid of those bots.. address = name.lower().replace(' ', '.')+chr(64)+'gmail.com' setup(name='robotframework-pabot', version='0.39', description='Parallel test runner for Robot Framework', long_description='A parallel executor for Robot Framework tests.' 'With Pabot you can split one execution into multiple and save test execution time.', author=name, author_email=address, url='https://github.com/mkorpela/pabot', download_url='https://pypi.python.org/pypi/robotframework-pabot', packages=find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Development Status :: 5 - Production/Stable', 'Framework :: Robot Framework' ], scripts=[os.path.join('scripts', 'pabot'), os.path.join('scripts', 'pabot.bat')], license='Apache License, Version 2.0', install_requires=['robotframework', 'robotremoteserver>=1.1'])
#!/usr/bin/env python from distutils.core import setup import os from setuptools import find_packages name = 'Mikko Korpela' # I might be just a little bit too much afraid of those bots.. address = name.lower().replace(' ', '.')+chr(64)+'gmail.com' setup(name='robotframework-pabot', version='0.39', description='Parallel test runner for Robot Framework', long_description='A parallel executor for Robot Framework tests.' 'With Pabot you can split one execution into multiple and save test execution time.', author=name, author_email=address, url='https://github.com/mkorpela/pabot', download_url='https://pypi.python.org/pypi/robotframework-pabot', packages=find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Development Status :: 5 - Production/Stable', 'Framework :: Robot Framework' ], scripts=[os.path.join('scripts', 'pabot'), os.path.join('scripts', 'pabot.bat')], license='Apache License, Version 2.0', install_requires=['robotframework', 'robotremoteserver>=1.1'])
Add note about python 3 support
Add note about python 3 support
Python
apache-2.0
mkorpela/pabot,mkorpela/pabot
--- +++ @@ -22,6 +22,7 @@ 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Development Status :: 5 - Production/Stable',