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 |
|---|---|---|---|---|---|---|---|---|---|---|
fe6e24d3cadd71b7c613926f7baa26947f6caadd | webmention_plugin.py | webmention_plugin.py | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
info = UrlInfo(url)
in_reply_to = info.inReplyTo()
if url and in_reply_to:
sender = WebmentionSend(url, in_reply_to, verify=False)
sender.send()
| from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
in_reply_to = post.in_reply_to
if url and in_reply_to:
print "Sending webmention {} to {}".format(url, in_reply_to)
sender = WebmentionSend(url, in_reply_to)
sender.send(verify=False)
print "Finished sending webmention"
| Update webmention plugin to new version | Update webmention plugin to new version
| Python | bsd-2-clause | thedod/redwind,Lancey6/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind | ---
+++
@@ -3,9 +3,9 @@
def handle_new_or_edit(post):
url = post.permalink_url
- info = UrlInfo(url)
- in_reply_to = info.inReplyTo()
-
+ in_reply_to = post.in_reply_to
if url and in_reply_to:
- sender = WebmentionSend(url, in_reply_to, verify=False)
- sender.send()
+ print "Sending webmention {} to {}".format(url, in_reply_to)
+ sender = WebmentionSend(url, in_reply_to)
+ sender.send(verify=False)
+ print "Finished sending webmention" |
1bc674ea94209ff20a890b9743a28bc0b9d8cb89 | motels/serializers.py | motels/serializers.py | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M')
class Meta:
model = Comment
fields = ('id', 'motel', 'body', 'ranking',
'created_date')
class MotelListSerializer(serializers.ModelSerializer):
class Meta:
model = Motel
fields = ('id', 'name', 'town', 'latitude',
'longitude', 'ranking', 'telephone',
'website', 'description')
class MotelSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True, read_only=True)
class Meta:
model = Motel
fields = ('id', 'name', 'town', 'latitude',
'longitude','ranking','telephone',
'website','description', 'comments')
class TownSerializer(serializers.ModelSerializer):
class Meta:
model = Town
fields = ('name', 'latitude', 'longitude') | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False)
class Meta:
model = Comment
fields = ('id', 'motel', 'body', 'ranking',
'created_date')
class MotelListSerializer(serializers.ModelSerializer):
class Meta:
model = Motel
fields = ('id', 'name', 'town', 'latitude',
'longitude', 'ranking', 'telephone',
'website', 'description')
class MotelSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True, read_only=True)
class Meta:
model = Motel
fields = ('id', 'name', 'town', 'latitude',
'longitude','ranking','telephone',
'website','description', 'comments')
class TownSerializer(serializers.ModelSerializer):
class Meta:
model = Town
fields = ('name', 'latitude', 'longitude') | Fix bug with comment POST (created_date was required) | Fix bug with comment POST (created_date was required)
| Python | mit | amartinez1/5letrasAPI | ---
+++
@@ -4,7 +4,7 @@
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
- created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M')
+ created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False)
class Meta:
model = Comment |
11f6f98753eae023da73afa111403d34ca818df0 | armet/attributes/decimal.py | armet/attributes/decimal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import six
from .attribute import Attribute
import decimal
class DecimalAttribute(Attribute):
type = decimal.Decimal
def prepare(self, value):
if value is None:
return None
return six.text_type(value)
def clean(self, value):
if isinstance(value, decimal.Decimal):
# Value is already an integer.
return value
if isinstance(value, six.string_types):
# Strip the string of whitespace
value = value.strip()
if not value:
# Value is nothing; return nothing.
return None
try:
# Attempt to coerce whatever we have as an int.
return decimal.Decimal(value)
except ValueError:
# Failed to do so.
raise ValueError('Not a valid decimal value.')
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import six
from .attribute import Attribute
import decimal
class DecimalAttribute(Attribute):
type = decimal.Decimal
def prepare(self, value):
if value is None:
return None
return six.text_type(float(value))
def clean(self, value):
if isinstance(value, decimal.Decimal):
# Value is already an integer.
return value
if isinstance(value, six.string_types):
# Strip the string of whitespace
value = value.strip()
if not value:
# Value is nothing; return nothing.
return None
try:
# Attempt to coerce whatever we have as an int.
return decimal.Decimal(value)
except ValueError:
# Failed to do so.
raise ValueError('Not a valid decimal value.')
| Convert to float then to text. | Convert to float then to text.
| Python | mit | armet/python-armet | ---
+++
@@ -13,7 +13,7 @@
if value is None:
return None
- return six.text_type(value)
+ return six.text_type(float(value))
def clean(self, value):
if isinstance(value, decimal.Decimal): |
a4dda07a7c1c8883a8828f43abae51826711b33e | test/343-winter-sports-resorts.py | test/343-winter-sports-resorts.py | assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
'sort_key': 27 })
| assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
'sort_key': 33 })
| Sort keys changed, update test. | Sort keys changed, update test.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -1,4 +1,4 @@
assert_has_feature(
15, 5467, 12531, 'landuse',
{ 'kind': 'winter_sports',
- 'sort_key': 27 })
+ 'sort_key': 33 }) |
7c425075280fea87b1c8dd61b43f51e19e84b770 | astropy/utils/exceptions.py | astropy/utils/exceptions.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class AstropyWarning(Warning):
"""
The base warning class from which all Astropy warnings should inherit.
Any warning inheriting from this class is handled by the Astropy logger.
"""
class AstropyUserWarning(UserWarning, AstropyWarning):
"""
The primary warning class for Astropy.
Use this if you do not need a specific sub-class.
"""
class AstropyDeprecationWarning(DeprecationWarning, AstropyWarning):
"""
A warning class to indicate a deprecated feature.
"""
class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning):
"""
A warning class to indicate a soon-to-be deprecated feature.
"""
class AstropyBackwardsIncompatibleChangeWarning(AstropyWarning):
"""
A warning class indicating a change in astropy that is incompatible
with previous versions.
The suggested procedure is to issue this warning for the version in
which the change occurs, and remove it for all following versions.
"""
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class AstropyWarning(Warning):
"""
The base warning class from which all Astropy warnings should inherit.
Any warning inheriting from this class is handled by the Astropy logger.
"""
class AstropyUserWarning(UserWarning, AstropyWarning):
"""
The primary warning class for Astropy.
Use this if you do not need a specific sub-class.
"""
class AstropyDeprecationWarning(AstropyWarning):
"""
A warning class to indicate a deprecated feature.
"""
class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning):
"""
A warning class to indicate a soon-to-be deprecated feature.
"""
class AstropyBackwardsIncompatibleChangeWarning(AstropyWarning):
"""
A warning class indicating a change in astropy that is incompatible
with previous versions.
The suggested procedure is to issue this warning for the version in
which the change occurs, and remove it for all following versions.
"""
| Remove DeprecationWarning superclass for AstropyDeprecationWarning | Remove DeprecationWarning superclass for AstropyDeprecationWarning
we do this because in py2.7, DeprecationWarning and subclasses are hidden by default, but we want astropy's deprecations to get shown by default
| Python | bsd-3-clause | bsipocz/astropy,astropy/astropy,funbaker/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,larrybradley/astropy,lpsinger/astropy,dhomeier/astropy,funbaker/astropy,MSeifert04/astropy,stargaser/astropy,dhomeier/astropy,mhvk/astropy,AustereCuriosity/astropy,saimn/astropy,pllim/astropy,larrybradley/astropy,joergdietrich/astropy,stargaser/astropy,tbabej/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,kelle/astropy,funbaker/astropy,bsipocz/astropy,AustereCuriosity/astropy,pllim/astropy,saimn/astropy,kelle/astropy,lpsinger/astropy,joergdietrich/astropy,StuartLittlefair/astropy,bsipocz/astropy,AustereCuriosity/astropy,kelle/astropy,AustereCuriosity/astropy,stargaser/astropy,StuartLittlefair/astropy,tbabej/astropy,saimn/astropy,MSeifert04/astropy,saimn/astropy,tbabej/astropy,larrybradley/astropy,larrybradley/astropy,joergdietrich/astropy,tbabej/astropy,pllim/astropy,kelle/astropy,aleksandr-bakanov/astropy,astropy/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,mhvk/astropy,kelle/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,lpsinger/astropy,DougBurke/astropy,mhvk/astropy,pllim/astropy,astropy/astropy,dhomeier/astropy,astropy/astropy,DougBurke/astropy,lpsinger/astropy,bsipocz/astropy,tbabej/astropy,lpsinger/astropy,astropy/astropy,larrybradley/astropy,MSeifert04/astropy,joergdietrich/astropy,funbaker/astropy,saimn/astropy,pllim/astropy,mhvk/astropy,stargaser/astropy,joergdietrich/astropy,mhvk/astropy,MSeifert04/astropy,StuartLittlefair/astropy,DougBurke/astropy | ---
+++
@@ -24,7 +24,7 @@
"""
-class AstropyDeprecationWarning(DeprecationWarning, AstropyWarning):
+class AstropyDeprecationWarning(AstropyWarning):
"""
A warning class to indicate a deprecated feature.
""" |
a8e96366a55684c14835a3ef183708fa7177bd67 | server/lib/python/cartodb_services/setup.py | server/lib/python/cartodb_services/setup.py | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.19.1',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps api mapping tools geocoder routing',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mockredispy', 'mock'],
}
)
| """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.20.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps api mapping tools geocoder routing',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mockredispy', 'mock'],
}
)
| Bump for the python library version | Bump for the python library version
| Python | bsd-3-clause | CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api | ---
+++
@@ -10,7 +10,7 @@
setup(
name='cartodb_services',
- version='0.19.1',
+ version='0.20.0',
description='CartoDB Services API Python Library',
|
e0719d89d00471168ae65891a1024608ff5ea608 | settings_example.py | settings_example.py | """
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServer
# If this is set to a valid path, all files extracted from emails will be stored
# in sub-folders within it.
SAVE_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
#- file: %(pathname)s
# function: %(funcName)s
LOGGING_FORMAT = '''
- level: %(levelname)s
line: %(lineno)s
logger: %(name)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_KWARGS = dict(
fromat=LOGGING_FORMAT,
level=logging.DEBUG
)
def get_file_types():
file_types = None
with open(SETTINGS_YAML_PATH) as r:
file_types = yaml.load(r)
return file_types
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| """
Example settings module.
This should be copied as `settings.py` and the values modified there.
That file is ignored by the repo, since it will contain environment
specific and sensitive information (like passwords).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServer
# If this is set to a valid path, all files extracted from emails will be stored
# in sub-folders within it.
SAVE_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
#- file: %(pathname)s
# function: %(funcName)s
LOGGING_FORMAT = '''
- level: %(levelname)s
line: %(lineno)s
logger: %(name)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_KWARGS = dict(
format=LOGGING_FORMAT,
level=logging.DEBUG
)
def get_file_types():
file_types = None
with open(SETTINGS_YAML_PATH) as r:
file_types = yaml.load(r)
return file_types
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| Fix logging format settings example | Fix logging format settings example
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | ---
+++
@@ -35,7 +35,7 @@
'''.strip()
LOGGING_KWARGS = dict(
- fromat=LOGGING_FORMAT,
+ format=LOGGING_FORMAT,
level=logging.DEBUG
)
|
98ab2a2ac0279f504195e49d55ff7be817592a75 | kirppu/app/checkout/urls.py | kirppu/app/checkout/urls.py | from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(func.url, func.name, name=func.view_name)
for func in AJAX_FUNCTIONS.itervalues()
])
urlpatterns = patterns('kirppu.app.checkout.api', *_urls)
| from django.conf import settings
from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
if settings.KIRPPU_CHECKOUT_ACTIVE:
# Only activate API when checkout is active.
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(func.url, func.name, name=func.view_name)
for func in AJAX_FUNCTIONS.itervalues()
])
else:
_urls = []
urlpatterns = patterns('kirppu.app.checkout.api', *_urls)
| Fix access to checkout API. | Fix access to checkout API.
Prevent access to checkout API urls when checkout is not activated by
not creating urlpatterns.
| Python | mit | mniemela/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu | ---
+++
@@ -1,12 +1,19 @@
+from django.conf import settings
from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
-_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
-_urls.extend([
- url(func.url, func.name, name=func.view_name)
- for func in AJAX_FUNCTIONS.itervalues()
-])
+if settings.KIRPPU_CHECKOUT_ACTIVE:
+ # Only activate API when checkout is active.
+
+ _urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
+ _urls.extend([
+ url(func.url, func.name, name=func.view_name)
+ for func in AJAX_FUNCTIONS.itervalues()
+ ])
+
+else:
+ _urls = []
urlpatterns = patterns('kirppu.app.checkout.api', *_urls) |
535b07758a16dec2ce79781f19b34a96044b99d3 | fluent_contents/conf/plugin_template/models.py | fluent_contents/conf/plugin_template/models.py | from django.db import models
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
@python_2_unicode_compatible
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models.CharField(_("Title"), max_length=200)
class Meta:
verbose_name = _("{{ model|title }}")
verbose_name_plural = _("{{ model|title }}s")
def __str__(self):
return self.title
| from django.db import models
from django.utils.translation import gettext_lazy as _
from fluent_contents.models import ContentItem
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models.CharField(_("Title"), max_length=200)
class Meta:
verbose_name = _("{{ model|title }}")
verbose_name_plural = _("{{ model|title }}s")
def __str__(self):
return self.title
| Update plugin_template to Python 3-only standards | Update plugin_template to Python 3-only standards
| Python | apache-2.0 | edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents | ---
+++
@@ -1,11 +1,9 @@
from django.db import models
-from django.utils.six import python_2_unicode_compatible
-from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import gettext_lazy as _
from fluent_contents.models import ContentItem
-@python_2_unicode_compatible
class {{ model }}(ContentItem):
"""
CMS plugin data model to ... |
505f7f6b243502cb4d6053ac7d54e0ecad15c557 | functional_tests/test_question_page.py | functional_tests/test_question_page.py | from selenium import webdriver
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
"""Cleanup browser."""
self.browser.quit()
def test_typical_question(self):
"""When the user does it right, it should work."""
self.browser.get(SERVER_URL+"/question")
submit_button = self.browser.find_element_by_css_selector("input[type=submit]")
question_input = self.browser.find_element_by_tag_name("textarea")
if __name__ == '__main__':
unittest.main()
| from selenium import webdriver
from hamcrest import *
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
"""Cleanup browser."""
self.browser.quit()
def test_typical_question(self):
"""When the user does it right, it should work."""
self.browser.get(SERVER_URL+"/question")
submit_button = self.browser.find_element_by_css_selector("input[type=submit]")
question_input = self.browser.find_element_by_tag_name("textarea")
question_input.send_keys(LONG_QUESTION)
submit_button.click()
displayed_question = self.browser.find_element_by_class_name("question")
assert_that(displayed_question.text, equal_to(LONG_QUESTION),
"Questions should be shown after they are submitted")
LONG_QUESTION = """Centuries ago there lived--
"A king!" my little readers will say immediately.
No, children, you are mistaken. Once upon a time there was a piece of
wood. It was not an expensive piece of wood. Far from it. Just a common
block of firewood, one of those thick, solid logs that are put on the
fire in winter to make cold rooms cozy and warm.
I do not know how this really happened, yet the fact remains that one
fine day this piece of wood found itself in the shop of an old
carpenter. His real name was Mastro Antonio, but everyone called him
Mastro Cherry, for the tip of his nose was so round and red and shiny
that it looked like a ripe cherry.
"""
if __name__ == '__main__':
unittest.main()
| Test for submitting and viewing questions. | Test for submitting and viewing questions.
| Python | agpl-3.0 | bjaress/shortanswer | ---
+++
@@ -1,4 +1,5 @@
from selenium import webdriver
+from hamcrest import *
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
@@ -22,6 +23,29 @@
self.browser.get(SERVER_URL+"/question")
submit_button = self.browser.find_element_by_css_selector("input[type=submit]")
question_input = self.browser.find_element_by_tag_name("textarea")
+ question_input.send_keys(LONG_QUESTION)
+ submit_button.click()
+ displayed_question = self.browser.find_element_by_class_name("question")
+ assert_that(displayed_question.text, equal_to(LONG_QUESTION),
+ "Questions should be shown after they are submitted")
+
+
+LONG_QUESTION = """Centuries ago there lived--
+
+"A king!" my little readers will say immediately.
+
+No, children, you are mistaken. Once upon a time there was a piece of
+wood. It was not an expensive piece of wood. Far from it. Just a common
+block of firewood, one of those thick, solid logs that are put on the
+fire in winter to make cold rooms cozy and warm.
+
+I do not know how this really happened, yet the fact remains that one
+fine day this piece of wood found itself in the shop of an old
+carpenter. His real name was Mastro Antonio, but everyone called him
+Mastro Cherry, for the tip of his nose was so round and red and shiny
+that it looked like a ripe cherry.
+"""
+
if __name__ == '__main__':
unittest.main() |
20b0e705fe6eedb05a94a3e9cb978b65a525fe91 | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-multi-targets/master@smspillaz/cmake-multi-targets",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit",
"sanitizers-cmake/0.0.1@smspillaz/sanitizers-cmake")
url = "http://github.com/polysquare/sanitize-target-cmake"
license = "MIT"
def source(self):
zip_name = "sanitize-target-cmake.zip"
download("https://github.com/polysquare/"
"sanitize-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/sanitize-target-cmake",
src="sanitize-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.3"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-multi-targets/master@smspillaz/cmake-multi-targets",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit",
"sanitizers-cmake/0.0.1@smspillaz/sanitizers-cmake")
url = "http://github.com/polysquare/sanitize-target-cmake"
license = "MIT"
def source(self):
zip_name = "sanitize-target-cmake.zip"
download("https://github.com/polysquare/"
"sanitize-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/sanitize-target-cmake",
src="sanitize-target-cmake-" + VERSION,
keep_path=True)
| Bump version: 0.0.2 -> 0.0.3 | Bump version: 0.0.2 -> 0.0.3
[ci skip]
| Python | mit | polysquare/sanitize-target-cmake | ---
+++
@@ -2,7 +2,7 @@
from conans.tools import download, unzip
import os
-VERSION = "0.0.2"
+VERSION = "0.0.3"
class SanitizeTargetCMakeConan(ConanFile): |
8b1818aefd6180548cf3b9770eb7a4d93e827fd7 | alignak_app/__init__.py | alignak_app/__init__.py | #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| Remove import of all Class app | Remove import of all Class app
| Python | agpl-3.0 | Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app | ---
+++
@@ -6,9 +6,6 @@
This module is an Alignak App Indicator
"""
-
-# Specific Application
-from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0) |
f5747773e05fc892883c852e495f9e166888d1ea | rapt/connection.py | rapt/connection.py | import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
password = keyring.get_password(hostname, username)
if not password:
prompt_tmpl = "{username}@{hostname}'s password: "
prompt = prompt_tmpl.format(username=username, hostname=hostname)
password = getpass.getpass(prompt)
keyring.set_password(hostname, username, password)
def get_vr(username=None):
username = os.environ['VELOCIRAPTOR_USERNAME']
base = os.environ['VELOCIRAPTOR_URL']
set_password(base, username)
return Velociraptor(base=base, username=username)
| import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname
password = keyring.get_password(hostname, username)
if not password:
prompt_tmpl = "{username}@{hostname}'s password: "
prompt = prompt_tmpl.format(username=username, hostname=hostname)
password = getpass.getpass(prompt)
keyring.set_password(hostname, username, password)
def get_vr(username=None):
username = os.environ['VELOCIRAPTOR_USERNAME']
base = os.environ['VELOCIRAPTOR_URL']
set_password(base, username)
return Velociraptor(base=base, username=username)
| Set the hostname when it localhost | Set the hostname when it localhost
| Python | bsd-3-clause | yougov/rapt,yougov/rapt | ---
+++
@@ -16,6 +16,7 @@
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
+ os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname
password = keyring.get_password(hostname, username)
if not password: |
4a0491fb018cd96e510f25141dda5e7ceff423b4 | client/test/server_tests.py | client/test/server_tests.py | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def tearDown(self):
pass
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def testGetCommandNotFound(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def testGetCommandNotFound(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) | Remove tearDown not used method | Remove tearDown not used method
| Python | mit | CaminsTECH/owncloud-test | ---
+++
@@ -24,9 +24,6 @@
self.server = Server('')
self.server._requests = mock()
- def tearDown(self):
- pass
-
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get() |
a0863e53ccc8f548486eaa5f3e1f79774dea4b75 | tests/api/views/clubs/list_test.py | tests/api/views/clubs/list_test.py | from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aachen"},
{"id": sfn.id, "name": "Sportflug Niederberg"},
]
}
def test_name_filter(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == {"clubs": []}
| from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
{
"clubs": ExactSequence(
[
{"id": int, "name": "LV Aachen"},
{"id": int, "name": "Sportflug Niederberg"},
]
)
}
)
def test_name_filter(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([])})
| Use `pytest-voluptuous` to simplify JSON compare code | api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code
| Python | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines | ---
+++
@@ -1,32 +1,35 @@
+from pytest_voluptuous import S
+from voluptuous.validators import ExactSequence
+
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
- sfn = clubs.sfn()
- lva = clubs.lva()
- add_fixtures(db_session, sfn, lva)
+ add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
- assert res.json == {
- "clubs": [
- {"id": lva.id, "name": "LV Aachen"},
- {"id": sfn.id, "name": "Sportflug Niederberg"},
- ]
- }
+ assert res.json == S(
+ {
+ "clubs": ExactSequence(
+ [
+ {"id": int, "name": "LV Aachen"},
+ {"id": int, "name": "Sportflug Niederberg"},
+ ]
+ )
+ }
+ )
def test_name_filter(db_session, client):
- sfn = clubs.sfn()
- lva = clubs.lva()
- add_fixtures(db_session, sfn, lva)
+ add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
- assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
+ assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
- assert res.json == {"clubs": []}
+ assert res.json == S({"clubs": ExactSequence([])}) |
b74ae3ddba11ddc785da3a94bfff8f964d7c4ac6 | tests/test_run_ccoverage.py | tests/test_run_ccoverage.py | # coding=utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Test the run_ccoverage.py file."""
from __future__ import absolute_import, division, print_function, unicode_literals # isort:skip
import logging
import unittest
import funfuzz
FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test")
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("flake8").setLevel(logging.WARNING)
class RunCcoverageTests(unittest.TestCase):
""""TestCase class for functions in run_ccoverage.py"""
def test_main(self):
"""Run run_ccoverage with test parameters."""
build_url = "https://build.fuzzing.mozilla.org/builds/jsshell-mc-64-opt-gcov.zip"
# run_ccoverage's main method does not actually return anything.
self.assertTrue(not funfuzz.run_ccoverage.main(argparse_args=["--url", build_url]))
| # coding=utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Test the run_ccoverage.py file."""
from __future__ import absolute_import, division, print_function, unicode_literals # isort:skip
import logging
import unittest
import pytest
import funfuzz
FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test")
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("flake8").setLevel(logging.WARNING)
class RunCcoverageTests(unittest.TestCase):
""""TestCase class for functions in run_ccoverage.py"""
@pytest.mark.skip(reason="disable for now until actual use")
def test_main(self):
"""Run run_ccoverage with test parameters."""
build_url = "https://build.fuzzing.mozilla.org/builds/jsshell-mc-64-opt-gcov.zip"
# run_ccoverage's main method does not actually return anything.
self.assertTrue(not funfuzz.run_ccoverage.main(argparse_args=["--url", build_url]))
| Revert "Re-activate code coverage test." | Revert "Re-activate code coverage test."
This reverts commit 9a5d5122139aedddbbcea169525e924269f6c20a.
| Python | mpl-2.0 | nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,nth10sd/funfuzz | ---
+++
@@ -11,6 +11,8 @@
import logging
import unittest
+import pytest
+
import funfuzz
FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test")
@@ -20,6 +22,7 @@
class RunCcoverageTests(unittest.TestCase):
""""TestCase class for functions in run_ccoverage.py"""
+ @pytest.mark.skip(reason="disable for now until actual use")
def test_main(self):
"""Run run_ccoverage with test parameters."""
build_url = "https://build.fuzzing.mozilla.org/builds/jsshell-mc-64-opt-gcov.zip" |
93e447512b32e61ce41d25e73bb1592a3f8ac556 | gitfs/views/history.py | gitfs/views/history.py | from .view import View
class HistoryView(View):
pass
| from datetime import datetime
from errno import ENOENT
from stat import S_IFDIR
from pygit2 import GIT_SORT_TIME
from gitfs import FuseOSError
from log import log
from .view import View
class HistoryView(View):
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def _get_commits_by_date(self, date):
"""
Retrieves all the commits from a particular date.
:param date: date with the format: yyyy-mm-dd
:type date: str
:returns: a list containg the commits for that day. Each list item
will have the format: hh:mm:ss-<short_sha1>, where short_sha1 is
the short sha1 of the commit.
:rtype: list
"""
date = datetime.strptime(date, '%Y-%m-%d').date()
commits = []
for commit in self.repo.walk(self.repo.head.target, GIT_SORT_TIME):
commit_time = datetime.fromtimestamp(commit.commit_time)
if commit_time.date() == date:
time = commit_time.time().strftime('%H-%m-%S')
commits.append("%s-%s" % (time, commit.hex[:7]))
return commits
def readdir(self, path, fh):
commits = self._get_commits_by_date(self.date)
dir_entries = ['.', '..'] + commits
for entry in dir_entries:
yield entry
| Add minimal working version for HistoryView (to be refactored). | Add minimal working version for HistoryView (to be refactored).
| Python | apache-2.0 | ksmaheshkumar/gitfs,rowhit/gitfs,bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs | ---
+++
@@ -1,5 +1,67 @@
+from datetime import datetime
+from errno import ENOENT
+from stat import S_IFDIR
+from pygit2 import GIT_SORT_TIME
+
+from gitfs import FuseOSError
+from log import log
from .view import View
class HistoryView(View):
- pass
+ def getattr(self, path, fh=None):
+ '''
+ Returns a dictionary with keys identical to the stat C structure of
+ stat(2).
+
+ st_atime, st_mtime and st_ctime should be floats.
+
+ NOTE: There is an incombatibility between Linux and Mac OS X
+ concerning st_nlink of directories. Mac OS X counts all files inside
+ the directory, while Linux counts only the subdirectories.
+ '''
+
+ if path != '/':
+ raise FuseOSError(ENOENT)
+ return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
+
+
+ def opendir(self, path):
+ return 0
+
+ def releasedir(self, path, fi):
+ pass
+
+ def access(self, path, amode):
+ log.info('%s %s', path, amode)
+ return 0
+
+ def _get_commits_by_date(self, date):
+ """
+ Retrieves all the commits from a particular date.
+
+ :param date: date with the format: yyyy-mm-dd
+ :type date: str
+ :returns: a list containg the commits for that day. Each list item
+ will have the format: hh:mm:ss-<short_sha1>, where short_sha1 is
+ the short sha1 of the commit.
+ :rtype: list
+ """
+
+ date = datetime.strptime(date, '%Y-%m-%d').date()
+ commits = []
+ for commit in self.repo.walk(self.repo.head.target, GIT_SORT_TIME):
+ commit_time = datetime.fromtimestamp(commit.commit_time)
+ if commit_time.date() == date:
+ time = commit_time.time().strftime('%H-%m-%S')
+ commits.append("%s-%s" % (time, commit.hex[:7]))
+
+ return commits
+
+ def readdir(self, path, fh):
+ commits = self._get_commits_by_date(self.date)
+ dir_entries = ['.', '..'] + commits
+
+ for entry in dir_entries:
+ yield entry
+ |
267dfd75fa601b44b965d6df1d4440002f542638 | robert/__init__.py | robert/__init__.py | """
Entry point and the only view we have.
"""
from .article_utils import get_articles
from flask import Flask, render_template
from os import path
app = Flask(__name__)
config_path = path.abspath(path.join(path.dirname(__file__), 'config.py'))
app.config.from_pyfile(config_path)
@app.route('/')
def frontpage():
articles = get_articles()
context = {
'articles': articles,
'debug': app.config.get('DEBUG', False),
}
return render_template('home.html', **context)
@app.route('/about')
def about():
return render_template('about.html', title="Robert :: About")
| """
Entry point and the only view we have.
"""
from .article_utils import get_articles
from flask import Flask, render_template
from os import path
app = Flask(__name__)
config_path = path.abspath(path.join(path.dirname(__file__), 'config.py'))
app.config.from_pyfile(config_path)
@app.route('/')
def frontpage():
articles = get_articles()
context = {
'articles': articles,
'debug': app.config.get('DEBUG', False),
}
return render_template('home.html', **context)
@app.route('/about.html')
def about():
return render_template('about.html', title="Robert :: About")
| Change URL of about page -> /about.html | Change URL of about page -> /about.html
Since we can't control the web server serving this at GitHub Pages, we
can't setup proper URL rewriting to get rid of the extension. Ugly, but
keeps us from moving back to self-hosted site.
| Python | mit | thusoy/robertblag,thusoy/robertblag,thusoy/robertblag | ---
+++
@@ -23,7 +23,7 @@
return render_template('home.html', **context)
-@app.route('/about')
+@app.route('/about.html')
def about():
return render_template('about.html', title="Robert :: About")
|
4811de79c618134cec922e401ec447ef156ffc78 | scripts/pystart.py | scripts/pystart.py | import os,sys,re
from time import sleep
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran pystart and did import os,sys,re, sleep from time, and hexon/hexoff")
| import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran pystart and did import os,sys,re,sleep,pprint, and hexon/hexoff")
| Add pprint to default python includes | Add pprint to default python includes
| Python | mit | jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir | ---
+++
@@ -1,5 +1,6 @@
import os,sys,re
from time import sleep
+from pprint import pprint
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
@@ -8,4 +9,4 @@
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
-print ("Ran pystart and did import os,sys,re, sleep from time, and hexon/hexoff")
+print ("Ran pystart and did import os,sys,re,sleep,pprint, and hexon/hexoff") |
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a | deen/main.py | deen/main.py | import sys
import logging
import pathlib
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
| import sys
import logging
import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def main():
app = QApplication(sys.argv)
ex = Deen()
ex.setWindowIcon(QIcon(ICON))
LOGGER.addHandler(ex.log)
return app.exec_()
| Use os.path instead of pathlib | Use os.path instead of pathlib
| Python | apache-2.0 | takeshixx/deen,takeshixx/deen | ---
+++
@@ -1,13 +1,13 @@
import sys
import logging
-import pathlib
+import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
-ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
+ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
|
47530321c413976241e0d4e314f2a8e1532f38c9 | hackarena/utilities.py | hackarena/utilities.py | # -*- coding: utf-8 -*-
class Utilities(object):
def get_session_string(self, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
def get_session_middle_part(self, original_session_string):
return original_session_string.split(' ')[1]
def generate_random_name(self, original_session_string):
# Should get improved
return self.get_session_middle_part(original_session_string)
| # -*- coding: utf-8 -*-
class Utilities(object):
@classmethod
def get_session_string(cls, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
@classmethod
def get_session_middle_part(cls, original_session_string):
return original_session_string.split(' ')[1]
| Fix classmethods on utility class | Fix classmethods on utility class
| Python | mit | verekia/hackarena,verekia/hackarena,verekia/hackarena,verekia/hackarena | ---
+++
@@ -2,13 +2,12 @@
class Utilities(object):
- def get_session_string(self, original_session_string):
+
+ @classmethod
+ def get_session_string(cls, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
- def get_session_middle_part(self, original_session_string):
+ @classmethod
+ def get_session_middle_part(cls, original_session_string):
return original_session_string.split(' ')[1]
-
- def generate_random_name(self, original_session_string):
- # Should get improved
- return self.get_session_middle_part(original_session_string) |
b2155e167b559367bc24ba614f51360793951f12 | mythril/support/source_support.py | mythril/support/source_support.py | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
self.source_list = []
self.meta = meta
def get_source_from_contracts_list(self, contracts):
if contracts is None or len(contracts) == 0:
return
if isinstance(contracts[0], SolidityContract):
self.source_type = "solidity-file"
self.source_format = "text"
for contract in contracts:
self.source_list += [file.filename for file in contract.solidity_files]
elif isinstance(contracts[0], EVMContract):
self.source_format = "evm-byzantium-bytecode"
self.source_type = (
"raw-bytecode" if contracts[0].name == "MAIN" else "ethereum-address"
)
for contract in contracts:
self.source_list.append(contract.bytecode_hash)
else:
assert False # Fail hard
self.meta = ""
| from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
self.source_list = []
self.meta = meta
def get_source_from_contracts_list(self, contracts):
if contracts is None or len(contracts) == 0:
return
if isinstance(contracts[0], SolidityContract):
self.source_type = "solidity-file"
self.source_format = "text"
for contract in contracts:
self.source_list += [file.filename for file in contract.solidity_files]
elif isinstance(contracts[0], EVMContract):
self.source_format = "evm-byzantium-bytecode"
self.source_type = (
"raw-bytecode" if contracts[0].name == "MAIN" else "ethereum-address"
)
for contract in contracts:
self.source_list.append(contract.bytecode_hash)
else:
assert False # Fail hard
| Remove meta from source class (belongs to issue not source) | Remove meta from source class (belongs to issue not source)
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | ---
+++
@@ -29,4 +29,3 @@
else:
assert False # Fail hard
- self.meta = "" |
356891c9b0fbf1d57f67a22ca977d3d1016e5dc1 | numpy/array_api/_set_functions.py | numpy/array_api/_set_functions.py | from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
| from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
| Fix the array API unique() function | Fix the array API unique() function
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -12,4 +12,8 @@
See its docstring for more information.
"""
- return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
+ res = np.unique(x._array, return_counts=return_counts,
+ return_index=return_index, return_inverse=return_inverse)
+ if isinstance(res, tuple):
+ return tuple(Array._new(i) for i in res)
+ return Array._new(res) |
09d356f7b124368ac2ca80efa981d115ea847196 | django_ethereum_events/web3_service.py | django_ethereum_events/web3_service.py | from django.conf import settings
from web3 import Web3, RPCProvider
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given `RPCProvider`."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
rpc_provider (:obj:`Provider`, optional): Valid `web3` Provider instance.
"""
rpc_provider = kwargs.pop('rpc_provider', None)
if not rpc_provider:
rpc_provider = RPCProvider(
host=settings.ETHEREUM_NODE_HOST,
port=settings.ETHEREUM_NODE_PORT,
ssl=settings.ETHEREUM_NODE_SSL,
timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
)
self.web3 = Web3(rpc_provider)
super(Web3Service, self).__init__()
| from django.conf import settings
from web3 import Web3
try:
from web3 import HTTPProvider
RPCProvider = None
except ImportError:
from web3 import RPCProvider
HTTPProvider = None
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given `RPCProvider`."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
rpc_provider (:obj:`Provider`, optional): Valid `web3` Provider instance.
"""
rpc_provider = kwargs.pop('rpc_provider', None)
if not rpc_provider:
if HTTPProvider is not None:
uri = "{scheme}://{host}:{port}".format(
host=settings.ETHEREUM_NODE_HOST,
port=settings.ETHEREUM_NODE_PORT,
scheme="https" if settings.ETHEREUM_NODE_SSL else "http",
)
rpc_provider = HTTPProvider(
endpoint_uri=uri,
timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
)
elif RPCProvider is not None:
rpc_provider = RPCProvider(
host=settings.ETHEREUM_NODE_HOST,
port=settings.ETHEREUM_NODE_PORT,
ssl=settings.ETHEREUM_NODE_SSL,
timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
)
else:
raise ValueError("Cannot instantiate any RPC provider")
self.web3 = Web3(rpc_provider)
super(Web3Service, self).__init__()
| Support for Web3 4.0beta: HTTPProvider | Support for Web3 4.0beta: HTTPProvider
In Web3 3.16 the class is called RPCProvider, but in the
upcoming 4.0 series it's replaced with HTTPProvider.
This commit ensures both versions are supported in this regard.
| Python | mit | artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events | ---
+++
@@ -1,5 +1,11 @@
from django.conf import settings
-from web3 import Web3, RPCProvider
+from web3 import Web3
+try:
+ from web3 import HTTPProvider
+ RPCProvider = None
+except ImportError:
+ from web3 import RPCProvider
+ HTTPProvider = None
from .singleton import Singleton
@@ -15,11 +21,24 @@
"""
rpc_provider = kwargs.pop('rpc_provider', None)
if not rpc_provider:
- rpc_provider = RPCProvider(
- host=settings.ETHEREUM_NODE_HOST,
- port=settings.ETHEREUM_NODE_PORT,
- ssl=settings.ETHEREUM_NODE_SSL,
- timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
- )
+ if HTTPProvider is not None:
+ uri = "{scheme}://{host}:{port}".format(
+ host=settings.ETHEREUM_NODE_HOST,
+ port=settings.ETHEREUM_NODE_PORT,
+ scheme="https" if settings.ETHEREUM_NODE_SSL else "http",
+ )
+ rpc_provider = HTTPProvider(
+ endpoint_uri=uri,
+ timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
+ )
+ elif RPCProvider is not None:
+ rpc_provider = RPCProvider(
+ host=settings.ETHEREUM_NODE_HOST,
+ port=settings.ETHEREUM_NODE_PORT,
+ ssl=settings.ETHEREUM_NODE_SSL,
+ timeout=getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
+ )
+ else:
+ raise ValueError("Cannot instantiate any RPC provider")
self.web3 = Web3(rpc_provider)
super(Web3Service, self).__init__() |
3039b00e761f02eb0586dad51049377a31329491 | reggae/reflect.py | reggae/reflect.py | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
return builds[0]
def get_default_options(module):
opts = [v for n, v in getmembers(module) if isinstance(v, DefaultOptions)]
assert len(opts) == 1 or len(opts) == 0
return opts[0] if len(opts) else None
def get_dependencies(module):
from modulefinder import ModuleFinder
import os
finder = ModuleFinder()
finder.run_script(module)
all_module_paths = [m.__file__ for m in finder.modules.values()]
def is_in_same_path(p):
return p and os.path.dirname(p).startswith(os.path.dirname(module))
return [x for x in all_module_paths if is_in_same_path(x) and x != module]
| from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
return builds[0]
def get_default_options(module):
opts = [v for n, v in getmembers(module) if isinstance(v, DefaultOptions)]
assert len(opts) == 1 or len(opts) == 0
return opts[0] if len(opts) else None
def get_dependencies(module):
from modulefinder import ModuleFinder
import os
finder = ModuleFinder()
finder.run_script(module)
all_module_paths = [os.path.abspath(m.__file__) for
m in finder.modules.values() if m.__file__ is not None]
def is_in_same_path(p):
return p and os.path.dirname(p).startswith(os.path.dirname(module))
return [x for x in all_module_paths if is_in_same_path(x) and x != module]
| Use absolute paths for dependencies | Use absolute paths for dependencies
| Python | bsd-3-clause | atilaneves/reggae-python | ---
+++
@@ -24,7 +24,8 @@
finder = ModuleFinder()
finder.run_script(module)
- all_module_paths = [m.__file__ for m in finder.modules.values()]
+ all_module_paths = [os.path.abspath(m.__file__) for
+ m in finder.modules.values() if m.__file__ is not None]
def is_in_same_path(p):
return p and os.path.dirname(p).startswith(os.path.dirname(module)) |
827bc2751add4905b3fca57568c879e7cb8e70a0 | django_tml/inline_translations/middleware.py | django_tml/inline_translations/middleware.py | from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
if request.get_signed_cookie(self.cookie_name):
# inline tranlation turned on in cookies:
_.turn_on()
return None
except KeyError:
# cookie is not set
pass
# Turn off by default:
_.turn_off()
return None
@property
def cookie_name(self):
return settings.TML.get('inline_translation_cookie', 'inline_translations')
def process_response(self, request, response):
""" Set/reset cookie for inline tranlations """
if _.save:
response.set_signed_cookie(self.cookie_name, _.enabled)
_.save = False # reset save flag
_.turn_off() # turn off tranlation after request executed
return response
| # encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
if request.get_signed_cookie(self.cookie_name):
# inline tranlation turned on in cookies:
_.turn_on()
return None
except KeyError:
# cookie is not set
pass
# Turn off by default:
_.turn_off()
return None
@property
def cookie_name(self):
return settings.TML.get('inline_translation_cookie', 'inline_translations')
def process_response(self, request, response):
""" Set/reset cookie for inline tranlations """
if _.save:
if _.enabled:
response.set_signed_cookie(self.cookie_name, True)
else:
response.delete_cookie(self.cookie_name)
_.save = False # reset save flag
_.turn_off() # turn off tranlation after request executed
return response
| Delete cookie on reset inline mode | Delete cookie on reset inline mode
| Python | mit | translationexchange/tml-python,translationexchange/tml-python | ---
+++
@@ -1,3 +1,4 @@
+# encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
@@ -25,7 +26,10 @@
def process_response(self, request, response):
""" Set/reset cookie for inline tranlations """
if _.save:
- response.set_signed_cookie(self.cookie_name, _.enabled)
+ if _.enabled:
+ response.set_signed_cookie(self.cookie_name, True)
+ else:
+ response.delete_cookie(self.cookie_name)
_.save = False # reset save flag
_.turn_off() # turn off tranlation after request executed
return response |
8284a8e61ed6c4e6b3402c55d2247f7e468a6872 | tests/test_integrations/test_get_a_token.py | tests/test_integrations/test_get_a_token.py | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
self.client_id = os.getenv('CLIENT_ID')
self.secret_id = os.getenv('CLIENT_SECRET')
def test_get_a_token(self):
"""
Test getting a 24 hour token from the oauth token endpoint
"""
token = get_token(self.domain, self.client_id, self.secret_id)
assert token['access_token']
| # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
@unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
self.client_id = os.getenv('CLIENT_ID')
self.secret_id = os.getenv('CLIENT_SECRET')
def test_get_a_token(self):
"""
Test getting a 24 hour token from the oauth token endpoint
"""
token = get_token(self.domain, self.client_id, self.secret_id)
assert token['access_token']
| Add unittest skip for CI | Add unittest skip for CI
| Python | isc | bretth/auth0plus | ---
+++
@@ -11,6 +11,7 @@
class TestGetAToken(unittest.TestCase):
+ @unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret |
08bd3801c0ecc3d4ef9720094bcbf67acaf1b67b | Instanssi/admin_base/views.py | Instanssi/admin_base/views.py | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/files/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
# Get redirect path
if 'r' in request.GET:
r = request.GET['r']
if r[0] != "/":
r = "/control/"
else:
r = "/control/"
# Set session variable
try:
request.session['m_event_id'] = int(event_id)
except:
raise Http404
# Redirect
return HttpResponseRedirect(r) | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
# Get redirect path
if 'r' in request.GET:
r = request.GET['r']
if r[0] != "/":
r = "/control/"
else:
r = "/control/"
# Set session variable
try:
request.session['m_event_id'] = int(event_id)
except:
raise Http404
# Redirect
return HttpResponseRedirect(r) | Fix default refirect when url is /control/ | admin_base: Fix default refirect when url is /control/
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -5,7 +5,7 @@
@login_required(login_url='/control/auth/login/')
def index(request):
- return HttpResponseRedirect("/control/files/")
+ return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id): |
557d536aebe40bb115d2f0056aaaddf450ccc157 | test/params/test_arguments_parsing.py | test/params/test_arguments_parsing.py | import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args("")
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argument.oauth_tokens, is_('data/tokens.dat'))
| import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args([])
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argument.oauth_tokens, is_('data/tokens.dat'))
def test_parse_secret_and_token_params(self):
argument = parse_args(['--client-secrets', '/var/google/secrets.json',
'--oauth-tokens', '/var/google/token.dat'])
assert_that(argument.client_secrets, is_('/var/google/secrets.json'))
assert_that(argument.oauth_tokens, is_('/var/google/token.dat'))
| Test for parsing argument parameters | Test for parsing argument parameters
| Python | mit | gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer | ---
+++
@@ -6,7 +6,14 @@
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
- argument = parse_args("")
+ argument = parse_args([])
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argument.oauth_tokens, is_('data/tokens.dat'))
+
+ def test_parse_secret_and_token_params(self):
+ argument = parse_args(['--client-secrets', '/var/google/secrets.json',
+ '--oauth-tokens', '/var/google/token.dat'])
+
+ assert_that(argument.client_secrets, is_('/var/google/secrets.json'))
+ assert_that(argument.oauth_tokens, is_('/var/google/token.dat')) |
07b81828c100879795b629185bcc68bd69d30748 | setup.py | setup.py | from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
author_email="toshio@fedoraproject.org",
maintainer="Toshio Kuratomi",
maintainer_email="toshio@fedoraproject.org",
url="https://github.com/abadger/pubmarine",
license="GNU Affero General Public License v3 or later (AGPLv3+)",
keywords='game trading',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console :: Curses',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Games/Entertainment',
'Topic :: Games/Entertainment :: Simulation',
],
packages=['magnate', 'magnate.ui'],
scripts=['bin/magnate'],
install_requires=['ConfigObj', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'],
)
| from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
author_email="toshio@fedoraproject.org",
maintainer="Toshio Kuratomi",
maintainer_email="toshio@fedoraproject.org",
url="https://github.com/abadger/pubmarine",
license="GNU Affero General Public License v3 or later (AGPLv3+)",
keywords='game trading',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console :: Curses',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Games/Entertainment',
'Topic :: Games/Entertainment :: Simulation',
],
packages=['magnate', 'magnate.ui'],
scripts=['bin/magnate'],
install_requires=['ConfigObj', 'PyYaml', 'attrs', 'jsonschema', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'],
)
| Add more libraries that are used at runtime | Add more libraries that are used at runtime
| Python | agpl-3.0 | abadger/stellarmagnate | ---
+++
@@ -28,5 +28,5 @@
],
packages=['magnate', 'magnate.ui'],
scripts=['bin/magnate'],
- install_requires=['ConfigObj', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'],
+ install_requires=['ConfigObj', 'PyYaml', 'attrs', 'jsonschema', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'],
) |
98ca83d54eab97c81c5df86b415eb9ff0b201902 | src/__init__.py | src/__init__.py | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, port))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
| import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address.split(':')[0] != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, int(port)))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
| Fix starting inet client when should use unix socket instead. Fix port to be int. | Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg | ---
+++
@@ -20,7 +20,7 @@
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
- address != gethostbyname(gethostname()):
+ address.split(':')[0] != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
@@ -29,7 +29,7 @@
port = DEFAULT_EPG_PORT
# create socket, pass it to client
- _client = GuideClient((host, port))
+ _client = GuideClient((host, int(port)))
else:
# EPG is local, only use unix socket |
d90544ad2051e92a63da45d7270c7f66545edb82 | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| Migrate correctly from scratch also | Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.
| Python | agpl-3.0 | Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform | ---
+++
@@ -1,8 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-from django.db import migrations, models, OperationalError, connection
-from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
+from django.db import migrations, models, connection
+
+def table_description():
+ """Handle Mysql/Pg vs Sqlite"""
+ # django's mysql/pg introspection.get_table_description tries to select *
+ # from table and fails during initial migrations from scratch.
+ # sqlite does not have this failure, so we can use the API.
+ # For not-sqlite, query information-schema directly with code lifted
+ # from the internals of django.db.backends.mysql.introspection.py
+
+ if connection.vendor == 'sqlite':
+ fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
+ return [f.name for f in fields]
+ else:
+ cursor = connection.cursor()
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
+ rows = cursor.fetchall()
+ return [r[0] for r in rows]
class Migration(migrations.Migration):
@@ -11,15 +30,17 @@
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
- # An original version of 0008 removed the facebook_url field
- # We need to handle the case where our noop 0008 ran AND the case
- # where the original 0008 ran. We do that by using Django's introspection
- # API to query INFORMATION_SCHEMA. _meta is unavailable as the
- # column has already been removed from the model.
- fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
+ # An original version of 0008 removed the facebook_url field We need to
+ # handle the case where our noop 0008 ran AND the case where the original
+ # 0008 ran. We do that by using the standard information_schema to find out
+ # what columns exist. _meta is unavailable as the column has already been
+ # removed from the model
operations = []
+ fields = table_description()
- if not any(f.name == 'facebook_url' for f in fields):
+ # during a migration from scratch, fields will be empty, but we do not want to add
+ # an additional facebook_url
+ if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url', |
9c4bdeae651dd38801b980b4d06edcb8872cd5fa | Lib/test/test_gzip.py | Lib/test/test_gzip.py |
import sys, os
import gzip, tempfile
filename = tempfile.mktemp()
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"""
data2 = """/* zlibmodule.c -- gzip-compatible data compression */
/* See http://www.cdrom.com/pub/infozip/zlib/ */
/* See http://www.winimage.com/zLibDll for Windows */
"""
f = gzip.GzipFile(filename, 'w') ; f.write(data1) ; f.close()
f = gzip.GzipFile(filename, 'r') ; d = f.read() ; f.close()
assert d == data1
# Append to the previous file
f = gzip.GzipFile(filename, 'a') ; f.write(data2) ; f.close()
f = gzip.GzipFile(filename, 'r') ; d = f.read() ; f.close()
assert d == data1+data2
os.unlink( filename )
|
import sys, os
import gzip, tempfile
filename = tempfile.mktemp()
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"""
data2 = """/* zlibmodule.c -- gzip-compatible data compression */
/* See http://www.cdrom.com/pub/infozip/zlib/ */
/* See http://www.winimage.com/zLibDll for Windows */
"""
f = gzip.GzipFile(filename, 'wb') ; f.write(data1) ; f.close()
f = gzip.GzipFile(filename, 'rb') ; d = f.read() ; f.close()
assert d == data1
# Append to the previous file
f = gzip.GzipFile(filename, 'ab') ; f.write(data2) ; f.close()
f = gzip.GzipFile(filename, 'rb') ; d = f.read() ; f.close()
assert d == data1+data2
os.unlink( filename )
| Use binary mode for all gzip files we open. | Use binary mode for all gzip files we open.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -16,15 +16,15 @@
/* See http://www.winimage.com/zLibDll for Windows */
"""
-f = gzip.GzipFile(filename, 'w') ; f.write(data1) ; f.close()
+f = gzip.GzipFile(filename, 'wb') ; f.write(data1) ; f.close()
-f = gzip.GzipFile(filename, 'r') ; d = f.read() ; f.close()
+f = gzip.GzipFile(filename, 'rb') ; d = f.read() ; f.close()
assert d == data1
# Append to the previous file
-f = gzip.GzipFile(filename, 'a') ; f.write(data2) ; f.close()
+f = gzip.GzipFile(filename, 'ab') ; f.write(data2) ; f.close()
-f = gzip.GzipFile(filename, 'r') ; d = f.read() ; f.close()
+f = gzip.GzipFile(filename, 'rb') ; d = f.read() ; f.close()
assert d == data1+data2
os.unlink( filename ) |
577da237d219aacd4413cb789fb08c76ca218223 | ws/plugins/accuweather/__init__.py | ws/plugins/accuweather/__init__.py |
import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
print(mydir)
lookupmatrix = pickle.load(open( \
mydir +'/accuweather_location_codes.dump','rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
if type(city) != str:
raise(bad.Type("The input city " +str(city) +" wasn't of type string"))
index = lookuplist[1].index(city)
accuweather_index = lookuplist[0][index]
url = 'http://realtek.accu-weather.com/widget/realtek/weather-data.asp' \
+ '?location=cityId:' \
+ str(accuweather_index)
return url | import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
if type(city) != str:
raise(bad.Type("The input city " +str(city) +" wasn't of type string"))
index = lookuplist[1].index(city)
accuweather_index = lookuplist[0][index]
url = 'http://realtek.accu-weather.com/widget/realtek/weather-data.asp' \
+ '?location=cityId:' \
+ str(accuweather_index)
return url
| Use os.path.join() to join paths | Use os.path.join() to join paths
| Python | bsd-3-clause | BCCN-Prog/webscraping | ---
+++
@@ -1,4 +1,3 @@
-
import numpy as np
import pickle
import os
@@ -6,23 +5,17 @@
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
-
-print(mydir)
-
-lookupmatrix = pickle.load(open( \
- mydir +'/accuweather_location_codes.dump','rb'))
-
+lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
if type(city) != str:
raise(bad.Type("The input city " +str(city) +" wasn't of type string"))
-
-
+
index = lookuplist[1].index(city)
accuweather_index = lookuplist[0][index]
-
+
url = 'http://realtek.accu-weather.com/widget/realtek/weather-data.asp' \
+ '?location=cityId:' \
+ str(accuweather_index) |
d84e37089a287fd151824f0b48624f243fdded09 | d1lod/tests/test_dataone.py | d1lod/tests/test_dataone.py | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod.dataone import extractIdentifierFromFullURL as extract
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert extract('asdf') is None
assert extract(1) is None
assert extract('1') is None
assert extract('http://google.com') is None
# Extracts the right thing
assert extract('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
assert extract('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30'
| """test_dataone.py
Test the DataOne utility library.
"""
from d1lod import dataone
def test_parsing_resource_map():
pid = 'resourceMap_df35d.3.2'
aggd_pids = dataone.getAggregatedIdentifiers(pid)
assert len(aggd_pids) == 7
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert dataone.extractIdentifierFromFullURL('asdf') is None
assert dataone.extractIdentifierFromFullURL(1) is None
assert dataone.extractIdentifierFromFullURL('1') is None
assert dataone.extractIdentifierFromFullURL('http://google.com') is None
# Extracts the right thing
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30'
| Change imports in dataone test and add test for resource map parsing | Change imports in dataone test and add test for resource map parsing
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod | ---
+++
@@ -3,18 +3,25 @@
Test the DataOne utility library.
"""
-from d1lod.dataone import extractIdentifierFromFullURL as extract
+from d1lod import dataone
+
+def test_parsing_resource_map():
+ pid = 'resourceMap_df35d.3.2'
+
+ aggd_pids = dataone.getAggregatedIdentifiers(pid)
+
+ assert len(aggd_pids) == 7
def test_extracting_identifiers_from_urls():
# Returns None when it should
- assert extract('asdf') is None
- assert extract(1) is None
- assert extract('1') is None
- assert extract('http://google.com') is None
+ assert dataone.extractIdentifierFromFullURL('asdf') is None
+ assert dataone.extractIdentifierFromFullURL(1) is None
+ assert dataone.extractIdentifierFromFullURL('1') is None
+ assert dataone.extractIdentifierFromFullURL('http://google.com') is None
# Extracts the right thing
- assert extract('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
- assert extract('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
- assert extract('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
- assert extract('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
- assert extract('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30'
+ assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
+ assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
+ assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
+ assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
+ assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30' |
fd4f6fb2eef3fd24d427836023918103bac08ada | acme/acme/__init__.py | acme/acme/__init__.py | """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://github.com/ietf-wg-acme/acme/
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://ietf-wg-acme.github.io/acme
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| Use GH pages for IETF spec repo link | Use GH pages for IETF spec repo link
| Python | apache-2.0 | mitnk/letsencrypt,mitnk/letsencrypt,twstrike/le_for_patching,DavidGarciaCat/letsencrypt,kuba/letsencrypt,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,jsha/letsencrypt,thanatos/lets-encrypt-preview,TheBoegl/letsencrypt,kuba/letsencrypt,brentdax/letsencrypt,wteiken/letsencrypt,brentdax/letsencrypt,jtl999/certbot,VladimirTyrin/letsencrypt,dietsche/letsencrypt,dietsche/letsencrypt,stweil/letsencrypt,TheBoegl/letsencrypt,wteiken/letsencrypt,thanatos/lets-encrypt-preview,jtl999/certbot,stweil/letsencrypt,letsencrypt/letsencrypt,bsmr-misc-forks/letsencrypt,VladimirTyrin/letsencrypt,lmcro/letsencrypt,twstrike/le_for_patching,lmcro/letsencrypt,bsmr-misc-forks/letsencrypt,jsha/letsencrypt | ---
+++
@@ -3,10 +3,10 @@
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
-.. _`ACME protocol`: https://github.com/ietf-wg-acme/acme/
+
+.. _`ACME protocol`: https://ietf-wg-acme.github.io/acme
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
-
""" |
091b1f5eb7c999a8d9b2448c1ca75941d2efb926 | opentaxii/auth/sqldb/models.py | opentaxii/auth/sqldb/models.py | import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integer, primary_key=True)
username = Column(String(MAX_STR_LEN), unique=True)
password_hash = Column(String(MAX_STR_LEN))
def set_password(self, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt())
def is_password_valid(self, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
hashed = self.password_hash.encode('utf-8')
return bcrypt.hashpw(password, hashed) == hashed
| import hmac
import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integer, primary_key=True)
username = Column(String(MAX_STR_LEN), unique=True)
password_hash = Column(String(MAX_STR_LEN))
def set_password(self, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt())
def is_password_valid(self, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
hashed = self.password_hash.encode('utf-8')
return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)
| Use constant time string comparison for password checking | Use constant time string comparison for password checking
| Python | bsd-3-clause | EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII | ---
+++
@@ -1,3 +1,5 @@
+import hmac
+
import bcrypt
from sqlalchemy.schema import Column
@@ -10,6 +12,7 @@
MAX_STR_LEN = 256
+
class Account(Base):
__tablename__ = 'accounts'
@@ -18,7 +21,6 @@
username = Column(String(MAX_STR_LEN), unique=True)
password_hash = Column(String(MAX_STR_LEN))
-
def set_password(self, password):
if isinstance(password, unicode):
@@ -29,6 +31,4 @@
if isinstance(password, unicode):
password = password.encode('utf-8')
hashed = self.password_hash.encode('utf-8')
- return bcrypt.hashpw(password, hashed) == hashed
-
-
+ return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed) |
2bc2f7e077ad46903688aababa51d37853746231 | bmi_ilamb/bmi_ilamb.py | bmi_ilamb/bmi_ilamb.py | #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB v2'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
| #! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
| Change component name to 'ILAMB' | Change component name to 'ILAMB'
This currently conflicts with the component name for the NCL
version of ILAMB; however, I'll change its name to 'ILAMBv1'.
The current version of ILAMB should take the correct name.
| Python | mit | permamodel/bmi-ilamb | ---
+++
@@ -16,7 +16,7 @@
return [self._command] + (self._args or [])
def get_component_name(self):
- return 'ILAMB v2'
+ return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg'] |
2faca854148a0661946ac944e4b8aa0684c773f6 | request.py | request.py | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
def getParamAsInt(request, key, default):
"""
Safely pulls a key from the request and converts it to an integer
@param request: The HttpRequest object
@param key: The key from request.args containing the desired value
@param default: The value to return if the key does not exist
@return: The value matching the key, or if it does not exist, the default value provided.
"""
return int(request.args.get(key)) if key in request.args and request.args[key].isdigit() else default | Add get param as int | Add get param as int
| Python | bsd-3-clause | Sendhub/flashk_util | ---
+++
@@ -21,3 +21,14 @@
else:
return func(*args, **kwargs)
return decorated_function
+
+
+def getParamAsInt(request, key, default):
+ """
+ Safely pulls a key from the request and converts it to an integer
+ @param request: The HttpRequest object
+ @param key: The key from request.args containing the desired value
+ @param default: The value to return if the key does not exist
+ @return: The value matching the key, or if it does not exist, the default value provided.
+ """
+ return int(request.args.get(key)) if key in request.args and request.args[key].isdigit() else default |
6c351939243f758119ed91de299d6d37dc305359 | application/main/routes/__init__.py | application/main/routes/__init__.py | # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate),
(r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass),
]
| # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate),
(r'/changes/for_class/(.+)', ChangesForClass),
]
| Expand class name routing target | Expand class name routing target
| Python | bsd-3-clause | p22co/edaemon,paulsnar/edaemon,p22co/edaemon,p22co/edaemon,paulsnar/edaemon,paulsnar/edaemon | ---
+++
@@ -9,5 +9,5 @@
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate),
- (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass),
+ (r'/changes/for_class/(.+)', ChangesForClass),
] |
0bbe6a915f8c289a9960f3cba9354955a19854f4 | inpassing/pass_util.py | inpassing/pass_util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
elif not verified:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.owner_id == user_id).all()
def query_org_passes(session, org_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time != None)
).all()
elif not verified:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.org_id == org_id).all()
| # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.owner_id == user_id).all()
def query_org_passes(session, org_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time != None)
).all()
elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time == None)
).all()
else:
# All passes
return session.query(Pass).filter(Pass.org_id == org_id).all()
| Fix bug in user pass code | Fix bug in user pass code
The functions to query user and org passes return non-verified passes when
verified=None, which was not intended.
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend | ---
+++
@@ -12,7 +12,7 @@
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time != None)
).all()
- elif not verified:
+ elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id, Pass.assigned_time == None)
@@ -28,7 +28,7 @@
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time != None)
).all()
- elif not verified:
+ elif not verified and verified is not None:
# Only non-verified passes
return session.query(Pass).filter(
and_(Pass.org_id == org_id, Pass.assigned_time == None) |
7439a2c4b73707dc301117d3d8d368cfc31bc774 | akanda/rug/api/keystone.py | akanda/rug/api/keystone.py | # Copyright (c) 2015 Akanda, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient import auth as ksauth
from keystoneclient import session as kssession
from oslo_config import cfg
CONF = cfg.CONF
CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token')
class KeystoneSession(object):
def __init__(self):
self._session = None
self.region_name = CONF.auth_region
@property
def session(self):
if not self._session:
# Construct a Keystone session for configured auth_plugin
# and credentials
auth_plugin = ksauth.load_from_conf_options(
cfg.CONF, 'keystone_authtoken')
self._session = kssession.Session(auth=auth_plugin)
return self._session
| # Copyright (c) 2015 Akanda, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient import auth as ksauth
from keystoneclient import session as kssession
from oslo_config import cfg
CONF = cfg.CONF
class KeystoneSession(object):
def __init__(self):
self._session = None
self.region_name = CONF.auth_region
ksauth.register_conf_options(CONF, 'keystone_authtoken')
@property
def session(self):
if not self._session:
# Construct a Keystone session for configured auth_plugin
# and credentials
auth_plugin = ksauth.load_from_conf_options(
cfg.CONF, 'keystone_authtoken')
self._session = kssession.Session(auth=auth_plugin)
return self._session
| Use KSC auth's register_conf_options instead of oslo.cfg import | Use KSC auth's register_conf_options instead of oslo.cfg import
A newer keystoneclient is not happy with simply using oslo_config to
import the config group. Instead, use register_conf_options()
from keystoneclient.auth.
Change-Id: I798dad7ad5bd90362e1fa10c2eecb3e1d5bade71
| Python | apache-2.0 | openstack/akanda-rug,openstack/akanda-rug,stackforge/akanda-rug,stackforge/akanda-rug | ---
+++
@@ -19,13 +19,13 @@
CONF = cfg.CONF
-CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token')
class KeystoneSession(object):
def __init__(self):
self._session = None
self.region_name = CONF.auth_region
+ ksauth.register_conf_options(CONF, 'keystone_authtoken')
@property
def session(self): |
9d0ba593ae5f7e23a1bd32573ad8e80dac6eb845 | stalkr/cache.py | stalkr/cache.py | import os
import requests
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
self.directory = directory
if not os.path.isdir(directory):
os.mkdir(directory)
def get(self, key):
for extension in self.extensions:
filename = key + "." + extension
path = os.path.join(self.directory, filename)
if os.path.isfile(path):
return path
return None
def set(self, key, url):
res = requests.get(url)
if res.status_code == 200:
_, extension = os.path.splitext(url)
filename = key + extension
path = os.path.join(self.directory, filename)
with open(path, "wb") as file:
file.write(res.content)
return True
else:
return False
| import os
import requests
class UnknownExtensionException:
def __init__(self, extension):
self.extension = extension
def __str__(self):
return repr("{0}: unknown extension".format(self.extension))
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
self.directory = directory
if not os.path.isdir(directory):
os.mkdir(directory)
def get(self, key):
for extension in self.extensions:
filename = key + "." + extension
path = os.path.join(self.directory, filename)
if os.path.isfile(path):
return path
return None
def set(self, key, url):
res = requests.get(url)
if res.status_code == 200:
_, extension = os.path.splitext(url)
if extension[1:] not in self.extensions:
raise UnknownExtensionException(extension[1:])
filename = key + extension
path = os.path.join(self.directory, filename)
with open(path, "wb") as file:
file.write(res.content)
return True
else:
return False
| Raise exception if the image file extension is unknown | Raise exception if the image file extension is unknown
| Python | isc | helderm/stalkr,helderm/stalkr,helderm/stalkr,helderm/stalkr | ---
+++
@@ -1,5 +1,12 @@
import os
import requests
+
+class UnknownExtensionException:
+ def __init__(self, extension):
+ self.extension = extension
+
+ def __str__(self):
+ return repr("{0}: unknown extension".format(self.extension))
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
@@ -21,6 +28,8 @@
res = requests.get(url)
if res.status_code == 200:
_, extension = os.path.splitext(url)
+ if extension[1:] not in self.extensions:
+ raise UnknownExtensionException(extension[1:])
filename = key + extension
path = os.path.join(self.directory, filename)
with open(path, "wb") as file: |
5c5956dc11bbe9e65f6b9403cf0dbe5470eab257 | iterm2_tools/images.py | iterm2_tools/images.py | from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(image_bytes(f.read(), filename=fn))
| from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in the terminal.
If filename=None the filename defaults to "Unnamed file".
"""
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(image_bytes(f.read(), filename=fn))
| Add a docstring to image_bytes | Add a docstring to image_bytes
| Python | mit | asmeurer/iterm2-tools | ---
+++
@@ -8,6 +8,12 @@
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
+ """
+ Display the image given by the bytes b in the terminal.
+
+ If filename=None the filename defaults to "Unnamed file".
+
+ """
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline, |
eba55b9b4eb59af9a56965086aae240c6615ba1f | author/urls.py | author/urls.py | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.contrib.auth.views import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from author import views
def author_required(function=None, login_url=None):
author_permission = Permission(
content_type=ContentType.objects.get(app_label='game',
model='task'),
codename='add_task',
)
actual_decorator = permission_required(author_permission,
login_url=login_url)
if function is None:
return actual_decorator(login_required)
return actual_decorator(login_required(function))
urlpatterns = patterns(
'',
url(r'^$', RedirectView.as_view(url=reverse_lazy('author-login'),
permanent=False)),
url(r'^login/$',
login,
{'template_name': 'author/login.html'},
name='author-login'),
url(r'^panel/$',
author_required(function=views.PanelView.as_view(),
login_url=reverse_lazy('author-login')),
name='panel'),
)
| from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from author import views
def author_required(function=None, login_url=None):
actual_decorator = permission_required('game.add_task',
login_url=login_url)
if function is None:
return actual_decorator(login_required)
return actual_decorator(login_required(function))
urlpatterns = patterns(
'',
url(r'^$', RedirectView.as_view(url=reverse_lazy('author-login'),
permanent=False)),
url(r'^login/$',
login,
{'template_name': 'author/login.html'},
name='author-login'),
url(r'^panel/$',
author_required(function=views.PanelView.as_view(),
login_url=reverse_lazy('author-login')),
name='panel'),
)
| Fix bug with author permission check | Fix bug with author permission check
| Python | bsd-3-clause | stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3 | ---
+++
@@ -2,8 +2,6 @@
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
-from django.contrib.contenttypes.models import ContentType
-from django.contrib.auth.models import Permission
from django.contrib.auth.views import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
@@ -12,12 +10,7 @@
def author_required(function=None, login_url=None):
- author_permission = Permission(
- content_type=ContentType.objects.get(app_label='game',
- model='task'),
- codename='add_task',
- )
- actual_decorator = permission_required(author_permission,
+ actual_decorator = permission_required('game.add_task',
login_url=login_url)
if function is None:
return actual_decorator(login_required) |
ca9c4f7c3f1f7690395948b9dcdfd917cc33bfa8 | array/sudoku-check.py | array/sudoku-check.py | # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
j += 1
i += 1
return True
def check_columns(grid):
column = 0
length = len(grid)
while column < length:
row = 0
ref_check = {}
while row < length:
if grid[row][column] != '.' and grid[row][column] in ref_check:
return False
else:
ref_check[grid[row][column]] = 1
row += 1
column += 1
return True
def create_sub_grid(grid):
ref_check = {}
for square in grid:
if square != '.' and square in ref_check:
return False
else:
ref_check[square] = 1
return True
| # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
j += 1
i += 1
return True
def check_columns(grid):
column = 0
length = len(grid)
while column < length:
row = 0
ref_check = {}
while row < length:
if grid[row][column] != '.' and grid[row][column] in ref_check:
return False
else:
ref_check[grid[row][column]] = 1
row += 1
column += 1
return True
def create_sub_grid(grid):
ref_check = {}
for square in grid:
if square != '.' and square in ref_check:
return False
else:
ref_check[square] = 1
return True
def check_sub_grid(grid):
sub_grid = []
for row in range(0, 9, 3):
for i in range(0, 9, 3):
a = []
for j in range(row, row + 3):
for column in range(i, i + 3):
a.append(grid[j][column])
sub_grid.append(a)
for row in sub_grid:
if not create_sub_grid(row):
return False
return True
| Add create sub grid method | Add create sub grid method
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -37,3 +37,18 @@
else:
ref_check[square] = 1
return True
+
+def check_sub_grid(grid):
+ sub_grid = []
+ for row in range(0, 9, 3):
+ for i in range(0, 9, 3):
+ a = []
+ for j in range(row, row + 3):
+ for column in range(i, i + 3):
+ a.append(grid[j][column])
+ sub_grid.append(a)
+
+ for row in sub_grid:
+ if not create_sub_grid(row):
+ return False
+ return True |
b1dfc01eadd9420d5e20c5f3437e04505d77df13 | autocloud/__init__.py | autocloud/__init__.py | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT)
if not os.path.exists(name):
name = '/etc/autocloud/autocloud.cfg'
config.read(name)
KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url')
BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url')
HOST = config.get('autocloud', 'host') or '127.0.0.1'
PORT = int(config.get('autocloud', 'port')) or 5000
DEBUG = config.getboolean('autocloud', 'debug')
SQLALCHEMY_URI = config.get('sqlalchemy', 'uri')
VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
| # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
raise Exception('Please add a proper cofig file under /etc/autocloud/')
config.read(name)
KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url')
BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url')
HOST = config.get('autocloud', 'host') or '127.0.0.1'
PORT = int(config.get('autocloud', 'port')) or 5000
DEBUG = config.getboolean('autocloud', 'debug')
SQLALCHEMY_URI = config.get('sqlalchemy', 'uri')
VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
| Read the config file only from /etc/autocloud/autocloud.cfg file. | Read the config file only from /etc/autocloud/autocloud.cfg file.
| Python | agpl-3.0 | maxamillion/autocloud,maxamillion/autocloud,kushaldas/autocloud,maxamillion/autocloud,maxamillion/autocloud,kushaldas/autocloud,kushaldas/autocloud,kushaldas/autocloud | ---
+++
@@ -5,12 +5,9 @@
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
-config = ConfigParser.RawConfigParser()
-name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
- PROJECT_ROOT=PROJECT_ROOT)
-
+name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
- name = '/etc/autocloud/autocloud.cfg'
+ raise Exception('Please add a proper cofig file under /etc/autocloud/')
config.read(name)
|
dba22abf151ddee20aeb886e2bca6401a17d7cea | properties/spatial.py | properties/spatial.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
"""
_sphinx_prefix = 'properties.spatial'
@property
def default(self):
return getattr(self, '_default', [] if self.repeated else None)
@default.setter
def default(self, value):
self._default = self.validator(None, value).copy()
def validator(self, instance, value):
"""return a Vector based on input if input is valid"""
if isinstance(value, vmath.Vector):
return value
if isinstance(value, six.string_types):
if value.upper() == 'X':
return vmath.Vector(1, 0, 0)
if value.upper() == 'Y':
return vmath.Vector(0, 1, 0)
if value.upper() == 'Z':
return vmath.Vector(0, 0, 1)
try:
return vmath.Vector(value)
except Exception:
raise ValueError('{} must be a Vector'.format(self.name))
def from_json(self, value):
return vmath.Vector(*value)
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
"""
_sphinx_prefix = 'properties.spatial'
@property
def default(self):
return getattr(self, '_default', [] if self.repeated else None)
@default.setter
def default(self, value):
self._default = self.validator(None, value).copy()
def validator(self, instance, value):
"""return a Vector based on input if input is valid"""
if isinstance(value, vmath.Vector):
return value
if isinstance(value, six.string_types):
if value.upper() == 'X':
return vmath.Vector(1, 0, 0)
if value.upper() == 'Y':
return vmath.Vector(0, 1, 0)
if value.upper() == 'Z':
return vmath.Vector(0, 0, 1)
try:
return vmath.Vector(value)
except Exception:
raise ValueError('{}: must be Vector with '
'3 elements'.format(self.name))
def from_json(self, value):
return vmath.Vector(*value)
| Improve vector property error message | Improve vector property error message
| Python | mit | aranzgeo/properties,3ptscience/properties | ---
+++
@@ -39,7 +39,8 @@
try:
return vmath.Vector(value)
except Exception:
- raise ValueError('{} must be a Vector'.format(self.name))
+ raise ValueError('{}: must be Vector with '
+ '3 elements'.format(self.name))
def from_json(self, value):
return vmath.Vector(*value) |
b0b067c70d3bfc8fb599bd859116cce60f6759da | examples/dft/12-camb3lyp.py | examples/dft/12-camb3lyp.py | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
The default XC functional library (libxc) supports the energy and nuclear
gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
need xcfun library. See also example 32-xcfun_as_default.py for how to set
xcfun library as the default XC functional library.
'''
from pyscf import gto, dft
mol = gto.M(atom="H; F 1 1.", basis='631g')
mf = dft.UKS(mol)
mf.xc = 'CAMB3LYP'
mf.kernel()
mf.nuc_grad_method().kernel()
from pyscf.hessian import uks as uks_hess
# Switching to xcfun library on the fly
mf._numint.libxc = dft.xcfun
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
from pyscf import tdscf
# Switching to xcfun library on the fly
mf._numint.libxc = dft.xcfun
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
| #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''Density functional calculations can be run with either the default
backend library, libxc, or an alternative library, xcfun. See also
example 32-xcfun_as_default.py for how to set xcfun as the default XC
functional library.
'''
from pyscf import gto, dft
from pyscf.hessian import uks as uks_hess
from pyscf import tdscf
mol = gto.M(atom="H; F 1 1.", basis='631g')
# Calculation using libxc
mf = dft.UKS(mol)
mf.xc = 'CAMB3LYP'
mf.kernel()
mf.nuc_grad_method().kernel()
# We can also evaluate the geometric hessian
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
# or TDDFT gradients
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
# Switch to the xcfun library on the fly
mf._numint.libxc = dft.xcfun
# Repeat the geometric hessian
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
# and the TDDFT gradient calculation
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
tdks.nuc_grad_method().kernel()
| Update the camb3lyp example to libxc 5 series | Update the camb3lyp example to libxc 5 series
| Python | apache-2.0 | sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf | ---
+++
@@ -3,36 +3,42 @@
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
-'''
-The default XC functional library (libxc) supports the energy and nuclear
-gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
-need xcfun library. See also example 32-xcfun_as_default.py for how to set
-xcfun library as the default XC functional library.
+'''Density functional calculations can be run with either the default
+backend library, libxc, or an alternative library, xcfun. See also
+example 32-xcfun_as_default.py for how to set xcfun as the default XC
+functional library.
+
'''
from pyscf import gto, dft
+from pyscf.hessian import uks as uks_hess
+from pyscf import tdscf
mol = gto.M(atom="H; F 1 1.", basis='631g')
+
+# Calculation using libxc
mf = dft.UKS(mol)
mf.xc = 'CAMB3LYP'
mf.kernel()
-
mf.nuc_grad_method().kernel()
-
-from pyscf.hessian import uks as uks_hess
-# Switching to xcfun library on the fly
-mf._numint.libxc = dft.xcfun
+# We can also evaluate the geometric hessian
hess = uks_hess.Hessian(mf).kernel()
print(hess.reshape(2,3,2,3))
-
-from pyscf import tdscf
-# Switching to xcfun library on the fly
-mf._numint.libxc = dft.xcfun
+# or TDDFT gradients
tdks = tdscf.TDA(mf)
tdks.nstates = 3
tdks.kernel()
-
tdks.nuc_grad_method().kernel()
+# Switch to the xcfun library on the fly
+mf._numint.libxc = dft.xcfun
+# Repeat the geometric hessian
+hess = uks_hess.Hessian(mf).kernel()
+print(hess.reshape(2,3,2,3))
+# and the TDDFT gradient calculation
+tdks = tdscf.TDA(mf)
+tdks.nstates = 3
+tdks.kernel()
+tdks.nuc_grad_method().kernel() |
35aec417f31fce87ff31f255b0781352def48217 | examples/generate_images.py | examples/generate_images.py | from __future__ import print_function
import subprocess
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path to ImageMagick's convert.exe>
# Compile the LaTeX document with examples
num_runs = 2
for i in range(num_runs):
subprocess.run(["pdflatex", "--interaction=nonstopmode", "_examples.tex"])
# Convert pdf to png
#
# Optional: If you do not want a transparent background, add
#
# "-background", "white",
# "-alpha", "remove",
#
# to the call arguments
page_exists = True
page_num = 0
while page_exists:
print("Processing page {:d}".format(page_num + 1))
ret_val = subprocess.run(["convert-im",
"-density", "800",
"-trim",
"-resize", "25%",
"-quality", "100",
"_examples.pdf[{:02d}]".format(page_num),
"_examples-{:02d}.png".format(page_num),
])
page_num += 1
page_exists = ret_val == 0
| from subprocess import run
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path to ImageMagick's convert.exe>
# Compile the LaTeX document with examples
num_runs = 2
for i in range(num_runs):
run(["pdflatex", "--interaction=nonstopmode", "_examples.tex"])
# Convert pdf to png
#
# Optional: If you do not want a transparent background, add
#
# "-background", "white",
# "-alpha", "remove",
#
# to the call arguments
page_exists = True
page_num = 0
while page_exists:
print("Processing page {:d}".format(page_num + 1))
ret_val = run([
"convert-im",
"-density", "1600",
"-trim",
"-resize", "12.5%",
"-quality", "100",
"_examples.pdf[{:02d}]".format(page_num),
"_examples-{:02d}.png".format(page_num),
]).returncode
page_num += 1
page_exists = ret_val == 0
| Refactor examples generation to Python 3 | Refactor examples generation to Python 3
| Python | mit | mp4096/blockschaltbilder | ---
+++
@@ -1,5 +1,4 @@
-from __future__ import print_function
-import subprocess
+from subprocess import run
# Compile examples and export them as images
@@ -16,7 +15,7 @@
# Compile the LaTeX document with examples
num_runs = 2
for i in range(num_runs):
- subprocess.run(["pdflatex", "--interaction=nonstopmode", "_examples.tex"])
+ run(["pdflatex", "--interaction=nonstopmode", "_examples.tex"])
# Convert pdf to png
#
@@ -30,13 +29,14 @@
page_num = 0
while page_exists:
print("Processing page {:d}".format(page_num + 1))
- ret_val = subprocess.run(["convert-im",
- "-density", "800",
- "-trim",
- "-resize", "25%",
- "-quality", "100",
- "_examples.pdf[{:02d}]".format(page_num),
- "_examples-{:02d}.png".format(page_num),
- ])
+ ret_val = run([
+ "convert-im",
+ "-density", "1600",
+ "-trim",
+ "-resize", "12.5%",
+ "-quality", "100",
+ "_examples.pdf[{:02d}]".format(page_num),
+ "_examples-{:02d}.png".format(page_num),
+ ]).returncode
page_num += 1
page_exists = ret_val == 0 |
76be04b7474d9a12d45256c3f31719e3b2ac425d | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/data/TestSwiftFoundationTypeData.py | packages/Python/lldbsuite/test/lang/swift/foundation_value_types/data/TestSwiftFoundationTypeData.py | # TestSwiftFoundationValueTypes.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
# https://bugs.swift.org/browse/SR-3320
# This test fails with an assertion error with stdlib resilience enabled:
# https://github.com/apple/swift/pull/13573
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[
decorators.skipIf])
| # TestSwiftFoundationValueTypes.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[
decorators.skipUnlessDarwin,
decorators.expectedFailureAll(bugnumber="https://bugs.swift.org/browse/SR-3320")])
| Revert "Skip an x-failed test due to an unexpected assert" | Revert "Skip an x-failed test due to an unexpected assert"
This reverts commit b04c3edb7a8bcb5265a1ea4265714dcb8d1b185a.
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | ---
+++
@@ -12,9 +12,7 @@
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
-# https://bugs.swift.org/browse/SR-3320
-# This test fails with an assertion error with stdlib resilience enabled:
-# https://github.com/apple/swift/pull/13573
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[
- decorators.skipIf])
+ decorators.skipUnlessDarwin,
+ decorators.expectedFailureAll(bugnumber="https://bugs.swift.org/browse/SR-3320")]) |
3974d63721c49564be638c9912ee3e940ca2695d | decisiontree/tasks.py | decisiontree/tasks.py | from threadless_router.router import Router
from decisiontree.models import Session
from celery.task import Task
from celery.registry import tasks
import logging
logger = logging.getLogger()
logging.getLogger().setLevel(logging.DEBUG)
class PeriodicTask(Task):
"""celery task to notice when we haven't gotten a response after some time
and send a reminder. See settings.py.example and README.rst"""
def run(self):
logger.critical("HEY I'm in decisiontree's PeriodicTask")
router = Router()
app = router.get_app('decisiontree')
for session in Session.objects.filter(state__isnull=False,canceled__isnull=True):
app.tick(session)
logger.critical("HEY I'm in decisiontree's PeriodicTask... done")
tasks.register(PeriodicTask)
| from celery.task import task
from decisiontree.models import Session
@task
def check_for_session_timeout():
"""
Check sessions and send a reminder if they have not responded in
the given threshold.
Note: this requires the threadless router to run.
"""
from threadless_router.router import Router
router = Router()
app = router.get_app('decisiontree')
for session in Session.objects.filter(state__isnull=False, canceled__isnull=True):
app.tick(session)
| Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router. | Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router.
| Python | bsd-3-clause | caktus/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app | ---
+++
@@ -1,24 +1,18 @@
-from threadless_router.router import Router
+from celery.task import task
from decisiontree.models import Session
-from celery.task import Task
-from celery.registry import tasks
-import logging
-logger = logging.getLogger()
+@task
+def check_for_session_timeout():
+ """
+ Check sessions and send a reminder if they have not responded in
+ the given threshold.
-logging.getLogger().setLevel(logging.DEBUG)
-
-class PeriodicTask(Task):
- """celery task to notice when we haven't gotten a response after some time
- and send a reminder. See settings.py.example and README.rst"""
- def run(self):
- logger.critical("HEY I'm in decisiontree's PeriodicTask")
- router = Router()
- app = router.get_app('decisiontree')
- for session in Session.objects.filter(state__isnull=False,canceled__isnull=True):
- app.tick(session)
- logger.critical("HEY I'm in decisiontree's PeriodicTask... done")
-
-tasks.register(PeriodicTask)
+ Note: this requires the threadless router to run.
+ """
+ from threadless_router.router import Router
+ router = Router()
+ app = router.get_app('decisiontree')
+ for session in Session.objects.filter(state__isnull=False, canceled__isnull=True):
+ app.tick(session) |
cb8fe795aff58078a16ae1fac655c04762145abd | subscription/api.py | subscription/api.py | from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
| from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL
}
| Add filter for getting user subs: | Add filter for getting user subs:
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control | ---
+++
@@ -1,5 +1,5 @@
from tastypie import fields
-from tastypie.resources import ModelResource
+from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
@@ -34,3 +34,6 @@
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
+ filtering = {
+ 'to_addr': ALL
+ } |
934ec1300e70be518021d5851bdc380fef844393 | billjobs/tests/tests_export_account_email.py | billjobs/tests/tests_export_account_email.py | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
| from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test UserAdmin class has method export_email """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
""" Test method return an HttpResponse """
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(),
queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
""" Test method return text/csv as http response content type """
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(),
queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
| Add comment and reformat code | Add comment and reformat code
| Python | mit | ioO/billjobs | ---
+++
@@ -15,7 +15,7 @@
self.query_set = User.objects.all()
def test_method_is_avaible(self):
- """ Test admin can select the action in dropdown list """
+ """ Test UserAdmin class has method export_email """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
@@ -24,15 +24,19 @@
def test_action_has_a_short_description(self):
""" Test method has a short description """
- self.assertEqual(UserAdmin.export_email.short_description,
+ self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
+ """ Test method return an HttpResponse """
user_admin = UserAdmin(User, self.site)
- response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
+ response = user_admin.export_email(request=MockRequest(),
+ queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
+ """ Test method return text/csv as http response content type """
user_admin = UserAdmin(User, self.site)
- response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
+ response = user_admin.export_email(request=MockRequest(),
+ queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv') |
ebd829a4939a524283d5603ed86a916c7bf88bb9 | regcore/db/storage.py | regcore/db/storage.py | from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django ORM versions"""
class_str = settings.BACKENDS.get(
data_type,
'regcore.db.django_models.DM' + data_type.capitalize())
return import_string(class_str)
for_regulations = select_for('regulations')
for_layers = select_for('layers')
for_notices = select_for('notices')
for_diffs = select_for('diffs')
for_preambles = select_for('preambles')
| from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django ORM versions"""
class_str = settings.BACKENDS.get(
data_type,
'regcore.db.django_models.DM' + data_type.capitalize())
return import_string(class_str)()
for_regulations = select_for('regulations')
for_layers = select_for('layers')
for_notices = select_for('notices')
for_diffs = select_for('diffs')
for_preambles = select_for('preambles')
| Fix error during merge commit | Fix error during merge commit
| Python | cc0-1.0 | cmc333333/regulations-core,18F/regulations-core,eregs/regulations-core | ---
+++
@@ -9,7 +9,7 @@
class_str = settings.BACKENDS.get(
data_type,
'regcore.db.django_models.DM' + data_type.capitalize())
- return import_string(class_str)
+ return import_string(class_str)()
for_regulations = select_for('regulations')
for_layers = select_for('layers') |
b35befc9677541295609f4e55eea6fc2c4d7ab08 | office365/runtime/odata/odata_path_parser.py | office365/runtime/odata/odata_path_parser.py | from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_parameters:
if isinstance(method_parameters, dict):
url += ','.join(['%s=%s' % (key, ODataPathParser.encode_method_value(value)) for (key, value) in
method_parameters.items()])
else:
url += ','.join(['%s' % (ODataPathParser.encode_method_value(value)) for (i, value) in
enumerate(method_parameters)])
url += ")"
return url
@staticmethod
def encode_method_value(value):
if isinstance(value, basestring):
value = "'{0}'".format(value.replace("'", "''"))
elif isinstance(value, bool):
value = str(value).lower()
return value
| from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_parameters:
if isinstance(method_parameters, dict):
url += ','.join(['%s=%s' % (key, ODataPathParser.encode_method_value(value)) for (key, value) in
method_parameters.items()])
else:
url += ','.join(['%s' % (ODataPathParser.encode_method_value(value)) for (i, value) in
enumerate(method_parameters)])
url += ")"
return url
@staticmethod
def encode_method_value(value):
if isinstance(value, basestring):
value = value.replace("'", "''")
# Same replacements as SQL Server
# https://web.archive.org/web/20150101222238/http://msdn.microsoft.com/en-us/library/aa226544(SQL.80).aspx
# https://stackoverflow.com/questions/4229054/how-are-special-characters-handled-in-an-odata-query#answer-45883747
value = value.replace('%', '%25')
value = value.replace('+', '%2B')
value = value.replace('/', '%2F')
value = value.replace('?', '%3F')
value = value.replace('#', '%23')
value = value.replace('&', '%26')
value = "'{0}'".format(value)
elif isinstance(value, bool):
value = str(value).lower()
return value
| Add more OData parameter format escapes | Add more OData parameter format escapes
| Python | mit | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client | ---
+++
@@ -26,7 +26,19 @@
@staticmethod
def encode_method_value(value):
if isinstance(value, basestring):
- value = "'{0}'".format(value.replace("'", "''"))
+ value = value.replace("'", "''")
+
+ # Same replacements as SQL Server
+ # https://web.archive.org/web/20150101222238/http://msdn.microsoft.com/en-us/library/aa226544(SQL.80).aspx
+ # https://stackoverflow.com/questions/4229054/how-are-special-characters-handled-in-an-odata-query#answer-45883747
+ value = value.replace('%', '%25')
+ value = value.replace('+', '%2B')
+ value = value.replace('/', '%2F')
+ value = value.replace('?', '%3F')
+ value = value.replace('#', '%23')
+ value = value.replace('&', '%26')
+
+ value = "'{0}'".format(value)
elif isinstance(value, bool):
value = str(value).lower()
return value |
b5601797b0e734514e5958be64576abe9fe684d7 | src/cli.py | src/cli.py | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, opts=None):
if len(args) == 0:
args = '/'
self.explorer.change_dir(args)
def do_load(self, args, opts=None):
print("Loading "+ args)
self.explorer = h5_wrapper.H5Explorer(args)
def do_pwd(self, args, opts=None):
print(self.explorer.working_dir)
def do_pushd(self, args, opts=None):
self.explorer.push_dir(args)
def do_popd(self, args, opts=None):
self.explorer.pop_dir()
self.do_pwd(None)
def precmd(self, line):
if not line.startswith('load') and (line.endswith('.h5') or line.endswith('.hdf5')):
line = 'load ' + line
return line
def do_exit(self, args):
return True
def do_clear(self, args):
os.system('clear')
if __name__ == '__main__':
c = CmdApp()
c.cmdloop()
| from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
if len(args.strip()) > 0:
for g in self.explorer.list_groups(args):
print(g+"/")
for ds in self.explorer.list_datasets(args):
print(ds)
else:
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, opts=None):
if len(args) == 0:
args = '/'
self.explorer.change_dir(args)
def do_load(self, args, opts=None):
print("Loading "+ args)
self.explorer = h5_wrapper.H5Explorer(args)
def do_pwd(self, args, opts=None):
print(self.explorer.working_dir)
def do_pushd(self, args, opts=None):
self.explorer.push_dir(args)
def do_popd(self, args, opts=None):
self.explorer.pop_dir()
self.do_pwd(None)
def precmd(self, line):
if not line.startswith('load') and (line.endswith('.h5') or line.endswith('.hdf5')):
line = 'load ' + line
return line
def do_exit(self, args):
return True
def do_clear(self, args):
os.system('clear')
if __name__ == '__main__':
c = CmdApp()
c.cmdloop()
| Allow ls to pass arguments | Allow ls to pass arguments
| Python | mit | ksunden/h5cli | ---
+++
@@ -6,11 +6,18 @@
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
- for g in self.explorer.list_groups():
- print(g+"/")
-
- for ds in self.explorer.list_datasets():
- print(ds)
+ if len(args.strip()) > 0:
+ for g in self.explorer.list_groups(args):
+ print(g+"/")
+
+ for ds in self.explorer.list_datasets(args):
+ print(ds)
+ else:
+ for g in self.explorer.list_groups():
+ print(g+"/")
+
+ for ds in self.explorer.list_datasets():
+ print(ds)
def do_cd(self, args, opts=None):
if len(args) == 0: |
c01b01bd8ab640f74da0796ac1b6f05f5dc3ebc1 | pytest_cram/tests/test_options.py | pytest_cram/tests/test_options.py | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_cramignore(testdir):
testdir.makeini("""
[pytest]
cramignore =
sub/a*.t
a.t
c*.t
""")
testdir.tmpdir.ensure("sub/a.t")
testdir.tmpdir.ensure("sub/a0.t")
testdir.tmpdir.ensure("a.t")
testdir.tmpdir.ensure("a0.t")
testdir.tmpdir.ensure("b.t")
testdir.tmpdir.ensure("b0.t")
testdir.tmpdir.ensure("c.t")
testdir.tmpdir.ensure("c0.t")
result = testdir.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines([
"*collected 3*",
"a0.t s",
"b.t s",
"b0.t s",
"*3 skipped*",
])
| import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_nocram(testdir):
"""Ensure that --nocram collects .py but not .t files."""
testdir.makefile('.t', " $ true")
testdir.makepyfile("def test_(): assert True")
result = testdir.runpytest("--nocram")
assert result.ret == 0
result.stdout.fnmatch_lines(["test_nocram.py .", "*1 passed*"])
def test_cramignore(testdir):
"""Ensure that the cramignore option ignore the appropriate cram tests."""
testdir.makeini("""
[pytest]
cramignore =
sub/a*.t
a.t
c*.t
""")
testdir.tmpdir.ensure("sub/a.t")
testdir.tmpdir.ensure("sub/a0.t")
testdir.tmpdir.ensure("a.t")
testdir.tmpdir.ensure("a0.t")
testdir.tmpdir.ensure("b.t")
testdir.tmpdir.ensure("b0.t")
testdir.tmpdir.ensure("c.t")
testdir.tmpdir.ensure("c0.t")
result = testdir.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines([
"*collected 3*",
"a0.t s",
"b.t s",
"b0.t s",
"*3 skipped*",
])
| Test the --nocram command line option | Test the --nocram command line option
| Python | mit | tbekolay/pytest-cram,tbekolay/pytest-cram | ---
+++
@@ -7,7 +7,17 @@
assert pytest_cram.__version__
+def test_nocram(testdir):
+ """Ensure that --nocram collects .py but not .t files."""
+ testdir.makefile('.t', " $ true")
+ testdir.makepyfile("def test_(): assert True")
+ result = testdir.runpytest("--nocram")
+ assert result.ret == 0
+ result.stdout.fnmatch_lines(["test_nocram.py .", "*1 passed*"])
+
+
def test_cramignore(testdir):
+ """Ensure that the cramignore option ignore the appropriate cram tests."""
testdir.makeini("""
[pytest]
cramignore = |
15c51102f8e9f37bb08f9f6c04c7da2d75250cd2 | cabot/cabot_config.py | cabot/cabot_config.py | import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.environ.get('JENKINS_PASS')
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
ALERT_INTERVAL = os.environ.get('ALERT_INTERVAL', 10)
NOTIFICATION_INTERVAL = os.environ.get('NOTIFICATION_INTERVAL', 120)
# Default plugins are used if the user has not specified.
CABOT_PLUGINS_ENABLED = os.environ.get('CABOT_PLUGINS_ENABLED', 'cabot_alert_hipchat,cabot_alert_twilio,cabot_alert_email')
| import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.environ.get('JENKINS_PASS')
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
ALERT_INTERVAL = int(os.environ.get('ALERT_INTERVAL', 10))
NOTIFICATION_INTERVAL = int(os.environ.get('NOTIFICATION_INTERVAL', 120))
# Default plugins are used if the user has not specified.
CABOT_PLUGINS_ENABLED = os.environ.get('CABOT_PLUGINS_ENABLED', 'cabot_alert_hipchat,cabot_alert_twilio,cabot_alert_email')
| Convert *_INTERVAL variables to int | Convert *_INTERVAL variables to int
ALERT_INTERVAL and NOTIFICATION_INTERVAL are now converted to
numbers. This allows user-defined ALERT_INTERVAL and
NOTIFICATION_INTERVAL env variables to work without throwing
TypeErrors:
return self.run(*args, **kwargs)
File "/cabot/cabot/cabotapp/tasks.py", line 68, in update_service
service.update_status()
File "/cabot/cabot/cabotapp/models.py", line 243, in update_status
self.alert()
File "/cabot/cabot/cabotapp/models.py", line 174, in alert
if self.last_alert_sent and (timezone.now() - timedelta(minutes=settings.ALERT_INTERVAL)) < self.last_alert_sent:
TypeError: unsupported type for timedelta minutes component: str
| Python | mit | arachnys/cabot,reddit/cabot,cmclaughlin/cabot,cmclaughlin/cabot,bonniejools/cabot,dever860/cabot,lghamie/cabot,jdycar/cabot,jdycar/cabot,movermeyer/cabot,xinity/cabot,lghamie/cabot,dever860/cabot,lghamie/cabot,dever860/cabot,cmclaughlin/cabot,arachnys/cabot,maks-us/cabot,mcansky/cabotapp,xinity/cabot,cmclaughlin/cabot,bonniejools/cabot,xinity/cabot,mcansky/cabotapp,maks-us/cabot,robocopio/cabot,movermeyer/cabot,dever860/cabot,robocopio/cabot,mcansky/cabotapp,robocopio/cabot,robocopio/cabot,arachnys/cabot,maks-us/cabot,reddit/cabot,lghamie/cabot,reddit/cabot,bonniejools/cabot,xinity/cabot,bonniejools/cabot,arachnys/cabot,movermeyer/cabot,movermeyer/cabot,maks-us/cabot,reddit/cabot,jdycar/cabot,mcansky/cabotapp,jdycar/cabot | ---
+++
@@ -10,8 +10,8 @@
CALENDAR_ICAL_URL = os.environ.get('CALENDAR_ICAL_URL')
WWW_HTTP_HOST = os.environ.get('WWW_HTTP_HOST')
WWW_SCHEME = os.environ.get('WWW_SCHEME', "https")
-ALERT_INTERVAL = os.environ.get('ALERT_INTERVAL', 10)
-NOTIFICATION_INTERVAL = os.environ.get('NOTIFICATION_INTERVAL', 120)
+ALERT_INTERVAL = int(os.environ.get('ALERT_INTERVAL', 10))
+NOTIFICATION_INTERVAL = int(os.environ.get('NOTIFICATION_INTERVAL', 120))
# Default plugins are used if the user has not specified.
CABOT_PLUGINS_ENABLED = os.environ.get('CABOT_PLUGINS_ENABLED', 'cabot_alert_hipchat,cabot_alert_twilio,cabot_alert_email') |
8753b17e4583ca84249234fa09c5669df7a9d6ff | txnats/_meta.py | txnats/_meta.py | version_info = (0, 5, 1)
version = '.'.join(map(str, version_info))
| version_info = (0, 5, 2)
version = '.'.join(map(str, version_info))
| Increment version because bad release | Increment version because bad release
| Python | mit | johnwlockwood/txnats | ---
+++
@@ -1,2 +1,2 @@
-version_info = (0, 5, 1)
+version_info = (0, 5, 2)
version = '.'.join(map(str, version_info)) |
b0c27402da5522db7d8e1b65c81a28b3a19500b0 | pyinfra/modules/virtualenv.py | pyinfra/modules/virtualenv.py | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_copy=False,
present=True,
):
'''
Manage virtualenv.
+ python: python interpreter to use
+ site_packages: give access to the global site-packages
+ always_copy: always copy files rather than symlinking
+ present: whether the virtualenv should be installed
'''
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
for cmd in files.directory(state, host, path, present=False):
yield cmd
elif present and not host.fact.directory(path):
# Create missing virtualenv
command = '/usr/bin/virtualenv'
if python:
command += ' -p {}'.format(python)
if site_packages:
command += ' --system-site-packages'
if always_copy:
command += ' --always-copy'
command += ' ' + path
yield command
| # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_copy=False,
present=True,
):
'''
Manage virtualenv.
+ python: python interpreter to use
+ site_packages: give access to the global site-packages
+ always_copy: always copy files rather than symlinking
+ present: whether the virtualenv should be installed
'''
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
yield files.directory(state, host, path, present=False)
elif present and not host.fact.directory(path):
# Create missing virtualenv
command = '/usr/bin/virtualenv'
if python:
command += ' -p {}'.format(python)
if site_packages:
command += ' --system-site-packages'
if always_copy:
command += ' --always-copy'
command += ' ' + path
yield command
| Fix relying on pyinfra generator unroll | Fix relying on pyinfra generator unroll
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | ---
+++
@@ -30,8 +30,7 @@
if present is False and host.fact.directory(path):
# Ensure deletion of unwanted virtualenv
# no 'yield from' in python 2.7
- for cmd in files.directory(state, host, path, present=False):
- yield cmd
+ yield files.directory(state, host, path, present=False)
elif present and not host.fact.directory(path):
# Create missing virtualenv |
0ebac1925b3d4b32188a6f2c9e40760b21d933ce | backend/uclapi/dashboard/app_helpers.py | backend/uclapi/dashboard/app_helpers.py | from binascii import hexlify
import os
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_key += char
final = "uclapi" + dashes_key
return final
def generate_app_id():
key = hexlify(os.urandom(5)).decode()
final = "A" + key
return final
| from binascii import hexlify
from random import choice
import os
import string
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_key += char
final = "uclapi" + dashes_key
return final
def generate_app_id():
key = hexlify(os.urandom(5)).decode()
final = "A" + key
return final
def generate_app_client_id():
client_id = ''.join(random.choice(string.digits, k=16))
client_id += "."
client_id += ''.join(random.choice(string.digits, k=16))
return client_id
def generate_app_client_secret():
client_secret = ''.join(random.choice(string.ascii_lowercase + string.digits, k=64))
return client_secret | Add helpers to the dashboard code to generate OAuth keys | Add helpers to the dashboard code to generate OAuth keys
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | ---
+++
@@ -1,5 +1,8 @@
from binascii import hexlify
+from random import choice
+
import os
+import string
def generate_api_token():
@@ -21,3 +24,15 @@
final = "A" + key
return final
+
+def generate_app_client_id():
+ client_id = ''.join(random.choice(string.digits, k=16))
+ client_id += "."
+ client_id += ''.join(random.choice(string.digits, k=16))
+
+ return client_id
+
+def generate_app_client_secret():
+ client_secret = ''.join(random.choice(string.ascii_lowercase + string.digits, k=64))
+
+ return client_secret |
63f650855dfc707c6850add17d9171ba003bebcb | ckeditor_demo/urls.py | ckeditor_demo/urls.py | from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VERSION >= (1, 8):
urlpatterns = [
url(r'^$', ckeditor_form_view, name='ckeditor-form'),
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
]
else:
from django.conf.urls import patterns
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', ckeditor_form_view, name='ckeditor-form'),
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
)
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VERSION >= (1, 8):
urlpatterns = [
url(r'^$', ckeditor_form_view, name='ckeditor-form'),
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
]
else:
from django.conf.urls import patterns
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', ckeditor_form_view, name='ckeditor-form'),
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
| Fix media handling in demo application. | Fix media handling in demo application.
| Python | bsd-3-clause | MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,zatarus/django-ckeditor,Josephpaik/django-ckeditor,MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,MarcJoan/django-ckeditor,Josephpaik/django-ckeditor,Josephpaik/django-ckeditor | ---
+++
@@ -3,7 +3,6 @@
import django
from django.conf import settings
from django.conf.urls import include, url
-from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
@@ -15,6 +14,9 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
+ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
+ 'document_root': settings.MEDIA_ROOT,
+ }),
]
else:
from django.conf.urls import patterns
@@ -26,6 +28,7 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^static/(?P<path>.*)$', views.serve),
+ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
+ 'document_root': settings.MEDIA_ROOT,
+ }),
)
-
-urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
412e672ea12c691b423acfa1b67a7a2626d91b0d | openslides/default.settings.py | openslides/default.settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Global settings file.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
# Django settings for openslides project.
from openslides_settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
TIME_ZONE = 'Europe/Berlin'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '=(v@$58k$fcl4y8t2#q15y-9p=^45y&!$!ap$7xo6ub$akg-!5'
# Add OpenSlides plugins to this list (see example entry in comment)
INSTALLED_PLUGINS = (
# 'pluginname',
)
INSTALLED_APPS += INSTALLED_PLUGINS
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Global Django settings file for OpenSlides.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from openslides_settings import *
# Use 'DEBUG = True' to get more details for server errors (Default for relaeses: 'False')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
TIME_ZONE = 'Europe/Berlin'
# Default language for model/form translation strings
LANGUAGE_CODE = 'de'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '=(v@$58k$fcl4y8t2#q15y-9p=^45y&!$!ap$7xo6ub$akg-!5'
# Add OpenSlides plugins to this list (see example entry in comment)
INSTALLED_PLUGINS = (
# 'pluginname',
)
INSTALLED_APPS += INSTALLED_PLUGINS
| Set default language for model/form translation strings. Have to changed for English installation! (Template strings are translated automatically by selected browser language) | Set default language for model/form translation strings. Have to changed for English installation!
(Template strings are translated automatically by selected browser language)
| Python | mit | emanuelschuetze/OpenSlides,jwinzer/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,boehlke/OpenSlides,boehlke/OpenSlides,CatoTH/OpenSlides,normanjaeckel/OpenSlides,normanjaeckel/OpenSlides,ostcar/OpenSlides,jwinzer/OpenSlides,rolandgeider/OpenSlides,rolandgeider/OpenSlides,emanuelschuetze/OpenSlides,jwinzer/OpenSlides,tsiegleauq/OpenSlides,emanuelschuetze/OpenSlides,FinnStutzenstein/OpenSlides,CatoTH/OpenSlides,tsiegleauq/OpenSlides,FinnStutzenstein/OpenSlides,ostcar/OpenSlides,CatoTH/OpenSlides,emanuelschuetze/OpenSlides,ostcar/OpenSlides,jwinzer/OpenSlides,OpenSlides/OpenSlides,FinnStutzenstein/OpenSlides,boehlke/OpenSlides,FinnStutzenstein/OpenSlides,normanjaeckel/OpenSlides,tsiegleauq/OpenSlides,rolandgeider/OpenSlides,OpenSlides/OpenSlides,normanjaeckel/OpenSlides,boehlke/OpenSlides | ---
+++
@@ -4,19 +4,21 @@
openslides.default.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Global settings file.
+ Global Django settings file for OpenSlides.
:copyright: 2011, 2012 by OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
-
-# Django settings for openslides project.
from openslides_settings import *
+# Use 'DEBUG = True' to get more details for server errors (Default for relaeses: 'False')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
TIME_ZONE = 'Europe/Berlin'
+
+# Default language for model/form translation strings
+LANGUAGE_CODE = 'de'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '=(v@$58k$fcl4y8t2#q15y-9p=^45y&!$!ap$7xo6ub$akg-!5' |
543509e991f88ecad7e5ed69db6d3b175fe44351 | tests/constants.py | tests/constants.py | TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_GROUP = ''
TEST_BAD_USER = '1234'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
| TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_BAD_USER = '1234'
TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3133d6'
TEST_RECEIPT_ID = 'rLqVuqTRh62UzxtmqiaLzQmVcPgiCy'
PUSHOVER_API_URL = 'https://api.pushover.net/1/'
| Add a test group key | Add a test group key
| Python | mit | scolby33/pushover_complete | ---
+++
@@ -1,7 +1,7 @@
TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
-TEST_GROUP = ''
TEST_BAD_USER = '1234'
+TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.' |
07598bf67c3771391a5f3e287aab4b2c49180a05 | tests/test_tests.py | tests/test_tests.py | """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
class TestTests(BaseServiceTests):
"""Tests for :class:`retdec.test.Test`."""
def test_auth_sends_correct_request(self):
test = Test(api_key='API-KEY')
test.auth()
self.APIConnectionMock.assert_called_once_with(
'https://retdec.com/service/api/test/echo',
'API-KEY'
)
self.conn_mock.send_get_request.assert_called_once_with()
def test_auth_raises_exception_when_authentication_fails(self):
self.conn_mock.send_get_request.side_effect = AuthenticationError(
code=401,
message='Unauthorized by API Key',
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
with self.assertRaises(AuthenticationError) as cm:
test.auth()
| """
Tests for the :mod:`retdec.test` module.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
from retdec.exceptions import AuthenticationError
from retdec.test import Test
from tests.service_tests import BaseServiceTests
class TestTests(BaseServiceTests):
"""Tests for :class:`retdec.test.Test`."""
def test_auth_sends_correct_request(self):
test = Test(api_key='API-KEY')
test.auth()
self.APIConnectionMock.assert_called_once_with(
'https://retdec.com/service/api/test/echo',
'API-KEY'
)
self.conn_mock.send_get_request.assert_called_once_with()
def test_auth_raises_exception_when_authentication_fails(self):
self.conn_mock.send_get_request.side_effect = AuthenticationError(
code=401,
message='Unauthorized by API Key',
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
with self.assertRaises(AuthenticationError):
test.auth()
| Remove an unused variable from TestTests. | Remove an unused variable from TestTests.
| Python | mit | s3rvac/retdec-python | ---
+++
@@ -31,5 +31,5 @@
description='API key authentication failed.'
)
test = Test(api_key='INVALID-API-KEY')
- with self.assertRaises(AuthenticationError) as cm:
+ with self.assertRaises(AuthenticationError):
test.auth() |
8e0f2271b19504886728ccf5d060778c027c79ca | ide/views.py | ide/views.py | import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_all_projects())
@app.route('/parse', methods=['POST'])
def parse():
return requests.post(MCLABAAS_URL + '/ast', data=request.data).text
class ProjectConverter(BaseConverter):
def to_python(self, value):
return Project(value)
def to_url(self, value):
return BaseConverter.to_url(value.name)
app.url_map.converters['project'] = ProjectConverter
@app.route('/project/<project:project>/')
def project(project):
if not project.exists():
abort(404)
return render_template('project.html')
@app.route('/project/<project:project>/tree', methods=['GET'])
def tree(project):
return json.dumps(project.tree())
@app.route('/project/<project:project>/read', methods=['GET'])
def read(project):
return project.read_file(request.args['path'])
@app.route('/project/<project:project>/write', methods=['POST'])
def write(project):
project.write_file(request.form['path'], request.form['contents'])
return json.dumps({'status': 'OK'})
| import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_all_projects())
@app.route('/parse', methods=['POST'])
def parse():
return requests.post(MCLABAAS_URL + '/ast', data=request.data).text
class ProjectConverter(BaseConverter):
def to_python(self, value):
project = Project(value)
if not project.exists():
abort(404)
return project
def to_url(self, value):
return BaseConverter.to_url(value.name)
app.url_map.converters['project'] = ProjectConverter
@app.route('/project/<project:project>/')
def project(project):
return render_template('project.html')
@app.route('/project/<project:project>/tree', methods=['GET'])
def tree(project):
return json.dumps(project.tree())
@app.route('/project/<project:project>/read', methods=['GET'])
def read(project):
return project.read_file(request.args['path'])
@app.route('/project/<project:project>/write', methods=['POST'])
def write(project):
project.write_file(request.form['path'], request.form['contents'])
return json.dumps({'status': 'OK'})
| Check if project exists inside ProjectConverter. | Check if project exists inside ProjectConverter.
| Python | apache-2.0 | Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide | ---
+++
@@ -21,7 +21,10 @@
class ProjectConverter(BaseConverter):
def to_python(self, value):
- return Project(value)
+ project = Project(value)
+ if not project.exists():
+ abort(404)
+ return project
def to_url(self, value):
return BaseConverter.to_url(value.name)
@@ -31,8 +34,6 @@
@app.route('/project/<project:project>/')
def project(project):
- if not project.exists():
- abort(404)
return render_template('project.html')
|
5eb96c599dbbef56853dfb9441ab2eb54d36f9b7 | ckanext/syndicate/tests/test_plugin.py | ckanext/syndicate/tests/test_plugin.py | from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
self.entity.extras = {'syndicate': 'true'}
self.syndicate_patch = patch('ckanext.syndicate.plugin.syndicate_task')
self.plugin = SyndicatePlugin()
def test_syndicates_task_for_dataset_create(self):
with self.syndicate_patch as mock_syndicate:
self.plugin.notify(self.entity, DomainObjectOperation.new)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/create')
def test_syndicates_task_for_dataset_update(self):
with self.syndicate_patch as mock_syndicate:
self.plugin.notify(self.entity, DomainObjectOperation.changed)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/update')
| from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
self.entity.extras = {'syndicate': 'true'}
self.syndicate_patch = patch('ckanext.syndicate.plugin.syndicate_task')
self.plugin = SyndicatePlugin()
def test_syndicates_task_for_dataset_create(self):
with self.syndicate_patch as mock_syndicate:
self.plugin.notify(self.entity, DomainObjectOperation.new)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/create')
def test_syndicates_task_for_dataset_update(self):
with self.syndicate_patch as mock_syndicate:
self.plugin.notify(self.entity, DomainObjectOperation.changed)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/update')
def test_syndicates_task_for_dataset_delete(self):
with self.syndicate_patch as mock_syndicate:
self.plugin.notify(self.entity, DomainObjectOperation.deleted)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/delete')
| Add test for notify dataset/delete | Add test for notify dataset/delete
| Python | agpl-3.0 | aptivate/ckanext-syndicate,aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues,sorki/ckanext-redmine-autoissues | ---
+++
@@ -27,3 +27,9 @@
self.plugin.notify(self.entity, DomainObjectOperation.changed)
mock_syndicate.assert_called_with(self.entity.id,
'dataset/update')
+
+ def test_syndicates_task_for_dataset_delete(self):
+ with self.syndicate_patch as mock_syndicate:
+ self.plugin.notify(self.entity, DomainObjectOperation.deleted)
+ mock_syndicate.assert_called_with(self.entity.id,
+ 'dataset/delete') |
70c61b734940aed0ed4a491bc1169e1320d02998 | docs/conf.py | docs/conf.py | import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {}
""".format(release)
exclude_patterns = ['_build']
pygments_style = 'sphinx'
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
html_sidebars = {"**": ['localtoc.html', 'relations.html', 'sourcelink.html',
'searchbox.html', 'links.html']}
latex_elements = {}
latex_documents = [
('index', 'libtaxii.tex', u'libtaxii Documentation',
u'The MITRE Corporation', 'manual'),
]
| import os
import libtaxii
project = u'libtaxii'
copyright = u'2014, The MITRE Corporation'
version = libtaxii.__version__
release = version
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinxcontrib.napoleon',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
**Version**: {0}
""".format(release)
exclude_patterns = ['_build']
pygments_style = 'sphinx'
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
html_theme = 'default'
html_sidebars = {"**": ['localtoc.html', 'relations.html', 'sourcelink.html',
'searchbox.html', 'links.html']}
latex_elements = {}
latex_documents = [
('index', 'libtaxii.tex', u'libtaxii Documentation',
u'The MITRE Corporation', 'manual'),
]
| Fix zero-length field error when building docs in Python 2.6 | Fix zero-length field error when building docs in Python 2.6
| Python | bsd-3-clause | Intelworks/libtaxii,stkyle/libtaxii,TAXIIProject/libtaxii | ---
+++
@@ -24,7 +24,7 @@
master_doc = 'index'
rst_prolog = """
-**Version**: {}
+**Version**: {0}
""".format(release)
exclude_patterns = ['_build'] |
c9631819179eb99728c0ad7f3d6b46aef6dea079 | polygraph/types/object_type.py | polygraph/types/object_type.py | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
self.name = getattr(meta, 'name', None)
self.description = getattr(meta, 'name', None)
class ObjectType(Schema):
OPTIONS_CLASS = ObjectTypeOpts
def __init__(self, only=(), exclude=(), prefix='', strict=None,
many=False, context=None, load_only=(), dump_only=(),
partial=False):
super().__init__(only, exclude, prefix, strict,
many, context, load_only, dump_only, partial)
self._name = self.opts.name or self.__class__.__name__
self._description = self.opts.description or trim_docstring(self.__doc__)
def build_definition(self):
field_map = OrderedDict()
for fieldname, field in self.fields.items():
field_map[fieldname] = field.build_definition()
return GraphQLObjectType(name=self._name,
fields=field_map,
description=self._description)
| from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
self.name = getattr(meta, 'name', None)
self.description = getattr(meta, 'description', None)
class ObjectType(Schema):
OPTIONS_CLASS = ObjectTypeOpts
def __init__(self, only=(), exclude=(), prefix='', strict=None,
many=False, context=None, load_only=(), dump_only=(),
partial=False):
super().__init__(only, exclude, prefix, strict,
many, context, load_only, dump_only, partial)
self.name = self.opts.name or self.__class__.__name__
self.description = self.opts.description or trim_docstring(self.__doc__)
def build_definition(self):
field_map = OrderedDict()
for fieldname, field in self.fields.items():
field_map[fieldname] = field.build_definition()
return GraphQLObjectType(name=self.name,
fields=field_map,
description=self.description)
| Fix ObjectType name and description attributes | Fix ObjectType name and description attributes
| Python | mit | polygraph-python/polygraph | ---
+++
@@ -10,7 +10,7 @@
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
self.name = getattr(meta, 'name', None)
- self.description = getattr(meta, 'name', None)
+ self.description = getattr(meta, 'description', None)
class ObjectType(Schema):
@@ -21,13 +21,13 @@
partial=False):
super().__init__(only, exclude, prefix, strict,
many, context, load_only, dump_only, partial)
- self._name = self.opts.name or self.__class__.__name__
- self._description = self.opts.description or trim_docstring(self.__doc__)
+ self.name = self.opts.name or self.__class__.__name__
+ self.description = self.opts.description or trim_docstring(self.__doc__)
def build_definition(self):
field_map = OrderedDict()
for fieldname, field in self.fields.items():
field_map[fieldname] = field.build_definition()
- return GraphQLObjectType(name=self._name,
+ return GraphQLObjectType(name=self.name,
fields=field_map,
- description=self._description)
+ description=self.description) |
ac5b9765d69139915f06bd52d96b1abaa3d41331 | scuole/districts/views.py | scuole/districts/views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().select_related('county__name')
class DistrictDetailView(DetailView):
queryset = District.objects.all().prefetch_related('stats__year')
pk_url_kwarg = 'district_id'
slug_url_kwarg = 'district_slug'
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().defer('shape')
class DistrictDetailView(DetailView):
queryset = District.objects.all().prefetch_related('stats__year')
pk_url_kwarg = 'district_id'
slug_url_kwarg = 'district_slug'
| Remove unused select_related, defer the loading of shape for speed | Remove unused select_related, defer the loading of shape for speed
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | ---
+++
@@ -7,7 +7,7 @@
class DistrictListView(ListView):
- queryset = District.objects.all().select_related('county__name')
+ queryset = District.objects.all().defer('shape')
class DistrictDetailView(DetailView): |
924be2b545a4d00b9eacc5aa1c974e8ebf407c2f | shade/tests/unit/test_shade.py | shade/tests/unit/test_shade.py | # -*- coding: utf-8 -*-
# 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.
"""
test_shade
----------------------------------
Tests for `shade` module.
"""
from shade.tests import base
class TestShade(base.TestCase):
def test_something(self):
pass
| # -*- coding: utf-8 -*-
# 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 shade
from shade.tests import base
class TestShade(base.TestCase):
def test_openstack_cloud(self):
self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud)
| Add basic unit test for shade.openstack_cloud | Add basic unit test for shade.openstack_cloud
Just getting basic minimal surface area unit tests to help when making
changes. This exposed some python3 incompatibilities in
os-client-config, which is why the change Depends on
Ia78bd8edd17c7d2360ad958b3de734503d400774.
Change-Id: I9cf5082d01861a0b6b372728a33ce9df9ee8d300
Depends-On: Ia78bd8edd17c7d2360ad958b3de734503d400774
| Python | apache-2.0 | stackforge/python-openstacksdk,openstack-infra/shade,openstack/python-openstacksdk,openstack/python-openstacksdk,openstack-infra/shade,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,jsmartin/shade,jsmartin/shade | ---
+++
@@ -12,17 +12,11 @@
# License for the specific language governing permissions and limitations
# under the License.
-"""
-test_shade
-----------------------------------
-
-Tests for `shade` module.
-"""
-
+import shade
from shade.tests import base
class TestShade(base.TestCase):
- def test_something(self):
- pass
+ def test_openstack_cloud(self):
+ self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud) |
437d495ba310ab2deee4a5c0f81e61228f2b6503 | yunity/resources/tests/integration/test_chat__rename_chat_succeeds/response.py | yunity/resources/tests/integration/test_chat__rename_chat_succeeds/response.py | from .initial_data import users
from yunity.utils.tests.comparison import DeepMatcher
response = {
"http_status": 201,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name",
"message": {
"content": "Hello user 1",
"sender": users[0].id,
"created_at": DeepMatcher.DATETIME_AROUND_NOW,
"id": "AnyInt",
"type": "TEXT"
},
"id": "AnyInt"
}
}
| from .initial_data import users
from yunity.utils.tests.comparison import DeepMatcher
response = {
"http_status": 200,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name",
"message": {
"content": "Hello user 1",
"sender": users[0].id,
"created_at": DeepMatcher.DATETIME_AROUND_NOW,
"id": "AnyInt",
"type": "TEXT"
},
"id": "AnyInt"
}
}
| Update expected http status code in test | Update expected http status code in test
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend | ---
+++
@@ -2,7 +2,7 @@
from yunity.utils.tests.comparison import DeepMatcher
response = {
- "http_status": 201,
+ "http_status": 200,
"response": {
"participants": [users[0].id, users[1].id, users[2].id],
"name": "New funny name", |
3f29248fc8159030417750e900a0e4c940883b4e | conf/models.py | conf/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneToOneField(Site, related_name='conf',
on_delete=models.CASCADE)
color = models.CharField(max_length=5, blank=True)
def __str__(self):
return 'Configuration'
@receiver(post_save, sender=Site)
def create_conf(sender, instance, created, **kwargs):
if created:
Conf.objects.create(site=instance)
@receiver(post_save, sender=Site)
def save_conf(sender, instance, **kwargs):
instance.conf.save()
class SitePermission(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
sites = models.ManyToManyField('sites.Site', blank=True)
objects = models.Manager()
class Meta:
verbose_name = 'Site permission'
verbose_name_plural = 'Site permissions'
def __str__(self):
return 'Site permissions for {}'.format(self.user)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneToOneField(Site, related_name='conf',
on_delete=models.CASCADE)
color = models.CharField(max_length=5, blank=True)
class Meta:
verbose_name = 'Configuration'
verbose_name_plural = 'Configuration'
def __str__(self):
return 'Configuration for {}'.format(self.site.name)
@receiver(post_save, sender=Site)
def create_conf(sender, instance, created, **kwargs):
if created:
Conf.objects.create(site=instance)
@receiver(post_save, sender=Site)
def save_conf(sender, instance, **kwargs):
instance.conf.save()
class SitePermission(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
sites = models.ManyToManyField('sites.Site', blank=True)
objects = models.Manager()
class Meta:
verbose_name = 'Site permission'
verbose_name_plural = 'Site permissions'
def __str__(self):
return 'Site permissions for {}'.format(self.user)
| Add verbose name to Conf model. | Add verbose name to Conf model.
| Python | bsd-2-clause | overshard/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,muhleder/timestrap,cdubz/timestrap | ---
+++
@@ -13,8 +13,12 @@
on_delete=models.CASCADE)
color = models.CharField(max_length=5, blank=True)
+ class Meta:
+ verbose_name = 'Configuration'
+ verbose_name_plural = 'Configuration'
+
def __str__(self):
- return 'Configuration'
+ return 'Configuration for {}'.format(self.site.name)
@receiver(post_save, sender=Site) |
5536a2f330861631e411a064c9544ab732f0917a | dataproperty/_align.py | dataproperty/_align.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align:
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
return self.__align_string
def __init__(self, code, string):
self.__align_code = code
self.__align_string = string
def __repr__(self):
return self.align_string
AUTO = __AlignData(1 << 0, "auto")
LEFT = __AlignData(1 << 1, "left")
RIGHT = __AlignData(1 << 2, "right")
CENTER = __AlignData(1 << 3, "center")
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align(object):
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
return self.__align_string
def __init__(self, code, string):
self.__align_code = code
self.__align_string = string
def __repr__(self):
return self.align_string
AUTO = __AlignData(1 << 0, "auto")
LEFT = __AlignData(1 << 1, "left")
RIGHT = __AlignData(1 << 2, "right")
CENTER = __AlignData(1 << 3, "center")
| Change old style class defined to new style class definition | Change old style class defined to new style class definition
| Python | mit | thombashi/DataProperty | ---
+++
@@ -7,7 +7,7 @@
from __future__ import unicode_literals
-class Align:
+class Align(object):
class __AlignData(object):
|
b9b4089fcd7f26ebf339c568ba6454d538a1813e | zk_shell/cli.py | zk_shell/cli.py | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| Handle IOError in run_once mode so paging works | Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <f25f6873bbbde69f1fe653b3e6bd40d543b8d0e0@itevenworks.net>
| Python | apache-2.0 | harlowja/zk_shell,harlowja/zk_shell,rgs1/zk_shell,rgs1/zk_shell | ---
+++
@@ -24,7 +24,10 @@
setup_readline=params.run_once == "")
if params.run_once != "":
- sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ try:
+ sys.exit(0 if s.onecmd(params.run_once) == None else 1)
+ except IOError:
+ sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True |
623b170985a69a713db2d3c4887ed3b2ed8dc368 | feincms_extensions/content_types.py | feincms_extensions/content_types.py | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {'content_type': 'rich-text', 'html': self.text}
def mediafile_data(mediafile):
"""Return json serializable data for the mediafile."""
if mediafile is None:
return None
return {
'url': mediafile.file.url,
'type': mediafile.type,
'created': mediafile.created,
'copyright': mediafile.copyright,
'file_size': mediafile.file_size,
}
class JsonSectionContent(SectionContent):
class Meta(SectionContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'content_type': 'section',
'title': self.title,
'html': self.richtext,
'mediafile': mediafile_data(self.mediafile),
}
class JsonMediaFileContent(MediaFileContent):
class Meta(MediaFileContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
data = mediafile_data(self.mediafile)
data['content_type'] = 'media-file'
return data
| from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'content_type': 'rich-text',
'html': self.text,
'id': self.pk,
}
def mediafile_data(mediafile):
"""Return json serializable data for the mediafile."""
if mediafile is None:
return None
return {
'url': mediafile.file.url,
'type': mediafile.type,
'created': mediafile.created,
'copyright': mediafile.copyright,
'file_size': mediafile.file_size,
}
class JsonSectionContent(SectionContent):
class Meta(SectionContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
'id': self.pk,
'content_type': 'section',
'title': self.title,
'html': self.richtext,
'mediafile': mediafile_data(self.mediafile),
}
class JsonMediaFileContent(MediaFileContent):
class Meta(MediaFileContent.Meta):
abstract = True
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
data = mediafile_data(self.mediafile)
data['content_type'] = 'media-file'
data['id'] = self.pk
return data
| Add id to json content types | Add id to json content types
Tests will probably fail! | Python | bsd-2-clause | incuna/feincms-extensions,incuna/feincms-extensions | ---
+++
@@ -9,7 +9,11 @@
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
- return {'content_type': 'rich-text', 'html': self.text}
+ return {
+ 'content_type': 'rich-text',
+ 'html': self.text,
+ 'id': self.pk,
+ }
def mediafile_data(mediafile):
@@ -32,6 +36,7 @@
def json(self, **kwargs):
"""Return a json serializable dictionary containing the content."""
return {
+ 'id': self.pk,
'content_type': 'section',
'title': self.title,
'html': self.richtext,
@@ -47,4 +52,5 @@
"""Return a json serializable dictionary containing the content."""
data = mediafile_data(self.mediafile)
data['content_type'] = 'media-file'
+ data['id'] = self.pk
return data |
45ee26fae4a8d31b66e3307c0ab4aed21678b4b6 | scrubadub/filth/named_entity.py | scrubadub/filth/named_entity.py | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
self.type = "{}_{}".format(self.type, label).lower()
| from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
self.label = label.lower()
| Revert NamedEntityFilth name because it was a bad idea | Revert NamedEntityFilth name because it was a bad idea
| Python | mit | deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub | ---
+++
@@ -9,4 +9,4 @@
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
- self.type = "{}_{}".format(self.type, label).lower()
+ self.label = label.lower() |
6c0e6e79c05b95001ad4c7c1f6ab3b505ffbd6a5 | examples/comparator_example.py | examples/comparator_example.py | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['file_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexObjectType': ['name']}
# Parse in the input Bundle documents and create their python-maec Bundle class representations
bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml"))
bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml"))
# Perform the comparison and get the results
comparison_results = Bundle.compare([bundle1, bundle2], match_on = match_on_dictionary, case_sensitive = False)
# Pretty print the common and unique Objects
print "******Common Objects:*******\n"
pprint.pprint(comparison_results.get_common())
print "****************************"
print "******Unique Objects:*******\n"
pprint.pprint(comparison_results.get_unique())
print "****************************"
| import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['full_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexObjectType': ['name']}
# Parse in the input Bundle documents and create their python-maec Bundle class representations
bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml"))
bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml"))
# Perform the comparison and get the results
comparison_results = Bundle.compare([bundle1, bundle2], match_on = match_on_dictionary, case_sensitive = False)
# Pretty print the common and unique Objects
print "******Common Objects:*******\n"
pprint.pprint(comparison_results.get_common())
print "****************************"
print "******Unique Objects:*******\n"
pprint.pprint(comparison_results.get_unique())
print "****************************"
| Change comparison parameter in example | Change comparison parameter in example
| Python | bsd-3-clause | MAECProject/python-maec | ---
+++
@@ -2,12 +2,12 @@
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
-match_on_dictionary = {'FileObjectType': ['file_name'],
+match_on_dictionary = {'FileObjectType': ['full_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexObjectType': ['name']}
# Parse in the input Bundle documents and create their python-maec Bundle class representations
-bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml"))
-bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml"))
+bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml"))
+bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml"))
# Perform the comparison and get the results
comparison_results = Bundle.compare([bundle1, bundle2], match_on = match_on_dictionary, case_sensitive = False)
# Pretty print the common and unique Objects |
c3e034de03ee45bb161c06bcff870839f9ed4d4b | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import patterns, url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | Remove reference to deprecated "patterns" function. | Remove reference to deprecated "patterns" function.
This function is no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | ---
+++
@@ -1,4 +1,4 @@
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
|
18fec1124bb86f90183350e7b9c86eb946a01884 | whatchanged/main.py | whatchanged/main.py | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if sys.argv < 3:
print('Usage: %s <module1> <module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3]
diff = set([])
if isdir(old):
assert isdir(new)
for dirpath, dirnames, filenames in walk(new):
for file_ in filenames:
if is_py_file(file_):
new_file = join(dirpath, file_)
old_file = new_file.replace(new, old)
if exists(old_file):
mdiff = diff_files(old_file, new_file)
if mdiff is not None:
diff.add(mdiff)
else:
diff.add(diff_files(old, new))
for module in diff:
print(module)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if len(sys.argv) < 3:
print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3]
diff = set([])
if isdir(old):
assert isdir(new)
for dirpath, dirnames, filenames in walk(new):
for file_ in filenames:
if is_py_file(file_):
new_file = join(dirpath, file_)
old_file = new_file.replace(new, old)
if exists(old_file):
mdiff = diff_files(old_file, new_file)
if mdiff is not None:
diff.add(mdiff)
else:
diff.add(diff_files(old, new))
for module in diff:
print(module)
if __name__ == '__main__':
main()
| Fix minor bug in length comparison. | Fix minor bug in length comparison.
| Python | bsd-2-clause | punchagan/what-changed | ---
+++
@@ -14,8 +14,8 @@
def main():
import sys
- if sys.argv < 3:
- print('Usage: %s <module1> <module2>' % sys.argv[0])
+ if len(sys.argv) < 3:
+ print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3] |
2a08a8a6d5cdac0ddcbaf34977c119c5b75bbe8d | wtforms_webwidgets/__init__.py | wtforms_webwidgets/__init__.py | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
# from .common import *
from .common import CustomWidgetMixin, custom_widget_wrapper, FieldRenderer, MultiField | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
from .common import *
| Revert "Possible fix for docs not rendering auto" | Revert "Possible fix for docs not rendering auto"
This reverts commit 88c3fd3c4b23b12f4b68d3f5a13279870486d4b2.
| Python | mit | nickw444/wtforms-webwidgets | ---
+++
@@ -11,5 +11,4 @@
"""
-# from .common import *
-from .common import CustomWidgetMixin, custom_widget_wrapper, FieldRenderer, MultiField
+from .common import * |
a73dd1859dd21ede778a5404ca073ade0d5ef17c | src/greenmine/urls/__init__.py | src/greenmine/urls/__init__.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.main', namespace='web')),
url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
)
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
from django.views.static import serve
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
urlpatterns += patterns('',
(r'^%s(?P<path>.*)$' % _media_url, serve, {'document_root': settings.MEDIA_ROOT})
)
| # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.main', namespace='web')),
#url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
)
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
from django.views.static import serve
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
urlpatterns += patterns('',
(r'^%s(?P<path>.*)$' % _media_url, serve, {'document_root': settings.MEDIA_ROOT})
)
| Remove redis cache stats url. | Remove redis cache stats url.
| Python | bsd-3-clause | niwinz/Green-Mine,niwinz/Green-Mine,niwinz/Green-Mine,niwinz/Green-Mine | ---
+++
@@ -7,7 +7,7 @@
urlpatterns = patterns('',
url(r'^api/', include('greenmine.urls.api', namespace='api')),
url(r'^', include('greenmine.urls.main', namespace='web')),
- url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
+ #url(r'^redis/status/', include('redis_cache.stats.urls', namespace='redis_cache')),
)
urlpatterns += staticfiles_urlpatterns() |
0e7edc1359726ce3257cf67dbb88408979be6a0b | doc/quickstart/testlibs/LoginLibrary.py | doc/quickstart/testlibs/LoginLibrary.py | import os
import sys
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, password)
def change_password(self, username, old_pwd, new_pwd):
self._run_command('change-password', username, old_pwd, new_pwd)
def attempt_to_login_with_credentials(self, username, password):
self._run_command('login', username, password)
def status_should_be(self, expected_status):
if expected_status != self._status:
raise AssertionError("Expected status to be '%s' but was '%s'"
% (expected_status, self._status))
def _run_command(self, command, *args):
command = '"%s" %s %s' % (self._sut_path, command, ' '.join(args))
process = os.popen(command)
self._status = process.read().strip()
process.close()
| import os
import sys
import subprocess
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, password)
def change_password(self, username, old_pwd, new_pwd):
self._run_command('change-password', username, old_pwd, new_pwd)
def attempt_to_login_with_credentials(self, username, password):
self._run_command('login', username, password)
def status_should_be(self, expected_status):
if expected_status != self._status:
raise AssertionError("Expected status to be '%s' but was '%s'"
% (expected_status, self._status))
def _run_command(self, command, *args):
if not sys.executable:
raise RuntimeError("Could not find Jython installation")
command = [sys.executable, self._sut_path, command] + list(args)
process = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self._status = process.communicate()[0].strip()
| Use subprocess isntead of popen to get Jython working too | Use subprocess isntead of popen to get Jython working too
| Python | apache-2.0 | ldtri0209/robotframework,ldtri0209/robotframework,waldenner/robotframework,waldenner/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,fiuba08/robotframework,fiuba08/robotframework,ldtri0209/robotframework | ---
+++
@@ -1,5 +1,6 @@
import os
import sys
+import subprocess
class LoginLibrary:
@@ -24,7 +25,9 @@
% (expected_status, self._status))
def _run_command(self, command, *args):
- command = '"%s" %s %s' % (self._sut_path, command, ' '.join(args))
- process = os.popen(command)
- self._status = process.read().strip()
- process.close()
+ if not sys.executable:
+ raise RuntimeError("Could not find Jython installation")
+ command = [sys.executable, self._sut_path, command] + list(args)
+ process = subprocess.Popen(command, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+ self._status = process.communicate()[0].strip() |
ea3f4934ffa8b88d8716f6550134c37e300c4003 | sqlitebiter/_const.py | sqlitebiter/_const.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "table not found in {}"
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "convertible table not found in {}"
| Modify a log message template | Modify a log message template
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter | ---
+++
@@ -11,4 +11,4 @@
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
-TABLE_NOT_FOUND_MSG_FORMAT = "table not found in {}"
+TABLE_NOT_FOUND_MSG_FORMAT = "convertible table not found in {}" |
df6375c952f0681a3f66596ca77701db8a193b6b | flake8/tests/test_mccabe.py | flake8/tests/test_mccabe.py | import unittest
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # NOQA
from flake8.mccabe import get_code_complexity
_GLOBAL = """\
for i in range(10):
pass
def a():
def b():
def c():
pass
c()
b()
"""
class McCabeTest(unittest.TestCase):
def setUp(self):
self.old = sys.stdout
self.out = sys.stdout = StringIO()
def tearDown(self):
sys.sdtout = self.old
def test_sample(self):
self.assertEqual(get_code_complexity(_GLOBAL, 1), 2)
self.out.seek(0)
res = self.out.read().strip().split('\n')
wanted = ["stdin:5:1: W901 'a' is too complex (4)",
"stdin:2:1: W901 'Loop 2' is too complex (2)"]
self.assertEqual(res, wanted)
| import unittest
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # NOQA
from flake8.mccabe import get_code_complexity
_GLOBAL = """\
for i in range(10):
pass
def a():
def b():
def c():
pass
c()
b()
"""
class McCabeTest(unittest.TestCase):
def setUp(self):
self.old = sys.stdout
self.out = sys.stdout = StringIO()
def tearDown(self):
sys.sdtout = self.old
def test_sample(self):
self.assertEqual(get_code_complexity(_GLOBAL, 1), 2)
self.out.seek(0)
res = self.out.read().strip().split('\n')
wanted = ["stdin:5:1: C901 'a' is too complex (4)",
"stdin:2:1: C901 'Loop 2' is too complex (2)"]
self.assertEqual(res, wanted)
| Fix the codes in the tests | Fix the codes in the tests
| Python | mit | wdv4758h/flake8,lericson/flake8 | ---
+++
@@ -36,6 +36,6 @@
self.assertEqual(get_code_complexity(_GLOBAL, 1), 2)
self.out.seek(0)
res = self.out.read().strip().split('\n')
- wanted = ["stdin:5:1: W901 'a' is too complex (4)",
- "stdin:2:1: W901 'Loop 2' is too complex (2)"]
+ wanted = ["stdin:5:1: C901 'a' is too complex (4)",
+ "stdin:2:1: C901 'Loop 2' is too complex (2)"]
self.assertEqual(res, wanted) |
15490a05696e5e37aa98af905669967fe406eb1d | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['localeurl']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['localeurl']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
| Python | mit | simonluijk/django-localeurl,jmagnusson/django-localeurl | ---
+++
@@ -10,6 +10,7 @@
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
+ 'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
) |
4e6ee7ed1d0e6cc105dad537dc79e12bdcbe9a40 | geozones/factories.py | geozones/factories.py | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
zoom = random.randint(1, 10)
order = factory.Sequence(lambda n: n)
class LocationFactory(factory.Factory):
FACTORY_FOR = Location
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
name = factory.Sequence(lambda n: "Location_%s" % n)
regionId = factory.SubFactory(RegionFactory)
| # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
zoom = random.randint(1, 10)
order = factory.Sequence(lambda n: n)
class LocationFactory(factory.Factory):
FACTORY_FOR = Location
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
description = factory.Sequence(lambda n: "Location_%s" % n)
region = factory.SubFactory(RegionFactory)
| Fix location factory field name | Fix location factory field name
| Python | mit | sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa | ---
+++
@@ -22,5 +22,5 @@
latitude = random.uniform(-90.0, 90.0)
longitude = random.uniform(-180.0, 180.0)
- name = factory.Sequence(lambda n: "Location_%s" % n)
- regionId = factory.SubFactory(RegionFactory)
+ description = factory.Sequence(lambda n: "Location_%s" % n)
+ region = factory.SubFactory(RegionFactory) |
989abb47041e6a172765453c750c31144a92def5 | doc/rst2html-manual.py | doc/rst2html-manual.py | #!/usr/bin/env python3
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
import locale
from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directives import noop
from rst2pdf.roles import counter_off
locale.setlocale(locale.LC_ALL, '')
directives.register_directive('code-block', code_block.code_block_directive)
directives.register_directive('oddeven', noop.noop_directive)
roles.register_canonical_role('counter', counter_off.counter_fn)
description = (
'Generates (X)HTML documents from standalone reStructuredText '
'sources. ' + default_description
)
publish_cmdline(writer_name='html', description=description)
| #!/usr/bin/env python3
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.
#
# .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
"""
A version of rst2html5 with support for rst2pdf's custom roles/directives.
"""
import locale
from docutils.core import default_description
from docutils.core import publish_cmdline
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directives import noop
from rst2pdf.roles import counter_off
locale.setlocale(locale.LC_ALL, '')
directives.register_directive('code-block', code_block.code_block_directive)
directives.register_directive('oddeven', noop.noop_directive)
roles.register_canonical_role('counter', counter_off.counter_fn)
description = (
'Generates HTML5 documents from standalone reStructuredText '
'sources.\n' + default_description
)
publish_cmdline(writer_name='html5', description=description)
| Switch rst2html to HTML5 builder | Switch rst2html to HTML5 builder
This gives a prettier output and every browser in widespread usage has
supported it for years. The license, which was previously missing, is
added.
Signed-off-by: Stephen Finucane <06fa905d7f2aaced6dc72e9511c71a2a51e8aead@that.guru>
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf | ---
+++
@@ -1,12 +1,23 @@
#!/usr/bin/env python3
+# -*- coding: utf8 -*-
+# :Copyright: © 2015 Günter Milde.
+# :License: Released under the terms of the `2-Clause BSD license`_, in short:
+#
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided the copyright
+# notice and this notice are preserved.
+# This file is offered as-is, without any warranty.
+#
+# .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
"""
-A minimal front end to the Docutils Publisher, producing HTML.
+A version of rst2html5 with support for rst2pdf's custom roles/directives.
"""
import locale
-from docutils.core import publish_cmdline, default_description
+from docutils.core import default_description
+from docutils.core import publish_cmdline
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
@@ -22,8 +33,8 @@
roles.register_canonical_role('counter', counter_off.counter_fn)
description = (
- 'Generates (X)HTML documents from standalone reStructuredText '
- 'sources. ' + default_description
+ 'Generates HTML5 documents from standalone reStructuredText '
+ 'sources.\n' + default_description
)
-publish_cmdline(writer_name='html', description=description)
+publish_cmdline(writer_name='html5', description=description) |
8244b6196ce84949e60174f844f80357c8a23478 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
| Migrate from Folly Format to fmt | Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
| Python | apache-2.0 | facebook/wangle,facebook/wangle,facebook/wangle | ---
+++
@@ -7,6 +7,7 @@
import specs.folly as folly
import specs.fizz as fizz
+import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
@@ -22,7 +23,7 @@
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
- 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
+ 'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'), |
18818a8dfebcc44f9e8b582c15d6185f9a7a0c45 | minicms/templatetags/cms.py | minicms/templatetags/cms.py | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks for "%s"' % name
@register.inclusion_tag('minicms/menu.html', takes_context=True)
def show_menu(context, name='menu'):
request = context['request']
menu = []
try:
for line in Block.objects.get(name=name).content.splitlines():
line = line.rstrip()
try:
title, url = line.rsplit(' ', 1)
except:
continue
menu.append({'title': title.strip(), 'url': url})
except Block.DoesNotExist:
pass
# Mark the best-matching URL as active
if request.path != '/':
active = None
active_len = 0
# Normalize path
path = request.path.rstrip('/') + '/'
for item in menu:
# Normalize path
url = item['url'].rstrip('/') + '/'
if path.startswith(url) and len(url) > active_len:
active = item
active_len = len(url)
if active is not None:
active['active'] = True
return {'menu': menu}
| from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks for "%s"' % name
@register.inclusion_tag('minicms/menu.html', takes_context=True)
def show_menu(context, name='menu'):
request = context['request']
menu = []
try:
for line in Block.objects.get(name=name).content.splitlines():
line = line.rstrip()
try:
title, url = line.rsplit(' ', 1)
except:
continue
menu.append({'title': title.strip(), 'url': url})
except Block.DoesNotExist:
pass
# Mark the best-matching URL as active
active = None
active_len = 0
# Normalize path
path = request.path.rstrip('/') + '/'
for item in menu:
# Normalize path
url = item['url'].rstrip('/') + '/'
# Root is only active if you have a "Home" link
if path != '/' and url == '/':
continue
if path.startswith(url) and len(url) > active_len:
active = item
active_len = len(url)
if active is not None:
active['active'] = True
return {'menu': menu}
| Allow "Home" to be active menu item | Allow "Home" to be active menu item
| Python | bsd-3-clause | adieu/allbuttonspressed,adieu/allbuttonspressed | ---
+++
@@ -29,17 +29,19 @@
pass
# Mark the best-matching URL as active
- if request.path != '/':
- active = None
- active_len = 0
+ active = None
+ active_len = 0
+ # Normalize path
+ path = request.path.rstrip('/') + '/'
+ for item in menu:
# Normalize path
- path = request.path.rstrip('/') + '/'
- for item in menu:
- # Normalize path
- url = item['url'].rstrip('/') + '/'
- if path.startswith(url) and len(url) > active_len:
- active = item
- active_len = len(url)
- if active is not None:
- active['active'] = True
+ url = item['url'].rstrip('/') + '/'
+ # Root is only active if you have a "Home" link
+ if path != '/' and url == '/':
+ continue
+ if path.startswith(url) and len(url) > active_len:
+ active = item
+ active_len = len(url)
+ if active is not None:
+ active['active'] = True
return {'menu': menu} |
1b63781465abcc19df053a283148ea48436b8152 | mint/django_rest/rbuilder/inventory/views.py | mint/django_rest/rbuilder/inventory/views.py | #
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#
from django.http import HttpResponse
from django_restapi import resource
from mint.django_rest.deco import requires
from mint.django_rest.rbuilder.inventory import models
from mint.django_rest.rbuilder.inventory import systemdbmgr
MANAGER_CLASS = systemdbmgr.SystemDBManager
class InventoryService(resource.Resource):
def __init__(self):
permitted_methods = ['GET', 'PUT', 'POST', 'DELETE']
resource.Resource.__init__(self, permitted_methods=permitted_methods)
def __call__(self, request, *args, **kw):
self.sysMgr = MANAGER_CLASS(request.cfg)
return resource.Resource.__call__(self, request, *args, **kw)
class InventorySystemsService(InventoryService):
def read(self, request):
systems = self.sysMgr.getSystems()
resp = [str((s.id, s.registrationDate)) for s in systems]
return HttpResponse(str(resp))
@requires('system', models.ManagedSystem)
def create(self, request, system):
return self.sysMgr.registerSystem(system)
def launch(self, instanceId, targetType, targetName):
return self.sysMgr.launchSystem(instanceId, targetType, targetName)
| #
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#
from django.http import HttpResponse
from django_restapi import resource
from mint.django_rest.deco import requires
from mint.django_rest.rbuilder.inventory import models
from mint.django_rest.rbuilder.inventory import systemdbmgr
MANAGER_CLASS = systemdbmgr.SystemDBManager
class InventoryService(resource.Resource):
def __init__(self):
permitted_methods = ['GET', 'PUT', 'POST', 'DELETE']
resource.Resource.__init__(self, permitted_methods=permitted_methods)
def __call__(self, request, *args, **kw):
self.sysMgr = MANAGER_CLASS(request.cfg)
return resource.Resource.__call__(self, request, *args, **kw)
class InventorySystemsService(InventoryService):
def read(self, request):
systems = self.sysMgr.getSystems()
resp = [str((s.id, s.registrationDate)) for s in systems]
return HttpResponse(str(resp))
@requires('system', models.managed_system)
def create(self, request, system):
return self.sysMgr.registerSystem(system)
def launch(self, instanceId, targetType, targetName):
return self.sysMgr.launchSystem(instanceId, targetType, targetName)
| Fix reference to model name | Fix reference to model name
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -30,7 +30,7 @@
resp = [str((s.id, s.registrationDate)) for s in systems]
return HttpResponse(str(resp))
- @requires('system', models.ManagedSystem)
+ @requires('system', models.managed_system)
def create(self, request, system):
return self.sysMgr.registerSystem(system)
|
658587192ad4dbd56a655015bb4225cb965e60fa | neutron_fwaas/tests/tempest_plugin/plugin.py | neutron_fwaas/tests/tempest_plugin/plugin.py | # Copyright (c) 2015 Midokura SARL
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from tempest.test_discover import plugins
class NeutronFWaaSPlugin(plugins.TempestPlugin):
def get_opt_lists(self):
return []
def load_tests(self):
this_dir = os.path.dirname(os.path.abspath(__file__))
# top_level_dir = $(this_dir)/../../..
d = os.path.split(this_dir)[0]
d = os.path.split(d)[0]
top_level_dir = os.path.split(d)[0]
test_dir = os.path.join(top_level_dir,
'neutron_fwaas/tests/tempest_plugin/tests')
return (test_dir, top_level_dir)
def register_opts(self):
return
| # Copyright (c) 2015 Midokura SARL
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from tempest.test_discover import plugins
class NeutronFWaaSPlugin(plugins.TempestPlugin):
def get_opt_lists(self):
return []
def load_tests(self):
this_dir = os.path.dirname(os.path.abspath(__file__))
# top_level_dir = $(this_dir)/../../..
d = os.path.split(this_dir)[0]
d = os.path.split(d)[0]
top_level_dir = os.path.split(d)[0]
test_dir = os.path.join(top_level_dir,
'neutron_fwaas/tests/tempest_plugin/tests')
return (test_dir, top_level_dir)
def register_opts(self, conf):
return
| Fix TempestPlugin to fix gate failure | Fix TempestPlugin to fix gate failure
Currently, tempest plugin for FWaaS is failing due to a wrong
function signature. This patch fixes the function.
Reference:
http://logs.openstack.org/75/247375/5/check/gate-congress-dsvm-api/1c5ed1f/logs/tempest.txt.gz?level=ERROR
Change-Id: Ifb8a0d50a88218b39274798cf8a82dc6f30abd9d
Closes-Bug: #1520098
| Python | apache-2.0 | openstack/neutron-fwaas,openstack/neutron-fwaas | ---
+++
@@ -32,5 +32,5 @@
'neutron_fwaas/tests/tempest_plugin/tests')
return (test_dir, top_level_dir)
- def register_opts(self):
+ def register_opts(self, conf):
return |
2efff9eb852ec2a8f38b4c21ecc6e62898891901 | test/run_tests.py | test/run_tests.py | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path.split(abspath))[:-1]
test_path = join(*test_path)
test_files = [ f.partition('.')[0] for f in listdir(test_path)
if isfile(join(test_path,f)) and f.endswith('.py')]
test_files = filter(lambda f: f.startswith('test'), test_files)
for f in test_files:
print 'Running tests from', f
exec('import ' + f + ' as test')
methods = [ m[0] for m in getmembers(test, isfunction) ]
if 'setup' in methods:
test.setup()
for m in filter(lambda m: m.startswith('test'), methods):
getattr(test, m)()
if 'teardown' in methods:
test.teardown()
if __name__ == '__main__':
main()
| # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
"""
Note: This runs all of the tests. Maybe
this will be removed eventually?
"""
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path.split(abspath))[:-1]
test_path = join(*test_path)
test_files = [ f.partition('.')[0] for f in listdir(test_path)
if isfile(join(test_path,f)) and f.endswith('.py')]
test_files = filter(lambda f: f.startswith('test'), test_files)
for f in test_files:
print 'Running tests from', f
exec('import ' + f + ' as test')
methods = [ m[0] for m in getmembers(test, isfunction) ]
if 'setup' in methods:
test.setup()
for m in filter(lambda m: m.startswith('test'), methods):
getattr(test, m)()
if 'teardown' in methods:
test.teardown()
if __name__ == '__main__':
main()
| Add quick comment to explain test_runner.py | Add quick comment to explain test_runner.py
| Python | apache-2.0 | ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/monary | ---
+++
@@ -1,5 +1,10 @@
# Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
+
+"""
+Note: This runs all of the tests. Maybe
+ this will be removed eventually?
+"""
import os
from os import listdir |
473e0536f388846fccf48ad75100f9e09b574610 | src/texas_choropleth/settings/local.py | src/texas_choropleth/settings/local.py | from .base import *
from .pipeline import *
# Debug Settings
DEBUG = True
TEMPLATE_DEBUG = True
STATIC_ROOT = os.path.join(BASE_DIR, 'static_final')
# TMP Dir for Choropleth Screenshots
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
INVITE_SIGNUP_SUCCESS_URL = "/"
INSTALLED_APPS += (
'debug_toolbar',
)
INTERNAL_IPS = (
'172.17.42.1',
)
# Database Settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'texas_choropleth',
'USER': 'root',
'PASSWORD': 'root',
'HOST': os.environ.get('DB_1_PORT_3306_TCP_ADDR'),
'PORT': os.environ.get('DB_1_PORT_3306_TCP_PORT'),
}
}
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
PIPELINE_ENABLED = False
if PIPELINE_ENABLED:
# Let Pipeline find Compressed files
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
| from .base import *
from .pipeline import *
# Debug Settings
DEBUG = True
TEMPLATE_DEBUG = True
STATIC_ROOT = os.path.join(BASE_DIR, 'static_final')
# TMP Dir for Choropleth Screenshots
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
INVITE_SIGNUP_SUCCESS_URL = "/"
INSTALLED_APPS += (
'debug_toolbar',
)
INTERNAL_IPS = (
'172.17.42.1',
)
# Database Settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'texas_choropleth',
'USER': 'root',
'PASSWORD': 'root',
'HOST': os.environ.get('DB_1_PORT_3306_TCP_ADDR'),
'PORT': os.environ.get('DB_1_PORT_3306_TCP_PORT'),
}
}
IMAGE_EXPORT_TMP_DIR = os.path.join('/', 'tmp')
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
PIPELINE_ENABLED = False
# This allows us to "test" the pipeline configuration
# just by flipping the PIPELINE_ENABLED constant above.
if PIPELINE_ENABLED:
# Let Pipeline find Compressed files
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
| Add comment to clarify the pipeline settings. | Add comment to clarify the pipeline settings. | Python | bsd-3-clause | unt-libraries/texas-choropleth,damonkelley/texas-choropleth,unt-libraries/texas-choropleth,unt-libraries/texas-choropleth,unt-libraries/texas-choropleth,damonkelley/texas-choropleth,damonkelley/texas-choropleth,damonkelley/texas-choropleth | ---
+++
@@ -40,6 +40,8 @@
PIPELINE_ENABLED = False
+# This allows us to "test" the pipeline configuration
+# just by flipping the PIPELINE_ENABLED constant above.
if PIPELINE_ENABLED:
# Let Pipeline find Compressed files
STATICFILES_FINDERS = ( |
3db1ba530ea21baac3f42f56a2a49e85d8d9d18f | machete/issues/tests/test_create.py | machete/issues/tests/test_create.py |
from machete.issues.models import Issue
import unittest
class CreateTest(unittest.TestCase):
pass
| from machete.issues.models import Issue, Severity, Caliber, AssignedTo
import unittest
class CreateTest(unittest.TestCase):
"""Unit-tests around the creation of issues"""
def setUp(self):
super(CreateTest, self).setUp()
def test_should_be_able_to_create_new_issue(self):
"""Should be able to create a new issue and get all related objects"""
issue = Issue.create(description="Hey Jon, here's a bug for ya!")
severity = Severity.create(name="Low Unbreak Now!")
caliber = Caliber.create(issue, severity)
assert issue.severity == severity
assert issue in severity.issues
assert caliber.issue == issue
assert caliber.severity == severity
| Add Unit-Tests Around Issue and Severity Creation and Association | Add Unit-Tests Around Issue and Severity Creation and Association
| Python | bsd-3-clause | rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete | ---
+++
@@ -1,8 +1,21 @@
-
-from machete.issues.models import Issue
+from machete.issues.models import Issue, Severity, Caliber, AssignedTo
import unittest
-class CreateTest(unittest.TestCase):
- pass
+class CreateTest(unittest.TestCase):
+ """Unit-tests around the creation of issues"""
+
+ def setUp(self):
+ super(CreateTest, self).setUp()
+
+ def test_should_be_able_to_create_new_issue(self):
+ """Should be able to create a new issue and get all related objects"""
+ issue = Issue.create(description="Hey Jon, here's a bug for ya!")
+ severity = Severity.create(name="Low Unbreak Now!")
+ caliber = Caliber.create(issue, severity)
+
+ assert issue.severity == severity
+ assert issue in severity.issues
+ assert caliber.issue == issue
+ assert caliber.severity == severity |
f2703d18fc758033e7df582772b3abb973497562 | message/serializers.py | message/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon = serializers.Field(source='location.longitude')
class Meta:
model = Message
fields = ['id', 'title', 'lat', 'lon',]
| # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon = serializers.Field(source='location.longitude')
class Meta:
model = Message
fields = ['id', 'title', 'lat', 'lon', 'messageType']
| Add message type field for api serializer | Add message type field for api serializer
| Python | mit | sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness | ---
+++
@@ -16,4 +16,4 @@
class Meta:
model = Message
- fields = ['id', 'title', 'lat', 'lon',]
+ fields = ['id', 'title', 'lat', 'lon', 'messageType'] |
03d4c298add892e603e48ca35b1a5070f407d6ff | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
| """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
if os.path.getmtime(file) < time.time() - 5 * 60:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
| Remove only those files that were stored 5 minutes ago. | Remove only those files that were stored 5 minutes ago.
[https://cloudbolt.atlassian.net/browse/DEV-12629]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | ---
+++
@@ -4,13 +4,14 @@
from common.methods import set_progress
import glob
import os
+import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
- set_progress("Removing these files {}".format(file))
- os.remove(file)
-
+ if os.path.getmtime(file) < time.time() - 5 * 60:
+ set_progress("Removing these files {}".format(file))
+ os.remove(file)
return "SUCCESS", "", "" |
617919d11722e2cc191f3dcecabfbe08f5d93caf | lib/utils.py | lib/utils.py | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(lst, basestring):
# Convert list to proper format for URL parameters
if len(lst) > 1:
try:
lst = ','.join(lst)[:-1]
except TypeError:
raise Exception(inspect.stack()[1][3] + "expects a comma separated string or list object.")
else:
lst = lst[0]
# Verify that strings passed in have the appropriate format (comma separated string)
elif not match(r'(\w+,)?\w+', lst):
raise Exception("User list not properly formatted: expected list or comma separated string")
return lst
def build_list(comma_sep):
lst = comma_sep.split(',')
lst = [x.strip('_') for x in lst]
print "List = " + str(lst)
return lst
def zero_out(string):
temp = "finding offset"
header = ctypes.string_at(id(temp), sys.getsizeof(temp)).find(temp)
loc = id(string) + header
size = sys.getsizeof(string) - header
logger.info("Clearing 0x%08x size %i bytes" % (loc, size))
ctypes.memset(loc, 0, size) | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(input_lst, basestring):
# Convert list to proper format for URL parameters
if len(input_lst) > 1:
try:
lst = ','.join(input_lst)
except TypeError:
raise Exception(inspect.stack()[1][3] + "expects a comma separated string or list object.")
else:
lst = input_lst[0]
# Verify that strings passed in have the appropriate format (comma separated string)
elif not match(r'(\w+,)?\w+', input_lst):
raise Exception("User list not properly formatted: expected list or comma separated string")
return lst
def build_list(comma_sep):
lst = comma_sep.split(',')
lst = [x.strip('_') for x in lst]
print "List = " + str(lst)
return lst
def zero_out(string):
temp = "finding offset"
header = ctypes.string_at(id(temp), sys.getsizeof(temp)).find(temp)
loc = id(string) + header
size = sys.getsizeof(string) - header
logger.info("Clearing 0x%08x size %i bytes" % (loc, size))
ctypes.memset(loc, 0, size) | Fix issue where last email was truncated | Fix issue where last email was truncated
| Python | unlicense | CodingAnarchy/Amon | ---
+++
@@ -8,19 +8,19 @@
logger = logging.getLogger(__name__)
-def comma_sep_list(lst):
+def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
- if not isinstance(lst, basestring):
+ if not isinstance(input_lst, basestring):
# Convert list to proper format for URL parameters
- if len(lst) > 1:
+ if len(input_lst) > 1:
try:
- lst = ','.join(lst)[:-1]
+ lst = ','.join(input_lst)
except TypeError:
raise Exception(inspect.stack()[1][3] + "expects a comma separated string or list object.")
else:
- lst = lst[0]
+ lst = input_lst[0]
# Verify that strings passed in have the appropriate format (comma separated string)
- elif not match(r'(\w+,)?\w+', lst):
+ elif not match(r'(\w+,)?\w+', input_lst):
raise Exception("User list not properly formatted: expected list or comma separated string")
return lst
|
c79e6b16e29dc0c756bfe82d62b9e01a5702c47f | testanalyzer/pythonanalyzer.py | testanalyzer/pythonanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]",
content))
def get_function_count(self, content):
return len(
re.findall("[^\"](def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:)+[^\"]", content))
| import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content)
matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
return len(matches)
def get_function_count(self, content):
matches = re.findall("\"*def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:\"*", content)
matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
return len(matches)
| Fix counter to ignore quoted lines | Fix counter to ignore quoted lines
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | ---
+++
@@ -4,10 +4,11 @@
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
- return len(
- re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]",
- content))
+ matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content)
+ matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
+ return len(matches)
def get_function_count(self, content):
- return len(
- re.findall("[^\"](def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:)+[^\"]", content))
+ matches = re.findall("\"*def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:\"*", content)
+ matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
+ return len(matches) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.