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 |
|---|---|---|---|---|---|---|---|---|---|---|
2f28efa4bef5759392a46fe3457c87c94911e1ba | tools/api-client/python/interactive_mode.py | tools/api-client/python/interactive_mode.py | # Here's an example of stuff to copy and paste into an interactive Python interpreter to get a connection loaded.
# Or you can load it with 'python -i interactive-mode.py'.
# Set some variables.
bmrc = "~/.bmrc"
site = "www"
bmutilspath = "./lib"
# Import everything, make a connection, and try to log in.
import json
import os
import sys
sys.path.append(os.path.expanduser(bmutilspath).rstrip("/"))
import bmutils
bmconnection = bmutils.BMClientParser(os.path.expanduser(bmrc), site)
if not bmconnection.verify_login():
print "Could not login"
# At this point you can do whatever you want. Here's how to load a game, and print its info in nice JSON.
gamenumber = 3038
game = bmconnection.wrap_load_game_data(gamenumber)
json.dump(game, sys.stdout, indent=1, sort_keys=True)
| # Here's an example of stuff to copy and paste into an interactive Python
# interpreter to get a connection loaded.
# Or you can load it with 'python -i interactive_mode.py'.
# Set some variables.
bmrc = "~/.bmrc"
site = "www"
bmutilspath = "./lib"
# Import everything, make a connection, and try to log in.
import json
import os
import sys
sys.path.append(os.path.expanduser(bmutilspath).rstrip("/"))
import bmutils
bmconnection = bmutils.BMClientParser(os.path.expanduser(bmrc), site)
if not bmconnection.verify_login():
print "Could not login"
# At this point you can do whatever you want. Here's how to load a game,
# and print its info in nice JSON.
gamenumber = 3038
game = bmconnection.wrap_load_game_data(gamenumber)
print json.dumps(game, sys.stdout, indent=1, sort_keys=True)
| Print the JSON dump, so it's prettier. | Print the JSON dump, so it's prettier.
| Python | bsd-3-clause | dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen | ---
+++
@@ -1,5 +1,6 @@
-# Here's an example of stuff to copy and paste into an interactive Python interpreter to get a connection loaded.
-# Or you can load it with 'python -i interactive-mode.py'.
+# Here's an example of stuff to copy and paste into an interactive Python
+# interpreter to get a connection loaded.
+# Or you can load it with 'python -i interactive_mode.py'.
# Set some variables.
@@ -18,9 +19,10 @@
if not bmconnection.verify_login():
print "Could not login"
-# At this point you can do whatever you want. Here's how to load a game, and print its info in nice JSON.
+# At this point you can do whatever you want. Here's how to load a game,
+# and print its info in nice JSON.
gamenumber = 3038
game = bmconnection.wrap_load_game_data(gamenumber)
-json.dump(game, sys.stdout, indent=1, sort_keys=True)
+print json.dumps(game, sys.stdout, indent=1, sort_keys=True) |
db8dea37028432c89e098728970fbaa265e49359 | bookmarks/core/models.py | bookmarks/core/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from taggit.managers import TaggableManager
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
description = models.TextField(blank=True, null=True)
date_added = models.DateTimeField(default=timezone.now, blank=True)
tags = TaggableManager(blank=True)
private = models.BooleanField(default=False)
url = models.URLField()
def __unicode__(self):
return "{}: {} [{}]".format(
self.pk,
self.title[:40],
self.date_added
)
| from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from taggit.managers import TaggableManager
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
description = models.TextField(blank=True, null=True)
date_added = models.DateTimeField(default=timezone.now, blank=True)
tags = TaggableManager(blank=True)
private = models.BooleanField(default=False)
url = models.URLField(max_length=500)
def __unicode__(self):
return "{}: {} [{}]".format(
self.pk,
self.title[:40],
self.date_added
)
| Increase max length of url field. | Increase max length of url field.
| Python | mit | tom-henderson/bookmarks,tom-henderson/bookmarks,tom-henderson/bookmarks | ---
+++
@@ -12,7 +12,7 @@
date_added = models.DateTimeField(default=timezone.now, blank=True)
tags = TaggableManager(blank=True)
private = models.BooleanField(default=False)
- url = models.URLField()
+ url = models.URLField(max_length=500)
def __unicode__(self):
return "{}: {} [{}]".format( |
17c81bb4acb51907f6a4df9a1a436611e730c15d | test/geocoders/teleport.py | test/geocoders/teleport.py | # -*- coding: UTF-8 -*-
from geopy.geocoders import Teleport
from test.geocoders.util import GeocoderTestBase
class TeleportTestCaseUnitTest(GeocoderTestBase):
def test_user_agent_custom(self):
geocoder = Teleport(
user_agent='my_user_agent/1.0'
)
self.assertEqual(geocoder.headers['User-Agent'], 'my_user_agent/1.0')
class TeleportTestCase(GeocoderTestBase):
@classmethod
def setUpClass(cls):
cls.delta = 0.04
def test_unicode_name(self):
"""
Teleport.geocode unicode
"""
# work around ConfigurationError raised in GeoNames init
self.geocoder = Teleport()
self.geocode_run(
{"query": "New York, NY"},
{"latitude": 40.71427, "longitude": -74.00597},
)
def test_reverse(self):
"""
Teleport.reverse
"""
# work around ConfigurationError raised in GeoNames init
self.geocoder = Teleport()
self.reverse_run(
{"query": "40.71427, -74.00597"},
{"latitude": 40.71427, "longitude": -74.00597,
"address": "New York City, New York, United States"},
)
| # -*- coding: UTF-8 -*-
from geopy.geocoders import Teleport
from test.geocoders.util import GeocoderTestBase
class TeleportTestCaseUnitTest(GeocoderTestBase):
def test_user_agent_custom(self):
geocoder = Teleport(
user_agent='my_user_agent/1.0'
)
self.assertEqual(geocoder.headers['User-Agent'], 'my_user_agent/1.0')
class TeleportTestCase(GeocoderTestBase):
@classmethod
def setUpClass(cls):
cls.delta = 0.04
def test_unicode_name(self):
"""
Teleport.geocode unicode
"""
# work around ConfigurationError raised in GeoNames init
self.geocoder = Teleport(scheme='http')
self.geocode_run(
{"query": "New York, NY"},
{"latitude": 40.71427, "longitude": -74.00597},
)
def test_reverse(self):
"""
Teleport.reverse
"""
# work around ConfigurationError raised in GeoNames init
self.geocoder = Teleport(scheme='http')
self.reverse_run(
{"query": "40.71427, -74.00597"},
{"latitude": 40.71427, "longitude": -74.00597,
"address": "New York City, New York, United States"},
)
| Use http scheme to reduce test times | Use http scheme to reduce test times
| Python | mit | magnushiie/geopy,magnushiie/geopy | ---
+++
@@ -23,7 +23,7 @@
Teleport.geocode unicode
"""
# work around ConfigurationError raised in GeoNames init
- self.geocoder = Teleport()
+ self.geocoder = Teleport(scheme='http')
self.geocode_run(
{"query": "New York, NY"},
{"latitude": 40.71427, "longitude": -74.00597},
@@ -34,7 +34,7 @@
Teleport.reverse
"""
# work around ConfigurationError raised in GeoNames init
- self.geocoder = Teleport()
+ self.geocoder = Teleport(scheme='http')
self.reverse_run(
{"query": "40.71427, -74.00597"},
{"latitude": 40.71427, "longitude": -74.00597, |
d29e87eeb062df4d52c0c744919be4cae770fc2c | testing/config/settings/__init__.py | testing/config/settings/__init__.py | # include settimgs from daiquiri
from daiquiri.core.settings.django import *
from daiquiri.core.settings.celery import *
from daiquiri.core.settings.daiquiri import *
from daiquiri.core.settings.logging import *
from daiquiri.core.settings.vendor import *
from daiquiri.archive.settings import *
from daiquiri.auth.settings import *
from daiquiri.conesearch.settings import *
from daiquiri.cutout.settings import *
from daiquiri.files.settings import *
from daiquiri.meetings.settings import *
from daiquiri.metadata.settings import *
from daiquiri.oai.settings import *
from daiquiri.query.settings import *
from daiquiri.serve.settings import *
from daiquiri.stats.settings import *
from daiquiri.tap.settings import *
from daiquiri.wordpress.settings import *
# override settings from base.py (which is checked in to git)
try:
from .base import *
except ImportError:
pass
# override settings from local.py (which is not checked in to git)
try:
from .local import *
except ImportError:
pass
| # include settimgs from daiquiri
from daiquiri.core.settings.django import *
from daiquiri.core.settings.celery import *
from daiquiri.core.settings.daiquiri import *
from daiquiri.core.settings.logging import *
from daiquiri.core.settings.vendor import *
from daiquiri.archive.settings import *
from daiquiri.auth.settings import *
from daiquiri.conesearch.settings import *
from daiquiri.cutout.settings import *
from daiquiri.files.settings import *
from daiquiri.meetings.settings import *
from daiquiri.metadata.settings import *
from daiquiri.oai.settings import *
from daiquiri.query.settings import *
from daiquiri.registry.settings import *
from daiquiri.serve.settings import *
from daiquiri.stats.settings import *
from daiquiri.tap.settings import *
from daiquiri.wordpress.settings import *
# override settings from base.py (which is checked in to git)
try:
from .base import *
except ImportError:
pass
# override settings from local.py (which is not checked in to git)
try:
from .local import *
except ImportError:
pass
| Add registry settings to testing | Add registry settings to testing
| Python | apache-2.0 | aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri | ---
+++
@@ -14,6 +14,7 @@
from daiquiri.metadata.settings import *
from daiquiri.oai.settings import *
from daiquiri.query.settings import *
+from daiquiri.registry.settings import *
from daiquiri.serve.settings import *
from daiquiri.stats.settings import *
from daiquiri.tap.settings import * |
069d658291276e237ce6304c306a1676ba94a650 | pricing/get-lookup-pricing/get-lookup-pricing.py | pricing/get-lookup-pricing/get-lookup-pricing.py | from twilio.rest import TwilioPricingClient, TwilioLookupsClient
#auth credentials
account_sid = "ACCOUNT_SID"
auth_token = "AUTH_TOKEN"
#Use Lookup API to get country code / MCC / MNC that corresponds to given phone number
phone_number = "+15108675309"
print "Find outbound SMS price to:",phone_number
client = TwilioLookupsClient(account_sid, auth_token)
number= client.phone_numbers.get(phone_number,include_carrier_info=True)
mcc = number.carrier['mobile_country_code']
mnc = number.carrier['mobile_network_code']
country_code = number.country_code
#Use Pricing API to find the matching base/current prices to call that
#particular country / MCC / MNC from local phone number
client = TwilioPricingClient(account_sid, auth_token)
messaging_country = client.messaging_countries().get(country_code)
for c in messaging_country.outbound_sms_prices:
if ((c['mcc'] == mcc) and (c['mnc'] == mnc)):
for p in c['prices']:
if (p['number_type'] == "local"):
print "Country: ",country_code
print "Base Price: ",p['base_price']
print "Current Price: ",p['current_price']
| from twilio.rest import TwilioPricingClient, TwilioLookupsClient
#auth credentials
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "{{ auth_token }}"
#Use Lookup API to get country code / MCC / MNC that corresponds to given phone number
phone_number = "+15108675309"
print "Find outbound SMS price to:",phone_number
client = TwilioLookupsClient(account_sid, auth_token)
number= client.phone_numbers.get(phone_number,include_carrier_info=True)
mcc = number.carrier['mobile_country_code']
mnc = number.carrier['mobile_network_code']
country_code = number.country_code
#Use Pricing API to find the matching base/current prices to call that
#particular country / MCC / MNC from local phone number
client = TwilioPricingClient(account_sid, auth_token)
messaging_country = client.messaging_countries().get(country_code)
for c in messaging_country.outbound_sms_prices:
if ((c['mcc'] == mcc) and (c['mnc'] == mnc)):
for p in c['prices']:
if (p['number_type'] == "local"):
print "Country: ",country_code
print "Base Price: ",p['base_price']
print "Current Price: ",p['current_price']
| Correct errors in pricing snippets | Correct errors in pricing snippets
| Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | ---
+++
@@ -1,8 +1,8 @@
from twilio.rest import TwilioPricingClient, TwilioLookupsClient
#auth credentials
-account_sid = "ACCOUNT_SID"
-auth_token = "AUTH_TOKEN"
+account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+auth_token = "{{ auth_token }}"
#Use Lookup API to get country code / MCC / MNC that corresponds to given phone number
phone_number = "+15108675309" |
c2737cc54eff558b59bfcfac9e1f9772e07a2c6f | examples/python/setup.py | examples/python/setup.py |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '0.2',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '1.0beta5',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
| Make m2sh have the same version number as mongrel2. | Make m2sh have the same version number as mongrel2. | Python | bsd-3-clause | solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2 | ---
+++
@@ -10,7 +10,7 @@
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
- 'version': '0.2',
+ 'version': '1.0beta5',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'], |
f3b87dcad47e77a3383de6fef17080661471a4a3 | facturapdf/generators.py | facturapdf/generators.py | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in flowable['cast'].iteritems():
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | Use dict iteration compatible with Python 2 and 3 | Use dict iteration compatible with Python 2 and 3
| Python | bsd-3-clause | initios/factura-pdf | ---
+++
@@ -20,7 +20,7 @@
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
- for index, cls in flowable['cast'].iteritems():
+ for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args) |
00bedbd90c46d4cabcd22748bee047732d29417c | members/guardianfetch.py | members/guardianfetch.py | #!/usr/bin/python
import urllib, re
base = 'http://politics.guardian.co.uk'
out = open('../rawdata/mpinfo/guardian-mpsurls2005.txt', 'w')
for i in range(-272, -266):
url = '%s/person/browse/mps/az/0,,%d,00.html' % (base, i)
fp = urllib.urlopen(url)
index = fp.read()
fp.close()
m = re.findall('<a href="(/person/0[^"]*)">(.*?), (.*?)</a>', index)
for match in m:
url = '%s%s' % (base, match[0])
name = '%s %s' % (match[2], match[1])
fp = urllib.urlopen(url)
person = fp.read()
fp.close()
cons = re.search('Member of Parliament for <a href="(/hoc/constituency/[^"]*)">(.*?)</a>', person)
consurl, consname = cons.groups()
consurl = '%s%s' % (base, consurl)
out.write('%s\t%s\t%s\t%s\n' % (name, consname, url, consurl))
| #!/usr/bin/python
import sys
sys.path.append("../pyscraper")
import urllib, re
base = 'http://politics.guardian.co.uk'
from BeautifulSoup import BeautifulSoup
out = open('../rawdata/mpinfo/guardian-mpsurls2005.txt', 'w')
for i in range(-272, -266):
url = '%s/person/browse/mps/az/0,,%d,00.html' % (base, i)
fp = urllib.urlopen(url)
index = fp.read()
fp.close()
m = re.findall('<a href="(/person/0[^"]*)">(.*?), (.*?)</a>', index)
for match in m:
url = '%s%s' % (base, match[0])
name = '%s %s' % (match[2], match[1])
fp = urllib.urlopen(url)
person = fp.read()
mpurl = fp.geturl()
print "Parsing %s" % (mpurl)
fp.close()
soup = BeautifulSoup(person)
cons_div = soup.find('div', attrs={'id':'constituency'})
cons_link = cons_div.a
# first link in the constituency div
cons = re.search('<a href="([^"]*)">(.*?)</a>', str(cons_link))
consurl, consname = cons.groups()
out.write('%s\t%s\t%s\t%s\n' % (name, consname, mpurl, consurl))
| Update for new person page format | Update for new person page format
git-svn-id: 285608342ca21a36fbe1c940a1767f009072314d@8369 9cc54934-f9f6-0310-8a8d-e8e977684441
| Python | agpl-3.0 | henare/parlparse,henare/parlparse,spudmind/parlparse,spudmind/parlparse,henare/parlparse,spudmind/parlparse,spudmind/parlparse,henare/parlparse,henare/parlparse,spudmind/parlparse | ---
+++
@@ -1,8 +1,9 @@
#!/usr/bin/python
-
+import sys
+sys.path.append("../pyscraper")
import urllib, re
base = 'http://politics.guardian.co.uk'
-
+from BeautifulSoup import BeautifulSoup
out = open('../rawdata/mpinfo/guardian-mpsurls2005.txt', 'w')
for i in range(-272, -266):
url = '%s/person/browse/mps/az/0,,%d,00.html' % (base, i)
@@ -15,9 +16,14 @@
name = '%s %s' % (match[2], match[1])
fp = urllib.urlopen(url)
person = fp.read()
- fp.close()
- cons = re.search('Member of Parliament for <a href="(/hoc/constituency/[^"]*)">(.*?)</a>', person)
+ mpurl = fp.geturl()
+ print "Parsing %s" % (mpurl)
+ fp.close()
+ soup = BeautifulSoup(person)
+ cons_div = soup.find('div', attrs={'id':'constituency'})
+ cons_link = cons_div.a
+ # first link in the constituency div
+ cons = re.search('<a href="([^"]*)">(.*?)</a>', str(cons_link))
consurl, consname = cons.groups()
- consurl = '%s%s' % (base, consurl)
- out.write('%s\t%s\t%s\t%s\n' % (name, consname, url, consurl))
+ out.write('%s\t%s\t%s\t%s\n' % (name, consname, mpurl, consurl))
|
3b8dd8c41e78146a1d3914e03f99ce89b1624d26 | modules/pipestrconcat.py | modules/pipestrconcat.py | # pipestrconcat.py #aka stringbuilder
#
from pipe2py import util
def pipe_strconcat(context, _INPUT, conf, **kwargs):
"""This source builds a string.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
conf:
part -- parts
Yields (_OUTPUT):
string
"""
for item in _INPUT:
s = ""
for part in conf['part']:
if "subkey" in part:
s += item[part['subkey']] #todo: use this subkey check anywhere we can embed a module
else:
s += util.get_value(part, kwargs)
yield s
| # pipestrconcat.py #aka stringbuilder
#
from pipe2py import util
def pipe_strconcat(context, _INPUT, conf, **kwargs):
"""This source builds a string.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
conf:
part -- parts
Yields (_OUTPUT):
string
"""
if not isinstance(conf['part'], list): #todo do we need to do this anywhere else?
conf['part'] = [conf['part']]
for item in _INPUT:
s = ""
for part in conf['part']:
if "subkey" in part:
s += item[part['subkey']] #todo: use this subkey check anywhere we can embed a module
else:
s += util.get_value(part, kwargs)
yield s
| Allow singleton conf['part'] for strconcat | Allow singleton conf['part'] for strconcat
| Python | mit | nerevu/riko,nerevu/riko | ---
+++
@@ -15,6 +15,9 @@
Yields (_OUTPUT):
string
"""
+ if not isinstance(conf['part'], list): #todo do we need to do this anywhere else?
+ conf['part'] = [conf['part']]
+
for item in _INPUT:
s = ""
for part in conf['part']: |
d9971a831a622f606d62825957c970a791d53d75 | symaps_proxies/settings/base.py | symaps_proxies/settings/base.py | # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True
},
{
'CidrBlock': '16.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
]
}
] | # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True,
'subnets': [
{
'CidrBlock': '15.0.0.0/24',
},
{
'CidrBlock': '15.0.1.0/24',
}
]
}
]
| Simplify the aws vpcs settings for testing | Simplify the aws vpcs settings for testing
| Python | mit | davidlonjon/aws-proxies,davidlonjon/aws-proxies | ---
+++
@@ -9,14 +9,13 @@
'Value': 'symaps-prod-proxies'
}
],
- 'create_internet_gateway': True
- },
- {
- 'CidrBlock': '16.0.0.0/16',
- 'Tags': [
+ 'create_internet_gateway': True,
+ 'subnets': [
{
- 'Key': 'Name',
- 'Value': 'symaps-prod-proxies'
+ 'CidrBlock': '15.0.0.0/24',
+ },
+ {
+ 'CidrBlock': '15.0.1.0/24',
}
]
} |
fe870120076454e1baf72831e4346e9ad575771b | applications/urls.py | applications/urls.py | from django.conf.urls import url
from applications import views
app_name = 'application'
urlpatterns = [
# url(r'^notyet$', views.no_application, name='no_application'),
# url(r'^$', views.project_application_form, name='project_application_form'),
url(r'^$', views.application_form, name='application_form'),
url(r'^done/$', views.application_sent, name="application_sent")
]
| from django.conf.urls import url
from applications import views
app_name = 'application'
urlpatterns = [
# url(r'^notyet$', views.no_application, name='no_application'),
# url(r'^$', views.project_application_form, name='project_application_form'),
url(r'^$', views.application_form, name='application_form'),
# url(r'^done/$', views.application_sent, name="application_sent")
]
| Comment out url for application sent. | Comment out url for application sent.
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website | ---
+++
@@ -7,5 +7,5 @@
# url(r'^notyet$', views.no_application, name='no_application'),
# url(r'^$', views.project_application_form, name='project_application_form'),
url(r'^$', views.application_form, name='application_form'),
- url(r'^done/$', views.application_sent, name="application_sent")
+ # url(r'^done/$', views.application_sent, name="application_sent")
] |
830f8281f80f363be8433be562ea52b817ceefe3 | engine/extensions/pychan/tools.py | engine/extensions/pychan/tools.py | # coding: utf-8
### Functools ###
def applyOnlySuitable(func,**kwargs):
"""
This nifty little function takes another function and applies it to a dictionary of
keyword arguments. If the supplied function does not expect one or more of the
keyword arguments, these are silently discarded. The result of the application is returned.
This is useful to pass information to callbacks without enforcing a particular signature.
"""
if hasattr(func,'im_func'):
code = func.im_func.func_code
varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance
else:
code = func.func_code
varnames = code.co_varnames[0:code.co_argcount]
#http://docs.python.org/lib/inspect-types.html
if code.co_flags & 8:
return func(**kwargs)
for name,value in kwargs.items():
if name not in varnames:
del kwargs[name]
return func(**kwargs)
| # coding: utf-8
### Functools ###
def applyOnlySuitable(func,**kwargs):
"""
This nifty little function takes another function and applies it to a dictionary of
keyword arguments. If the supplied function does not expect one or more of the
keyword arguments, these are silently discarded. The result of the application is returned.
This is useful to pass information to callbacks without enforcing a particular signature.
"""
if hasattr(func,'im_func'):
code = func.im_func.func_code
varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance
else:
code = func.func_code
varnames = code.co_varnames[0:code.co_argcount]
#http://docs.python.org/lib/inspect-types.html
if code.co_flags & 8:
return func(**kwargs)
for name,value in kwargs.items():
if name not in varnames:
del kwargs[name]
return func(**kwargs)
def callbackWithArguments(callback,*args,**kwargs):
"""
Curries a function with extra arguments to
create a suitable callback.
If you don't know what this means, don't worry.
It is designed for the case where you need
different buttons to execute basically the same code
with different argumnets.
Usage::
# The target callback
def printStuff(text):
print text
# Mapping the events
gui.mapEvents({
'buttonHello' : callbackWithArguments(printStuff,"Hello"),
'buttonBye' : callbackWithArguments(printStuff,"Adieu")
})
"""
def real_callback():
callback(*args,**kwargs)
return real_callback
| Simplify callback creation with a functional utility function. | PyChan: Simplify callback creation with a functional utility function.
| Python | lgpl-2.1 | cbeck88/fifengine,gravitystorm/fifengine,cbeck88/fifengine,cbeck88/fifengine,fifengine/fifengine,fifengine/fifengine,Niektory/fifengine,gravitystorm/fifengine,fifengine/fifengine,Niektory/fifengine,gravitystorm/fifengine,gravitystorm/fifengine,Niektory/fifengine,cbeck88/fifengine | ---
+++
@@ -23,3 +23,28 @@
if name not in varnames:
del kwargs[name]
return func(**kwargs)
+
+def callbackWithArguments(callback,*args,**kwargs):
+ """
+ Curries a function with extra arguments to
+ create a suitable callback.
+
+ If you don't know what this means, don't worry.
+ It is designed for the case where you need
+ different buttons to execute basically the same code
+ with different argumnets.
+
+ Usage::
+ # The target callback
+ def printStuff(text):
+ print text
+ # Mapping the events
+ gui.mapEvents({
+ 'buttonHello' : callbackWithArguments(printStuff,"Hello"),
+ 'buttonBye' : callbackWithArguments(printStuff,"Adieu")
+ })
+ """
+ def real_callback():
+ callback(*args,**kwargs)
+ return real_callback
+ |
a2274f52e4567de4209e3394060fe62276ad3546 | test/mitmproxy/test_examples.py | test/mitmproxy/test_examples.py | import glob
from mitmproxy import utils, script
from mitmproxy.proxy import config
from . import tservers
def test_load_scripts():
example_dir = utils.Data(__name__).path("../../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
if "har_extractor" in f:
continue
if "flowwriter" in f:
f += " -"
if "iframe_injector" in f:
f += " foo" # one argument required
if "filt" in f:
f += " ~a"
if "modify_response_body" in f:
f += " foo bar" # two arguments required
try:
s = script.Script(f, script.ScriptContext(tmaster)) # Loads the script file.
except Exception as v:
if "ImportError" not in str(v):
raise
else:
s.unload()
| import glob
from mitmproxy import utils, script
from mitmproxy.proxy import config
from netlib import tutils as netutils
from netlib.http import Headers
from . import tservers, tutils
from examples import (
modify_form,
)
def test_load_scripts():
example_dir = utils.Data(__name__).path("../../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
if "har_extractor" in f:
continue
if "flowwriter" in f:
f += " -"
if "iframe_injector" in f:
f += " foo" # one argument required
if "filt" in f:
f += " ~a"
if "modify_response_body" in f:
f += " foo bar" # two arguments required
try:
s = script.Script(f, script.ScriptContext(tmaster)) # Loads the script file.
except Exception as v:
if "ImportError" not in str(v):
raise
else:
s.unload()
def test_modify_form():
form_header = Headers(content_type="application/x-www-form-urlencoded")
flow = tutils.tflow(req=netutils.treq(headers=form_header))
modify_form.request({}, flow)
assert flow.request.urlencoded_form["mitmproxy"] == ["rocks"]
| Add tests for modify_form example | Add tests for modify_form example
| Python | mit | xaxa89/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,gzzhanghao/mitmproxy,Kriechi/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,dwfreed/mitmproxy,mosajjal/mitmproxy,jvillacorta/mitmproxy,gzzhanghao/mitmproxy,mhils/mitmproxy,dwfreed/mitmproxy,tdickers/mitmproxy,cortesi/mitmproxy,mosajjal/mitmproxy,ujjwal96/mitmproxy,dwfreed/mitmproxy,MatthewShao/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,dufferzafar/mitmproxy,StevenVanAcker/mitmproxy,StevenVanAcker/mitmproxy,xaxa89/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,mhils/mitmproxy,fimad/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,cortesi/mitmproxy,zlorb/mitmproxy,gzzhanghao/mitmproxy,dufferzafar/mitmproxy,mhils/mitmproxy,xaxa89/mitmproxy,ujjwal96/mitmproxy,MatthewShao/mitmproxy,jvillacorta/mitmproxy,ujjwal96/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,laurmurclar/mitmproxy,MatthewShao/mitmproxy,jvillacorta/mitmproxy,cortesi/mitmproxy,Kriechi/mitmproxy,tdickers/mitmproxy,cortesi/mitmproxy,MatthewShao/mitmproxy,ddworken/mitmproxy,mitmproxy/mitmproxy,mosajjal/mitmproxy,mitmproxy/mitmproxy,mitmproxy/mitmproxy,vhaupert/mitmproxy,dwfreed/mitmproxy,fimad/mitmproxy,fimad/mitmproxy,tdickers/mitmproxy,zlorb/mitmproxy,xaxa89/mitmproxy,laurmurclar/mitmproxy,dufferzafar/mitmproxy,ddworken/mitmproxy,jvillacorta/mitmproxy,tdickers/mitmproxy,laurmurclar/mitmproxy,fimad/mitmproxy,Kriechi/mitmproxy,dufferzafar/mitmproxy,ujjwal96/mitmproxy,mosajjal/mitmproxy,gzzhanghao/mitmproxy | ---
+++
@@ -1,7 +1,15 @@
import glob
+
from mitmproxy import utils, script
from mitmproxy.proxy import config
-from . import tservers
+from netlib import tutils as netutils
+from netlib.http import Headers
+from . import tservers, tutils
+
+from examples import (
+ modify_form,
+
+)
def test_load_scripts():
@@ -28,3 +36,11 @@
raise
else:
s.unload()
+
+
+def test_modify_form():
+ form_header = Headers(content_type="application/x-www-form-urlencoded")
+ flow = tutils.tflow(req=netutils.treq(headers=form_header))
+ modify_form.request({}, flow)
+ assert flow.request.urlencoded_form["mitmproxy"] == ["rocks"]
+ |
59119f8a3f97b833559404a5f89cc66243fe06ca | opal/tests/test_views.py | opal/tests/test_views.py | """
Unittests for opal.views
"""
from django.test import TestCase
from opal import views
class ColumnContextTestCase(TestCase):
pass
| """
Unittests for opal.views
"""
from opal.core.test import OpalTestCase
from opal import models
from opal import views
class BaseViewTestCase(OpalTestCase):
def setUp(self):
self.patient = models.Patient.objects.create()
self.episode = self.patient.create_episode()
def get_request(self, path):
request = self.rf.get(path)
request.user = self.user
return request
def should_200(self, viewklass, request):
view = viewklass.as_view()
resp = view(request)
self.assertEqual(200, resp.status_code)
class EpisodeListTemplateViewTestCase(BaseViewTestCase):
def test_episode_template_view(self):
request = self.get_request('/episodetemplate')
self.should_200(views.EpisodeListTemplateView, request)
class PatientDetailTemplateViewTestCase(BaseViewTestCase):
def test_patient_detail_template_view(self):
request = self.get_request('/patient_detail_template')
self.should_200(views.PatientDetailTemplateView, request)
class BannedViewTestCase(BaseViewTestCase):
def test_banned_view(self):
request = self.get_request('/banned_passwords')
self.should_200(views.BannedView, request)
| Add some extra View tests | Add some extra View tests
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | ---
+++
@@ -1,9 +1,40 @@
"""
Unittests for opal.views
"""
-from django.test import TestCase
+from opal.core.test import OpalTestCase
+from opal import models
from opal import views
-class ColumnContextTestCase(TestCase):
- pass
+class BaseViewTestCase(OpalTestCase):
+ def setUp(self):
+ self.patient = models.Patient.objects.create()
+ self.episode = self.patient.create_episode()
+
+ def get_request(self, path):
+ request = self.rf.get(path)
+ request.user = self.user
+ return request
+
+ def should_200(self, viewklass, request):
+ view = viewklass.as_view()
+ resp = view(request)
+ self.assertEqual(200, resp.status_code)
+
+
+class EpisodeListTemplateViewTestCase(BaseViewTestCase):
+
+ def test_episode_template_view(self):
+ request = self.get_request('/episodetemplate')
+ self.should_200(views.EpisodeListTemplateView, request)
+
+class PatientDetailTemplateViewTestCase(BaseViewTestCase):
+
+ def test_patient_detail_template_view(self):
+ request = self.get_request('/patient_detail_template')
+ self.should_200(views.PatientDetailTemplateView, request)
+
+class BannedViewTestCase(BaseViewTestCase):
+ def test_banned_view(self):
+ request = self.get_request('/banned_passwords')
+ self.should_200(views.BannedView, request) |
7ddaa5a5f9bee7e21c1221950c50c8688e815e01 | wtforms/ext/sqlalchemy/__init__.py | wtforms/ext/sqlalchemy/__init__.py | import warnings
warnings.warn(
'wtforms.ext.sqlalchemy is deprecated, and will be removed in WTForms 3.0. '
'Instead transition to the excellent WTForms-Alchemy package: '
'https://github.com/kvesteri/wtforms-alchemy',
DeprecationWarning
)
| import warnings
warnings.warn(
'wtforms.ext.sqlalchemy is deprecated, and will be removed in WTForms 3.0. '
'The package has been extracted to a separate package wtforms_sqlalchemy: '
'https://github.com/wtforms/wtforms-sqlalchemy .\n'
'Or alternately, check out the WTForms-Alchemy package which provides declarative mapping and more: '
'https://github.com/kvesteri/wtforms-alchemy',
DeprecationWarning
)
| Add pointer to WTForms-SQLAlchemy in Deprecation | Add pointer to WTForms-SQLAlchemy in Deprecation
Closes #221
| Python | bsd-3-clause | crast/wtforms,cklein/wtforms,wtforms/wtforms | ---
+++
@@ -2,7 +2,9 @@
warnings.warn(
'wtforms.ext.sqlalchemy is deprecated, and will be removed in WTForms 3.0. '
- 'Instead transition to the excellent WTForms-Alchemy package: '
+ 'The package has been extracted to a separate package wtforms_sqlalchemy: '
+ 'https://github.com/wtforms/wtforms-sqlalchemy .\n'
+ 'Or alternately, check out the WTForms-Alchemy package which provides declarative mapping and more: '
'https://github.com/kvesteri/wtforms-alchemy',
DeprecationWarning
) |
b7cee426db61801fd118758bb2f47944f3b8fd37 | binaryornot/check.py | binaryornot/check.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_starting_chunk(filename):
with(filename, 'r') as f:
chunk = open(filename).read(1024)
return chunk
def is_binary_string(bytes_to_check):
"""
:param bytes: A chunk of bytes to check.
:returns: True if appears to be a binary, otherwise False.
"""
textchars = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100)))
result = bytes_to_check.translate(None, textchars)
return bool(result)
def is_binary(filename):
"""
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
"""
chunk = get_starting_chunk(filename)
return is_binary_string(chunk)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_starting_chunk(filename):
with open(filename, 'r') as f:
chunk = f.read(1024)
return chunk
def is_binary_string(bytes_to_check):
"""
:param bytes: A chunk of bytes to check.
:returns: True if appears to be a binary, otherwise False.
"""
textchars = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100)))
result = bytes_to_check.translate(None, textchars)
return bool(result)
def is_binary(filename):
"""
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
"""
chunk = get_starting_chunk(filename)
return is_binary_string(chunk)
| Fix file opening and make tests pass. | Fix file opening and make tests pass.
| Python | bsd-3-clause | hackebrot/binaryornot,0k/binaryornot,hackebrot/binaryornot,hackebrot/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,0k/binaryornot,pombredanne/binaryornot,audreyr/binaryornot | ---
+++
@@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
def get_starting_chunk(filename):
- with(filename, 'r') as f:
- chunk = open(filename).read(1024)
+ with open(filename, 'r') as f:
+ chunk = f.read(1024)
return chunk
|
2be9da941fbbf17a54abd79ecae80d0245c1912e | moulinette/utils/stream.py | moulinette/utils/stream.py | from threading import Thread
from Queue import Queue, Empty
# Read from a stream ---------------------------------------------------
class NonBlockingStreamReader:
"""A non-blocking stream reader
Open a separate thread which reads lines from the stream whenever data
becomes available and stores the data in a queue.
Based on: http://eyalarubas.com/python-subproc-nonblock.html
Keyword arguments:
- stream -- The stream to read from
"""
def __init__(self, stream):
self._s = stream
self._q = Queue()
def _populateQueue(stream, queue):
"""Collect lines from the stream and put them in the queue"""
while True:
line = stream.readline()
if line:
queue.put(line)
else:
break
self._t = Thread(target=_populateQueue, args=(self._s, self._q))
self._t.daemon = True
# Start collecting lines from the stream
self._t.start()
def readline(self, block=False, timeout=None):
"""Read line from the stream
Attempt to pull from the queue the data and return it. If no data is
available or timeout has expired, it returns None.
Keyword arguments:
- block -- If True, block if necessary until data is available
- timeout -- The number of seconds to block
"""
try:
return self._q.get(block=timeout is not None,
timeout=timeout)
except Empty:
return None
def close(self):
"""Close the stream"""
try:
self._s.close()
except IOError:
pass
| import threading
import Queue
# Read from a stream ---------------------------------------------------
class AsynchronousFileReader(threading.Thread):
"""
Helper class to implement asynchronous reading of a file
in a separate thread. Pushes read lines on a queue to
be consumed in another thread.
Based on:
http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading
"""
def __init__(self, fd, queue):
assert isinstance(queue, Queue.Queue)
assert callable(fd.readline)
threading.Thread.__init__(self)
self._fd = fd
self._queue = queue
def run(self):
"""The body of the tread: read lines and put them on the queue."""
for line in iter(self._fd.readline, ''):
self._queue.put(line)
def eof(self):
"""Check whether there is no more content to expect."""
return not self.is_alive() and self._queue.empty()
def join(self, timeout=None, close=True):
"""Close the file and join the thread."""
if close:
self._fd.close()
threading.Thread.join(self, timeout)
def start_async_file_reading(fd):
"""Helper which instantiate and run an AsynchronousFileReader."""
queue = Queue.Queue()
reader = AsynchronousFileReader(fd, queue)
reader.start()
return (reader, queue)
| Use a new asynchronous file reader helper | [ref] Use a new asynchronous file reader helper
| Python | agpl-3.0 | YunoHost/moulinette | ---
+++
@@ -1,59 +1,45 @@
-from threading import Thread
-from Queue import Queue, Empty
+import threading
+import Queue
# Read from a stream ---------------------------------------------------
-class NonBlockingStreamReader:
- """A non-blocking stream reader
+class AsynchronousFileReader(threading.Thread):
+ """
+ Helper class to implement asynchronous reading of a file
+ in a separate thread. Pushes read lines on a queue to
+ be consumed in another thread.
- Open a separate thread which reads lines from the stream whenever data
- becomes available and stores the data in a queue.
-
- Based on: http://eyalarubas.com/python-subproc-nonblock.html
-
- Keyword arguments:
- - stream -- The stream to read from
+ Based on:
+ http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading
"""
- def __init__(self, stream):
- self._s = stream
- self._q = Queue()
+ def __init__(self, fd, queue):
+ assert isinstance(queue, Queue.Queue)
+ assert callable(fd.readline)
+ threading.Thread.__init__(self)
+ self._fd = fd
+ self._queue = queue
- def _populateQueue(stream, queue):
- """Collect lines from the stream and put them in the queue"""
- while True:
- line = stream.readline()
- if line:
- queue.put(line)
- else:
- break
+ def run(self):
+ """The body of the tread: read lines and put them on the queue."""
+ for line in iter(self._fd.readline, ''):
+ self._queue.put(line)
- self._t = Thread(target=_populateQueue, args=(self._s, self._q))
- self._t.daemon = True
- # Start collecting lines from the stream
- self._t.start()
+ def eof(self):
+ """Check whether there is no more content to expect."""
+ return not self.is_alive() and self._queue.empty()
- def readline(self, block=False, timeout=None):
- """Read line from the stream
+ def join(self, timeout=None, close=True):
+ """Close the file and join the thread."""
+ if close:
+ self._fd.close()
+ threading.Thread.join(self, timeout)
- Attempt to pull from the queue the data and return it. If no data is
- available or timeout has expired, it returns None.
- Keyword arguments:
- - block -- If True, block if necessary until data is available
- - timeout -- The number of seconds to block
-
- """
- try:
- return self._q.get(block=timeout is not None,
- timeout=timeout)
- except Empty:
- return None
-
- def close(self):
- """Close the stream"""
- try:
- self._s.close()
- except IOError:
- pass
+def start_async_file_reading(fd):
+ """Helper which instantiate and run an AsynchronousFileReader."""
+ queue = Queue.Queue()
+ reader = AsynchronousFileReader(fd, queue)
+ reader.start()
+ return (reader, queue) |
4c7c1aa8b3bb1994183618ee44f8dd5a89884bfa | awx/sso/strategies/django_strategy.py | awx/sso/strategies/django_strategy.py | # Copyright (c) 2017 Ansible, Inc.
# All Rights Reserved.
from social.strategies.django_strategy import DjangoStrategy
class AWXDjangoStrategy(DjangoStrategy):
"""A DjangoStrategy for python-social-auth containing
fixes and updates from social-app-django
TODO: Revert back to using the default DjangoStrategy after
we upgrade to social-core / social-app-django. We will also
want to ensure we update the SOCIAL_AUTH_STRATEGY setting.
"""
def __init__(self, storage, request=None, tpl=None):
super(AWXDjangoStrategy, self).__init__(storage, tpl)
def request_port(self):
"""Port in use for this request
https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76
"""
try: # django >= 1.9
return self.request.get_port()
except AttributeError: # django < 1.9
host_parts = self.request.get_host().split(':')
try:
return host_parts[1]
except IndexError:
return self.request.META['SERVER_PORT']
| # Copyright (c) 2017 Ansible, Inc.
# All Rights Reserved.
from social.strategies.django_strategy import DjangoStrategy
class AWXDjangoStrategy(DjangoStrategy):
"""A DjangoStrategy for python-social-auth containing
fixes and updates from social-app-django
TODO: Revert back to using the default DjangoStrategy after
we upgrade to social-core / social-app-django. We will also
want to ensure we update the SOCIAL_AUTH_STRATEGY setting.
"""
def request_port(self):
"""Port in use for this request
https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76
"""
try: # django >= 1.9
return self.request.get_port()
except AttributeError: # django < 1.9
host_parts = self.request.get_host().split(':')
try:
return host_parts[1]
except IndexError:
return self.request.META['SERVER_PORT']
| Fix typo in AWXDjangoStrategy constructor | Fix typo in AWXDjangoStrategy constructor
Signed-off-by: Matvey Kruglov <a9c5c297e6de9a9c1390d88b6df170967c0ffb3a@gmail.com>
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx | ---
+++
@@ -13,9 +13,6 @@
want to ensure we update the SOCIAL_AUTH_STRATEGY setting.
"""
- def __init__(self, storage, request=None, tpl=None):
- super(AWXDjangoStrategy, self).__init__(storage, tpl)
-
def request_port(self):
"""Port in use for this request
https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76 |
bab058be7b830a38d75eebf53170a805e726308c | keyring/util/platform.py | keyring/util/platform.py | import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
return os.path.join(os.environ['LOCALAPPDATA'], 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
| import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
| Fix regression on Windows XP in determining data root | Fix regression on Windows XP in determining data root
| Python | mit | jaraco/keyring | ---
+++
@@ -9,7 +9,12 @@
platform = sys.modules['platform']
def _data_root_Windows():
- return os.path.join(os.environ['LOCALAPPDATA'], 'Python Keyring')
+ try:
+ root = os.environ['LOCALAPPDATA']
+ except KeyError:
+ # Windows XP
+ root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
+ return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
""" |
eb22ca95b79e115130c957614ca9d07237360cf8 | src/django_registration/signals.py | src/django_registration/signals.py | """
Custom signals sent during the registration and activation processes.
"""
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user", "request"])
| """
Custom signals sent during the registration and activation processes.
"""
from django.dispatch import Signal
# A new user has registered.
# Provided args: user, request
user_registered = Signal()
# A user has activated his or her account.
# Provided args: user, request
user_activated = Signal()
| Fix RemovedInDjango40Warning from Signal arguments | Fix RemovedInDjango40Warning from Signal arguments
Fix to removove the following warning I've started to see when running unittest in my django project.
"""/<path to venv/lib/python3.7/site-packages/django_registration/signals.py:13: RemovedInDjango40Warning:
The providing_args argument is deprecated. As it is purely documentational, it has no replacement.
If you rely on this argument as documentation, you can move the text to a code comment or docstring.
user_activated = Signal(providing_args=["user", "request"])"""
| Python | bsd-3-clause | ubernostrum/django-registration | ---
+++
@@ -7,7 +7,9 @@
# A new user has registered.
-user_registered = Signal(providing_args=["user", "request"])
+# Provided args: user, request
+user_registered = Signal()
# A user has activated his or her account.
-user_activated = Signal(providing_args=["user", "request"])
+# Provided args: user, request
+user_activated = Signal() |
d63eec8ec53b4a20d4ac5149b7eb7cfa2d094e2d | calc.py | calc.py | """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
| """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
else:
usage = "calc.py [add|multiply] NUM1 [NUM2 [NUM3 [...]]]"
print(usage)
| Add usage message if instruction not recognized | Add usage message if instruction not recognized
| Python | bsd-3-clause | martaenciso/calc | ---
+++
@@ -16,3 +16,6 @@
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
+ else:
+ usage = "calc.py [add|multiply] NUM1 [NUM2 [NUM3 [...]]]"
+ print(usage) |
303384ff5345e08dfd50ef78871742f0dd2903b6 | src/main/python/pgshovel/utilities/__init__.py | src/main/python/pgshovel/utilities/__init__.py | import importlib
import sys
from contextlib import contextmanager
def load(path):
"""
Loads a module member from a lookup path (using ``path.to.module:member``
syntax.)
"""
module, name = path.split(':')
return getattr(importlib.import_module(module), name)
@contextmanager
def import_extras(name):
try:
yield
except ImportError as e:
s = sys.stderr
print >> s, '*' * 80
print >> s, ''
print >> s, 'This module requires that %r extras are installed.' % (name,)
print >> s, ''
print >> s, 'To install the necessary requirements, use:'
print >> s, ''
print >> s, ' pip install pgshovel[%s]' % (name,)
print >> s, ''
print >> s, '*' * 80
raise
def unique(sequence):
"""
Returns a new sequence containing the unique elements from the provided
sequence, while preserving the same type and order of the original
sequence.
"""
result = []
for item in sequence:
if item in result:
continue # we already have seen this item
result.append(item)
return type(sequence)(result)
| import importlib
import operator
import sys
from contextlib import contextmanager
def load(path):
"""
Loads a module member from a lookup path.
Paths are composed of two sections: a module path, and an attribute path,
separated by a colon.
For example::
>>> from pgshovel.utilities import load
>>> load('sys:stderr.write')
<built-in method write of file object at 0x10885a1e0>
"""
module, attribute = path.split(':')
return operator.attrgetter(attribute)(importlib.import_module(module))
@contextmanager
def import_extras(name):
try:
yield
except ImportError as e:
s = sys.stderr
print >> s, '*' * 80
print >> s, ''
print >> s, 'This module requires that %r extras are installed.' % (name,)
print >> s, ''
print >> s, 'To install the necessary requirements, use:'
print >> s, ''
print >> s, ' pip install pgshovel[%s]' % (name,)
print >> s, ''
print >> s, '*' * 80
raise
def unique(sequence):
"""
Returns a new sequence containing the unique elements from the provided
sequence, while preserving the same type and order of the original
sequence.
"""
result = []
for item in sequence:
if item in result:
continue # we already have seen this item
result.append(item)
return type(sequence)(result)
| Allow deep attribute access in dynamic loading utility. | Allow deep attribute access in dynamic loading utility.
Summary:
This will help for parameterizing access to methods of singleton
objects, such as the `msgpack` codec:
>>> from pgshovel.utilities import load
>>> load('pgshovel.contrib.msgpack:codec.decode')
<bound method MessagePackCodec.decode of <pgshovel.contrib.msgpack.MessagePackCodec object at 0x101d95f50>>
See also: D17954
Reviewers: tail, jeff
Reviewed By: jeff
Differential Revision: http://phabricator.local.disqus.net/D18049
| Python | apache-2.0 | fuziontech/pgshovel,disqus/pgshovel,fuziontech/pgshovel,disqus/pgshovel,fuziontech/pgshovel | ---
+++
@@ -1,15 +1,25 @@
import importlib
+import operator
import sys
from contextlib import contextmanager
def load(path):
"""
- Loads a module member from a lookup path (using ``path.to.module:member``
- syntax.)
+ Loads a module member from a lookup path.
+
+ Paths are composed of two sections: a module path, and an attribute path,
+ separated by a colon.
+
+ For example::
+
+ >>> from pgshovel.utilities import load
+ >>> load('sys:stderr.write')
+ <built-in method write of file object at 0x10885a1e0>
+
"""
- module, name = path.split(':')
- return getattr(importlib.import_module(module), name)
+ module, attribute = path.split(':')
+ return operator.attrgetter(attribute)(importlib.import_module(module))
@contextmanager |
8e5443c7f302957f18db116761f7e410e03eb1fb | app/main/errors.py | app/main/errors.py | # coding=utf-8
from flask import render_template
from . import main
from dmapiclient import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
| # coding=utf-8
from flask import render_template
from . import main
from ..api_client.error import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
| Change app-level error handler to use api_client.error exceptions | Change app-level error handler to use api_client.error exceptions
| Python | mit | AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend | ---
+++
@@ -2,7 +2,7 @@
from flask import render_template
from . import main
-from dmapiclient import APIError
+from ..api_client.error import APIError
@main.app_errorhandler(APIError) |
f6540575792beb2306736e967e5399df58c50337 | qutip/tests/test_heom.py | qutip/tests/test_heom.py | """
Tests for qutip.nonmarkov.heom.
"""
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers are importable
assert HEOMSolver
assert HSolverDL
| """
Tests for qutip.nonmarkov.heom.
"""
from qutip.nonmarkov.heom import (
BathExponent,
Bath,
BosonicBath,
DrudeLorentzBath,
DrudeLorentzPadeBath,
UnderDampedBath,
FermionicBath,
LorentzianBath,
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
HierarchyADOs,
HierarchyADOsState,
)
class TestBathAPI:
def test_api(self):
# just assert that the baths are importable
assert BathExponent
assert Bath
assert BosonicBath
assert DrudeLorentzBath
assert DrudeLorentzPadeBath
assert UnderDampedBath
assert FermionicBath
assert LorentzianBath
assert LorentzianPadeBath
class TestSolverAPI:
def test_api(self):
# just assert that the solvers and associated classes are importable
assert HEOMSolver
assert HSolverDL
assert HierarchyADOs
assert HierarchyADOsState
| Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api. | Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
| Python | bsd-3-clause | cgranade/qutip,qutip/qutip,qutip/qutip,cgranade/qutip | ---
+++
@@ -14,6 +14,8 @@
LorentzianPadeBath,
HEOMSolver,
HSolverDL,
+ HierarchyADOs,
+ HierarchyADOsState,
)
@@ -33,6 +35,8 @@
class TestSolverAPI:
def test_api(self):
- # just assert that the solvers are importable
+ # just assert that the solvers and associated classes are importable
assert HEOMSolver
assert HSolverDL
+ assert HierarchyADOs
+ assert HierarchyADOsState |
4c1116f592731885f87421d8d3e85fa51fc785f9 | apps/home/views.py | apps/home/views.py | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the user) or they are logged in but somehow don't have a valid slug
# then we bounce them to the login page.
# Otherwise (for the moment) we take them to the list of links.
def get(self, request, *args, **kwargs):
try:
print ('*'*30)
print (request.META.get('HTTP_KEYCLOAK_USERNAME'))
print (request.user.slug)
print ('*'*30)
u = request.user.slug
if (u is not None and u is not ''):
return redirect(reverse('link-list'))
else:
return redirect(reverse('login'))
except:
return redirect(reverse('login'))
| # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
from django.contrib.auth import login
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the user) or they are logged in but somehow don't have a valid slug
# then we bounce them to the login page.
# Otherwise (for the moment) we take them to the list of links.
def get(self, request, *args, **kwargs):
userid = request.META.get('HTTP_KEYCLOAK_USERNAME')
if userid:
try:
user = get_user_model().objects.get(userid=userid)
except:
user = get_user_model().objects.create_user(
userid=userid, is_active=True)
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(self.request, user)
self.user = user
return redirect(reverse('link-list'))
try:
u = request.user.slug
if (u is not None and u is not ''):
return redirect(reverse('link-list'))
else:
return redirect(reverse('login'))
except:
return redirect(reverse('login'))
| Handle the user id coming in via a header. | Handle the user id coming in via a header.
| Python | mit | dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse | ---
+++
@@ -3,7 +3,7 @@
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
-
+from django.contrib.auth import login
class Home(View):
@@ -12,11 +12,18 @@
# then we bounce them to the login page.
# Otherwise (for the moment) we take them to the list of links.
def get(self, request, *args, **kwargs):
+ userid = request.META.get('HTTP_KEYCLOAK_USERNAME')
+ if userid:
+ try:
+ user = get_user_model().objects.get(userid=userid)
+ except:
+ user = get_user_model().objects.create_user(
+ userid=userid, is_active=True)
+ user.backend = 'django.contrib.auth.backends.ModelBackend'
+ login(self.request, user)
+ self.user = user
+ return redirect(reverse('link-list'))
try:
- print ('*'*30)
- print (request.META.get('HTTP_KEYCLOAK_USERNAME'))
- print (request.user.slug)
- print ('*'*30)
u = request.user.slug
if (u is not None and u is not ''):
return redirect(reverse('link-list')) |
564e611d7cb0b94e71c53e69971a49c312a0f7f8 | tob-api/tob_api/custom_settings_ongov.py | tob-api/tob_api/custom_settings_ongov.py | '''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":{
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
}
}
}
}
| '''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":[
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
]
}
}
} | Fix ongov customs settings formatting. | Fix ongov customs settings formatting.
| Python | apache-2.0 | swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook | ---
+++
@@ -6,15 +6,14 @@
{
"Location":
{
- "includeFields":{
+ "includeFields":[
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
- }
+ ]
}
}
}
- |
1f7c21280b7135f026f1ff807ffc50c97587f6fd | project/api/managers.py | project/api/managers.py | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', person, **kwargs):
user = self.model(
email=email,
password='',
person=person,
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, person, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| Update manager for Person requirement | Update manager for Person requirement
| Python | bsd-2-clause | barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api | ---
+++
@@ -4,10 +4,11 @@
class UserManager(BaseUserManager):
- def create_user(self, email, password='', **kwargs):
+ def create_user(self, email, password='', person, **kwargs):
user = self.model(
email=email,
password='',
+ person=person,
is_active=True,
**kwargs
)
@@ -15,9 +16,10 @@
return user
- def create_superuser(self, email, password, **kwargs):
+ def create_superuser(self, email, password, person, **kwargs):
user = self.model(
email=email,
+ person=person,
is_staff=True,
is_active=True,
**kwargs |
06bfabc328c4aa32120fd7e52302db76974c2d1b | greengraph/command.py | greengraph/command.py | from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph quantifying the amount of green land between two locations")
parser.add_argument("--start", nargs="+",
help="The starting location, defaults to London ")
parser.add_argument("--end", nargs="+",
help="The ending location, defaults to Durham")
parser.add_argument("--steps", type=int,
help="An integer number of steps between the starting and ending locations, defaults to 10")
parser.add_argument("--out",
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
if arguments.start & & arguments.end:
mygraph = Greengraph(arguments.start, arguments.end)
else:
mygraph = Greengraph("London", "Durham")
if arguments.steps:
data = mygraph.green_between(arguments.steps)
else:
data = mygraph.green_between(10)
plt.plot(data)
plt.xlabel("Step")
plt.ylabel("Greenness")
if arguments.start & & arguments.end:
plt.title("Graph of green land between " +
" ".join(arguments.start) + " and " + " ".join(arguments.end))
else:
plt.title("Graph of green land between London and Durham")
if arguments.out:
plt.savefig(arguments.out)
else:
plt.savefig("graph.png")
if __name__ == "__main__":
process()
| from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph quantifying the amount of green land between two locations")
parser.add_argument("--start", nargs="+",
help="The starting location, defaults to London ")
parser.add_argument("--end", nargs="+",
help="The ending location, defaults to Durham")
parser.add_argument("--steps", type=int,
help="An integer number of steps between the starting and ending locations, defaults to 10")
parser.add_argument("--out",
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
if arguments.start and arguments.end:
mygraph = Greengraph(arguments.start, arguments.end)
else:
mygraph = Greengraph("London", "Durham")
if arguments.steps:
data = mygraph.green_between(arguments.steps)
else:
data = mygraph.green_between(10)
plt.plot(data)
plt.xlabel("Step")
plt.ylabel("Number of green pixels (Max 160000)")
if arguments.start and arguments.end:
plt.title("Graph of green land between " +
" ".join(arguments.start) + " and " + " ".join(arguments.end))
else:
plt.title("Graph of green land between London and Durham")
if arguments.out:
plt.savefig(arguments.out)
else:
plt.savefig("graph.png")
if __name__ == "__main__":
process()
| Correct error where && was used instead of and | Correct error where && was used instead of and
| Python | mit | MikeVasmer/GreenGraphCoursework | ---
+++
@@ -16,7 +16,7 @@
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
- if arguments.start & & arguments.end:
+ if arguments.start and arguments.end:
mygraph = Greengraph(arguments.start, arguments.end)
else:
mygraph = Greengraph("London", "Durham")
@@ -26,8 +26,8 @@
data = mygraph.green_between(10)
plt.plot(data)
plt.xlabel("Step")
- plt.ylabel("Greenness")
- if arguments.start & & arguments.end:
+ plt.ylabel("Number of green pixels (Max 160000)")
+ if arguments.start and arguments.end:
plt.title("Graph of green land between " +
" ".join(arguments.start) + " and " + " ".join(arguments.end))
else: |
0b82a5c10a9e728f6f5424429a70fd2951c9b5c5 | pythonmisp/__init__.py | pythonmisp/__init__.py | from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute
| from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError
| Add MispTransportError in package import | Add MispTransportError in package import
| Python | apache-2.0 | nbareil/python-misp | ---
+++
@@ -1 +1 @@
-from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute
+from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError |
b7d928b473ec6b1eb60707783842d78b9a9ecdec | info.py | info.py | #!/usr/bin/env python
# Print information columns of number values.
import sys
import numpy as np
from dwi import asciifile
for filename in sys.argv[1:]:
af = asciifile.AsciiFile(filename)
print filename
print af.d['description']
params = af.params()
for i, a in enumerate(af.a.T):
d = dict(i=i, param=params[i],
median=np.median(a), mean=a.mean(), var=a.var(),
min=a.min(), max=a.max())
print '{i}\t{param}'\
'\t{median:g}\t{mean:g}\t{var:g}'\
'\t{min:g}\t{max:g}'.format(**d)
| #!/usr/bin/env python
# Print information columns of number values.
import sys
import numpy as np
from dwi import asciifile
for filename in sys.argv[1:]:
af = asciifile.AsciiFile(filename)
print filename
if af.d.has_key('description'):
print af.d['description']
params = af.params()
for i, a in enumerate(af.a.T):
d = dict(i=i, param=params[i],
median=np.median(a), mean=a.mean(), var=a.var(),
min=a.min(), max=a.max(), sum=sum(a))
print '{i}\t{param}'\
'\t{median:g}\t{mean:g}\t{var:g}'\
'\t{min:g}\t{max:g}\t{sum:g}'.format(**d)
| Print sum. Print description only if it exists. | Print sum. Print description only if it exists.
| Python | mit | jupito/dwilib,jupito/dwilib | ---
+++
@@ -10,12 +10,13 @@
for filename in sys.argv[1:]:
af = asciifile.AsciiFile(filename)
print filename
- print af.d['description']
+ if af.d.has_key('description'):
+ print af.d['description']
params = af.params()
for i, a in enumerate(af.a.T):
d = dict(i=i, param=params[i],
median=np.median(a), mean=a.mean(), var=a.var(),
- min=a.min(), max=a.max())
+ min=a.min(), max=a.max(), sum=sum(a))
print '{i}\t{param}'\
'\t{median:g}\t{mean:g}\t{var:g}'\
- '\t{min:g}\t{max:g}'.format(**d)
+ '\t{min:g}\t{max:g}\t{sum:g}'.format(**d) |
b773186f4e39e531e162e3d56a129a21129864e7 | bookmarks/views.py | bookmarks/views.py | from rest_framework import serializers
from rest_framework_json_api.views import ModelViewSet
from .models import Collection, Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ["id", "key", "value", "kind", "row", "collection"]
class ItemViewSet(ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
class CollectionSerializer(serializers.ModelSerializer):
class Meta:
model = Collection
fields = ["key", "column", "row", "id"]
class CollectionViewSet(ModelViewSet):
queryset = Collection.objects.all()
serializer_class = CollectionSerializer
| from rest_framework import serializers
from rest_framework_json_api.views import ModelViewSet
from .models import Collection, Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ["id", "key", "value", "kind", "row", "collection"]
class ItemViewSet(ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
class CollectionSerializer(serializers.ModelSerializer):
class Meta:
model = Collection
fields = ["key", "column", "row", "id", "item_set"]
class CollectionViewSet(ModelViewSet):
queryset = Collection.objects.all()
serializer_class = CollectionSerializer
| Add item_set to collections response | Add item_set to collections response
| Python | mit | GSC-RNSIT/bookmark-manager,GSC-RNSIT/bookmark-manager,rohithpr/bookmark-manager,rohithpr/bookmark-manager | ---
+++
@@ -18,7 +18,7 @@
class CollectionSerializer(serializers.ModelSerializer):
class Meta:
model = Collection
- fields = ["key", "column", "row", "id"]
+ fields = ["key", "column", "row", "id", "item_set"]
class CollectionViewSet(ModelViewSet): |
fc609dd987593d58cddec3af8865a1d3a456fb43 | modules/expansion/dns.py | modules/expansion/dns.py | import json
import dns.resolver
mispattributes = {'input':['hostname', 'domain'], 'output':['ip-src', 'ip-dst']}
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if request.get('hostname'):
toquery = request['hostname']
elif request.get('domain'):
toquery = request['domain']
else:
return False
r = dns.resolver.Resolver()
r.nameservers = ['8.8.8.8']
try:
answer = r.query(toquery, 'A')
except dns.resolver.NXDOMAIN:
return False
except dns.exception.Timeout:
return False
r = {'results':[{'types':mispattributes['output'], 'values':[str(answer[0])]}]}
return r
def introspection():
return mispattributes['input']
| import json
import dns.resolver
mispattributes = {'input':['hostname', 'domain'], 'output':['ip-src', 'ip-dst']}
moduleinfo = "0.1"
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if request.get('hostname'):
toquery = request['hostname']
elif request.get('domain'):
toquery = request['domain']
else:
return False
r = dns.resolver.Resolver()
r.nameservers = ['8.8.8.8']
try:
answer = r.query(toquery, 'A')
except dns.resolver.NXDOMAIN:
return False
except dns.exception.Timeout:
return False
r = {'results':[{'types':mispattributes['output'], 'values':[str(answer[0])]}]}
return r
def introspection():
return mispattributes
def version():
return moduleinfo
| Add a version per default | Add a version per default
| Python | agpl-3.0 | amuehlem/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,VirusTotal/misp-modules,amuehlem/misp-modules,MISP/misp-modules,VirusTotal/misp-modules,Rafiot/misp-modules,Rafiot/misp-modules,VirusTotal/misp-modules,MISP/misp-modules,MISP/misp-modules | ---
+++
@@ -2,6 +2,7 @@
import dns.resolver
mispattributes = {'input':['hostname', 'domain'], 'output':['ip-src', 'ip-dst']}
+moduleinfo = "0.1"
def handler(q=False):
if q is False:
@@ -26,4 +27,6 @@
def introspection():
- return mispattributes['input']
+ return mispattributes
+def version():
+ return moduleinfo |
c1fbc761e10e06effa49ede1f8dbc04189999bd5 | niftynet/layer/post_processing.py | niftynet/layer/post_processing.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.utilities.util_common import look_up_operations
from niftynet.layer.base_layer import Layer
SUPPORTED_OPS = {"SOFTMAX", "ARGMAX", "IDENTITY"}
class PostProcessingLayer(Layer):
"""
This layer operation converts the raw network outputs into final inference
results.
"""
def __init__(self, func='', num_classes=0, name='post_processing'):
super(PostProcessingLayer, self).__init__(name=name)
self.func = look_up_operations(func.upper(), SUPPORTED_OPS)
self.num_classes = num_classes
def num_output_channels(self):
assert self._op._variables_created
if self.func == "SOFTMAX":
return self.num_classes
else:
return 1
def layer_op(self, inputs):
if self.func == "SOFTMAX":
output_tensor = tf.cast(tf.nn.softmax(inputs), tf.float32)
elif self.func == "ARGMAX":
output_tensor = tf.to_int64(tf.argmax(inputs, -1))
output_tensor = tf.expand_dims(output_tensor, axis=-1)
elif self.func == "IDENTITY":
output_tensor = tf.cast(inputs, tf.float32)
return output_tensor
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.utilities.util_common import look_up_operations
from niftynet.layer.base_layer import Layer
SUPPORTED_OPS = {"SOFTMAX", "ARGMAX", "IDENTITY"}
class PostProcessingLayer(Layer):
"""
This layer operation converts the raw network outputs into final inference
results.
"""
def __init__(self, func='', num_classes=0, name='post_processing'):
super(PostProcessingLayer, self).__init__(name=name)
self.func = look_up_operations(func.upper(), SUPPORTED_OPS)
self.num_classes = num_classes
def num_output_channels(self):
assert self._op._variables_created
if self.func == "SOFTMAX":
return self.num_classes
else:
return 1
def layer_op(self, inputs):
if self.func == "SOFTMAX":
output_tensor = tf.cast(tf.nn.softmax(inputs), tf.float32)
elif self.func == "ARGMAX":
output_tensor = tf.argmax(inputs, -1,output_type=tf.int32)
output_tensor = tf.expand_dims(output_tensor, axis=-1)
elif self.func == "IDENTITY":
output_tensor = tf.cast(inputs, tf.float32)
return output_tensor
| Change label output to int32 for compatibility with some viewers | Change label output to int32 for compatibility with some viewers
| Python | apache-2.0 | NifTK/NiftyNet,NifTK/NiftyNet,NifTK/NiftyNet,NifTK/NiftyNet | ---
+++
@@ -31,7 +31,7 @@
if self.func == "SOFTMAX":
output_tensor = tf.cast(tf.nn.softmax(inputs), tf.float32)
elif self.func == "ARGMAX":
- output_tensor = tf.to_int64(tf.argmax(inputs, -1))
+ output_tensor = tf.argmax(inputs, -1,output_type=tf.int32)
output_tensor = tf.expand_dims(output_tensor, axis=-1)
elif self.func == "IDENTITY":
output_tensor = tf.cast(inputs, tf.float32) |
02e7875bb8792741cfcf1b94561c5c5a418fcfbc | stable_baselines/__init__.py | stable_baselines/__init__.py | from stable_baselines.a2c import A2C
from stable_baselines.acer import ACER
from stable_baselines.acktr import ACKTR
# from stable_baselines.ddpg import DDPG
from stable_baselines.deepq import DeepQ
from stable_baselines.gail import GAIL
from stable_baselines.ppo1 import PPO1
from stable_baselines.ppo2 import PPO2
from stable_baselines.trpo_mpi import TRPO
| from stable_baselines.a2c import A2C
from stable_baselines.acer import ACER
from stable_baselines.acktr import ACKTR
from stable_baselines.ddpg import DDPG
from stable_baselines.deepq import DeepQ
from stable_baselines.gail import GAIL
from stable_baselines.ppo1 import PPO1
from stable_baselines.ppo2 import PPO2
from stable_baselines.trpo_mpi import TRPO
| Revert "Try fixing circular import" | Revert "Try fixing circular import"
This reverts commit 1a23578be15c06c8d8688bcceffac4af2e980c95.
| Python | mit | hill-a/stable-baselines,hill-a/stable-baselines | ---
+++
@@ -1,7 +1,7 @@
from stable_baselines.a2c import A2C
from stable_baselines.acer import ACER
from stable_baselines.acktr import ACKTR
-# from stable_baselines.ddpg import DDPG
+from stable_baselines.ddpg import DDPG
from stable_baselines.deepq import DeepQ
from stable_baselines.gail import GAIL
from stable_baselines.ppo1 import PPO1 |
332c21f97936baab6901fccb3b6d28eaee83729c | skimage/_shared/utils.py | skimage/_shared/utils.py | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = 'Deprecated function.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
| import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
| Make deprecation warning in doc string bold | Make deprecation warning in doc string bold
| Python | bsd-3-clause | chintak/scikit-image,warmspringwinds/scikit-image,SamHames/scikit-image,almarklein/scikit-image,chriscrosscutler/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,almarklein/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,dpshelio/scikit-image,WarrenWeckesser/scikits-image,vighneshbirodkar/scikit-image,robintw/scikit-image,keflavich/scikit-image,Britefury/scikit-image,paalge/scikit-image,chintak/scikit-image,ClinicalGraphics/scikit-image,Hiyorimi/scikit-image,ofgulban/scikit-image,rjeli/scikit-image,michaelaye/scikit-image,Midafi/scikit-image,blink1073/scikit-image,rjeli/scikit-image,newville/scikit-image,paalge/scikit-image,juliusbierk/scikit-image,ajaybhat/scikit-image,keflavich/scikit-image,robintw/scikit-image,ofgulban/scikit-image,WarrenWeckesser/scikits-image,SamHames/scikit-image,paalge/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,Midafi/scikit-image,dpshelio/scikit-image,rjeli/scikit-image,youprofit/scikit-image,youprofit/scikit-image,chintak/scikit-image,newville/scikit-image,blink1073/scikit-image,bsipocz/scikit-image,oew1v07/scikit-image,emon10005/scikit-image,michaelaye/scikit-image,GaZ3ll3/scikit-image,SamHames/scikit-image,vighneshbirodkar/scikit-image,bennlich/scikit-image,almarklein/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,pratapvardhan/scikit-image,oew1v07/scikit-image,juliusbierk/scikit-image,jwiggins/scikit-image,emon10005/scikit-image,jwiggins/scikit-image,almarklein/scikit-image,ajaybhat/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,GaZ3ll3/scikit-image,pratapvardhan/scikit-image,Hiyorimi/scikit-image | ---
+++
@@ -44,7 +44,7 @@
return func(*args, **kwargs)
# modify doc string to display deprecation warning
- doc = 'Deprecated function.' + alt_msg
+ doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else: |
07bc7efb756e2bc99f59c59476379bc186f36143 | sktracker/io/__init__.py | sktracker/io/__init__.py | """`sktracker.io` module is designed to easly and quickly open Tiff files and
to be able to parse and import any kind of metadata.
Finally, an OME module is provided to read and write OME xml metadata. See
https://www.openmicroscopy.org/site/support/ome-model/ for details.
"""
from .tifffile import imsave
from .tifffile import imread
from .tifffile import imshow
from .tifffile import TiffFile
from .tifffile import TiffSequence
from .ome import OMEModel
from .tiff_metadata import get_metadata_from_tiff
__all__ = ['get_metadata_from_tiff', 'OMEModel', 'imsave', 'imread', 'imshow',
'TiffFile', 'TiffSequence']
| """`sktracker.io` module is designed to easly and quickly open Tiff files and
to be able to parse and import any kind of metadata.
Finally, an OME module is provided to read and write OME xml metadata. See
https://www.openmicroscopy.org/site/support/ome-model/ for details.
"""
# Remove warnings for tifffile.py
import warnings
warnings.filterwarnings("ignore")
from .tifffile import imsave
from .tifffile import imread
from .tifffile import imshow
from .tifffile import TiffFile
from .tifffile import TiffSequence
from .ome import OMEModel
from .tiff_metadata import get_metadata_from_tiff
__all__ = ['get_metadata_from_tiff', 'OMEModel', 'imsave', 'imread', 'imshow',
'TiffFile', 'TiffSequence']
| Remove warning messages for tifffile.py | Remove warning messages for tifffile.py
| Python | bsd-3-clause | bnoi/scikit-tracker,bnoi/scikit-tracker,bnoi/scikit-tracker | ---
+++
@@ -5,6 +5,10 @@
https://www.openmicroscopy.org/site/support/ome-model/ for details.
"""
+
+# Remove warnings for tifffile.py
+import warnings
+warnings.filterwarnings("ignore")
from .tifffile import imsave
from .tifffile import imread |
b86a0aa55bb6f30be07cff5e3e6cdb27d84b0024 | Insertion_sort/insertion_sort.py | Insertion_sort/insertion_sort.py | def insertion_sort(seq):
for i in range(1, len(l)):
for j in range(i, 0, -1):
if l[j - 1] < l[j]:
break
l[j - 1], l[j] = l[j], l[j - 1]
return l | def insertion_sort(l):
for i in range(1, len(l)):
for j in range(i, 0, -1):
if l[j - 1] < l[j]:
break
l[j - 1], l[j] = l[j], l[j - 1]
return l | Revert "Added implementation of selection sort" | Revert "Added implementation of selection sort"
This reverts commit acf509f392d536c61c0dbed3a07ed24849b00928.
| Python | mit | wizh/algorithms | ---
+++
@@ -1,4 +1,4 @@
-def insertion_sort(seq):
+def insertion_sort(l):
for i in range(1, len(l)):
for j in range(i, 0, -1):
if l[j - 1] < l[j]: |
6ab4fc7af637976a92846005c4d1d35693e893a0 | rivescript/__main__.py | rivescript/__main__.py | #!/usr/bin/env python
from __future__ import absolute_import
"""RiveScript's __main__.py
This script is executed when you run `python rivescript` directly.
It does nothing more than load the interactive mode of RiveScript."""
__docformat__ = 'plaintext'
from rivescript.interactive import interactive_mode
if __name__ == "__main__":
interactive_mode()
# vim:expandtab
| #!/usr/bin/env python
from __future__ import absolute_import
"""RiveScript's __main__.py
This script is executed when you run `python rivescript` directly.
It does nothing more than load the interactive mode of RiveScript."""
__docformat__ = 'plaintext'
# Boilerplate to allow running as script directly.
# See: http://stackoverflow.com/questions/2943847/nightmare-with-relative-imports-how-does-pep-366-work
if __name__ == "__main__" and not __package__:
import sys, os
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
import rivescript
__package__ = str("rivescript")
from .interactive import interactive_mode
interactive_mode()
# vim:expandtab
| Fix running the module directly | Fix running the module directly
After rearranging the package structure, running the rivescript module
directly stopped working due to relative import errors. Fix it so that
it can be run directly while still working when imported as normal.
| Python | mit | Dinh-Hung-Tu/rivescript-python,FujiMakoto/makoto-rivescript,aichaos/rivescript-python,FujiMakoto/makoto-rivescript,plasmashadow/rivescript-python,aichaos/rivescript-python,FujiMakoto/makoto-rivescript,plasmashadow/rivescript-python,aichaos/rivescript-python,plasmashadow/rivescript-python,Dinh-Hung-Tu/rivescript-python,Dinh-Hung-Tu/rivescript-python | ---
+++
@@ -9,9 +9,16 @@
__docformat__ = 'plaintext'
-from rivescript.interactive import interactive_mode
+# Boilerplate to allow running as script directly.
+# See: http://stackoverflow.com/questions/2943847/nightmare-with-relative-imports-how-does-pep-366-work
+if __name__ == "__main__" and not __package__:
+ import sys, os
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ sys.path.insert(0, parent_dir)
+ import rivescript
+ __package__ = str("rivescript")
-if __name__ == "__main__":
+ from .interactive import interactive_mode
interactive_mode()
# vim:expandtab |
79087444a858c33362c5a31200f158c6edda95df | humans/utils.py | humans/utils.py | from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_keys(key).results
keys = settings.GPG_OBJ.list_keys()
if not results or not results[0]["fingerprint"]:
return None, "invalid"
else:
state = "valid"
result = results[0]
for key in keys:
if key["fingerprint"] == result["fingerprint"]:
exp_timestamp = int(key["expires"]) if key["expires"] else ""
expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
if key["trust"] == "r":
state = "revoked"
elif exp_timestamp and expires < timezone.now():
state = "expired"
break
return result["fingerprint"], state
| from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_keys(key).results
keys = settings.GPG_OBJ.list_keys()
if not results or not results[0]["fingerprint"]:
return None, "invalid"
else:
state = "valid"
result = results[0]
for key in keys:
if key["fingerprint"] == result["fingerprint"]:
exp_timestamp = int(key["expires"]) if key["expires"] else 0
expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
if key["trust"] == "r":
state = "revoked"
elif exp_timestamp and expires < timezone.now():
state = "expired"
break
return result["fingerprint"], state
| Fix 'float is required' when key has no exp date | Fix 'float is required' when key has no exp date
No expiration date was defaulting to "", which was throwing an error
when creating the expire date timestamp.
| Python | mit | whitesmith/hawkpost,whitesmith/hawkpost,whitesmith/hawkpost | ---
+++
@@ -13,7 +13,7 @@
result = results[0]
for key in keys:
if key["fingerprint"] == result["fingerprint"]:
- exp_timestamp = int(key["expires"]) if key["expires"] else ""
+ exp_timestamp = int(key["expires"]) if key["expires"] else 0
expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
if key["trust"] == "r":
state = "revoked" |
6ebb2b021594633a66f2ff90121d4a39eec96cc8 | test_project/test_project/urls.py | test_project/test_project/urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('test_app.urls')),
)
| from django.conf.urls import patterns, include, url
from django.http import HttpResponseNotFound
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('test_app.urls')),
)
def custom404(request):
return HttpResponseNotFound(status=404)
handler404 = 'test_project.urls.custom404'
| Use a custom 404 handler to avoid using the default template loader. | Use a custom 404 handler to avoid using the default template loader.
| Python | mit | liberation/django-elasticsearch,leotsem/django-elasticsearch,sadnoodles/django-elasticsearch,alsur/django-elasticsearch | ---
+++
@@ -1,4 +1,5 @@
from django.conf.urls import patterns, include, url
+from django.http import HttpResponseNotFound
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
@@ -7,3 +8,8 @@
urlpatterns = patterns('',
url(r'^', include('test_app.urls')),
)
+
+def custom404(request):
+ return HttpResponseNotFound(status=404)
+
+handler404 = 'test_project.urls.custom404' |
399e8ae093034ca69030f15dff8e9b570baf0cf5 | paper_to_git/database.py | paper_to_git/database.py | from peewee import SqliteDatabase, OperationalError
__all__ = [
'BaseDatabase',
]
class BaseDatabase:
"""The base database class to be used with Peewee.
"""
def __init__(self, url=None):
self.url = url
self.db = SqliteDatabase(None)
def initialize(self, url=None):
if url is not None:
self.url = url
else:
raise ValueError
self.db.init(url)
self._post_initialization()
return self.db
def _post_initialization(self):
from paper_to_git.models import PaperDoc, PaperFolder
self.db.connect()
try:
self.db.create_tables([PaperDoc, PaperFolder])
except OperationalError:
# The database already exists.
pass
| from peewee import SqliteDatabase, OperationalError
__all__ = [
'BaseDatabase',
]
class BaseDatabase:
"""The base database class to be used with Peewee.
"""
def __init__(self, url=None):
self.url = url
self.db = SqliteDatabase(None)
def initialize(self, url=None):
if url is not None:
self.url = url
else:
raise ValueError
self.db.init(url)
self._post_initialization()
return self.db
def _post_initialization(self):
from paper_to_git.models import PaperDoc, PaperFolder, Sync
self.db.connect()
try:
self.db.create_tables([PaperDoc, PaperFolder, Sync])
except OperationalError:
# The database already exists.
pass
| Add model Sync to repo. | Add model Sync to repo.
| Python | apache-2.0 | maxking/paper-to-git,maxking/paper-to-git | ---
+++
@@ -23,10 +23,10 @@
return self.db
def _post_initialization(self):
- from paper_to_git.models import PaperDoc, PaperFolder
+ from paper_to_git.models import PaperDoc, PaperFolder, Sync
self.db.connect()
try:
- self.db.create_tables([PaperDoc, PaperFolder])
+ self.db.create_tables([PaperDoc, PaperFolder, Sync])
except OperationalError:
# The database already exists.
pass |
579fa16e21b580f2469e3c098a26ec480ea0dba5 | meetings/conferences/urls.py | meetings/conferences/urls.py | from django.conf.urls import url, include
from conferences import views
urlpatterns = [
url(r'^$', views.ConferenceList.as_view(), name='list'),
url(r'^(?P<pk>[0-9]+)/$', views.ConferenceDetail.as_view(), name='detail'),
url(r'^(?P<conference_id>[0-9]+)/submissions/',
include('submissions.urls', namespace='submissions')),
]
| from django.conf.urls import url, include
from conferences import views
urlpatterns = [
url(r'^$', views.ConferenceList.as_view(), name='list'),
url(r'^(?P<pk>[-\w]+)/$', views.ConferenceDetail.as_view(), name='detail'),
url(r'^(?P<conference_id>[-\w]+)/submissions/',
include('submissions.urls', namespace='submissions')),
]
| Change url config for slugs | Change url config for slugs
| Python | apache-2.0 | leodomingo/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings | ---
+++
@@ -3,7 +3,7 @@
urlpatterns = [
url(r'^$', views.ConferenceList.as_view(), name='list'),
- url(r'^(?P<pk>[0-9]+)/$', views.ConferenceDetail.as_view(), name='detail'),
- url(r'^(?P<conference_id>[0-9]+)/submissions/',
+ url(r'^(?P<pk>[-\w]+)/$', views.ConferenceDetail.as_view(), name='detail'),
+ url(r'^(?P<conference_id>[-\w]+)/submissions/',
include('submissions.urls', namespace='submissions')),
] |
9ec465771ed3b6b1b0be85468f73086fcfdbb76d | siemstress/__init__.py | siemstress/__init__.py | __version__ = '0.4-alpha'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['parsecore', 'querycore', 'query', 'triggercore', 'trigger']
import siemstress.query
import siemstress.trigger
| __version__ = '0.4-alpha'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['parsecore', 'querycore', 'query', 'triggercore', 'trigger',
'util']
import siemstress.query
import siemstress.trigger
import siemstress.util
| Add util module for DB testing | Add util module for DB testing
| Python | mit | dogoncouch/siemstress | ---
+++
@@ -2,7 +2,9 @@
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
-__all__ = ['parsecore', 'querycore', 'query', 'triggercore', 'trigger']
+__all__ = ['parsecore', 'querycore', 'query', 'triggercore', 'trigger',
+ 'util']
import siemstress.query
import siemstress.trigger
+import siemstress.util |
ab49b07f89dcc000201742275c7109597a032d9b | setup.py | setup.py | #!/usr/bin/env python
import os
import setuptools
NAME = 'takeyourmeds'
DATA = (
'static',
'templates',
)
def find_data(dirs):
result = []
for x in dirs:
for y, _, _ in os.walk(x):
result.append(os.path.join(y, '*'))
return result
setuptools.setup(
name=NAME,
scripts=('%s/manage.py' % NAME,),
packages=(NAME,),
package_data={NAME: find_data(DATA)},
)
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
NAME = 'takeyourmeds'
DATA = (
'static',
'templates',
)
def find_data(dirs):
result = []
for x in dirs:
for y, _, _ in os.walk(x):
result.append(os.path.join(y, '*'))
return result
setup(
name=NAME,
scripts=('%s/manage.py' % NAME,),
packages=find_packages(),
package_data={NAME: find_data(DATA)},
)
| Use find_packages so we actually install everything.. | Use find_packages so we actually install everything..
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | ---
+++
@@ -1,7 +1,8 @@
#!/usr/bin/env python
import os
-import setuptools
+
+from setuptools import setup, find_packages
NAME = 'takeyourmeds'
@@ -17,9 +18,9 @@
result.append(os.path.join(y, '*'))
return result
-setuptools.setup(
+setup(
name=NAME,
scripts=('%s/manage.py' % NAME,),
- packages=(NAME,),
+ packages=find_packages(),
package_data={NAME: find_data(DATA)},
) |
5fc27215618ac6e160b193e82dea4f222bfeaaf2 | setup.py | setup.py | """
setup.py
"""
__author__ = 'Gavin M. Roy'
__email__ = 'gmr@myyearbook.com'
__since__ = '2011-09-13'
from hockeyapp import __version__
from setuptools import setup
long_description = """Python client for the HockeyApp.net API"""
setup(name='hockeyapp',
version=__version__,
description="HockeyApp.net API",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
],
author='Gavin M. Roy',
author_email='gmr@myyearbook.com',
url='http://github.com/gmr/hockeyapp',
packages=['hockeyapp'],
entry_points=dict(console_scripts=['hockeyapp-cli=hockeyapp.cli:main']),
zip_safe=True,
install_requires=[
'poster'
])
| """
setup.py
"""
__author__ = 'Gavin M. Roy'
__email__ = 'gmr@myyearbook.com'
__since__ = '2011-09-13'
from hockeyapp import __version__
from setuptools import setup
long_description = """Python client for the HockeyApp.net API"""
setup(name='hockeyapp',
version=__version__,
description="HockeyApp.net API",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
],
author='Gavin M. Roy',
author_email='gmr@myyearbook.com',
url='http://github.com/gmr/hockeyapp',
packages=['hockeyapp'],
entry_points=dict(console_scripts=['hockeyapp-cli=hockeyapp.cli:main']),
zip_safe=True,
install_requires=[
'poster', 'argparse'
])
| Add argparse as a dependency to setyp.py | Add argparse as a dependency to setyp.py
Needed for python 2.6
Change-Id: I87df47c7b814024b1ec91d227f45762711de03c0
| Python | bsd-3-clause | gmr/hockeyapp,vkotovv/hockeyapp | ---
+++
@@ -24,6 +24,6 @@
entry_points=dict(console_scripts=['hockeyapp-cli=hockeyapp.cli:main']),
zip_safe=True,
install_requires=[
- 'poster'
+ 'poster', 'argparse'
])
|
8472078e29ca70843e19e24b6c3290dab20e80de | setup.py | setup.py | from setuptools import setup, find_packages
# Parse the version from the mapbox module.
with open('mapboxcli/__init__.py') as f:
for line in f:
if line.find("__version__") >= 0:
version = line.split("=")[1].strip()
version = version.strip('"')
version = version.strip("'")
continue
setup(name='mapboxcli',
version=version,
description="Command line interface to Mapbox Web Services",
classifiers=[],
keywords='',
author="Sean Gillies",
author_email='sean@mapbox.com',
url='https://github.com/mapbox/mapbox-cli-py',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click',
'click-plugins',
'cligj>=0.4',
'mapbox>=0.11',
'six'],
extras_require={
'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses'],
},
entry_points="""
[console_scripts]
mapbox=mapboxcli.scripts.cli:main_group
""")
| from setuptools import setup, find_packages
# Parse the version from the mapbox module.
with open('mapboxcli/__init__.py') as f:
for line in f:
if line.find("__version__") >= 0:
version = line.split("=")[1].strip()
version = version.strip('"')
version = version.strip("'")
continue
setup(name='mapboxcli',
version=version,
description="Command line interface to Mapbox Web Services",
classifiers=[],
keywords='',
author="Sean Gillies",
author_email='sean@mapbox.com',
url='https://github.com/mapbox/mapbox-cli-py',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click',
'click-plugins',
'cligj>=0.4',
'mapbox>=0.11',
'six'],
extras_require={
'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses',
'mock']},
entry_points="""
[console_scripts]
mapbox=mapboxcli.scripts.cli:main_group
""")
| Add mock to test extras | Add mock to test extras
| Python | mit | mapbox/mapbox-cli-py | ---
+++
@@ -29,8 +29,8 @@
'mapbox>=0.11',
'six'],
extras_require={
- 'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses'],
- },
+ 'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses',
+ 'mock']},
entry_points="""
[console_scripts]
mapbox=mapboxcli.scripts.cli:main_group |
540e58ca66783bf04fa5dee0b447bb3764cd087a | setup.py | setup.py | from setuptools import setup
setup(
name="ftfy",
version='3.3.0',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='info@luminoso.com',
license="MIT",
url='http://github.com/LuminosoInsight/python-ftfy',
platforms=["any"],
description="Fixes some problems with Unicode text after the fact",
packages=['ftfy', 'ftfy.bad_codecs'],
package_data={'ftfy': ['char_classes.dat']},
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Filters",
"Development Status :: 5 - Production/Stable"
],
entry_points={
'console_scripts': [
'ftfy = ftfy.cli:main'
]
}
)
| from setuptools import setup
setup(
name="ftfy",
version='3.3.0',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='info@luminoso.com',
license="MIT",
url='http://github.com/LuminosoInsight/python-ftfy',
platforms=["any"],
description="Fixes some problems with Unicode text after the fact",
packages=['ftfy', 'ftfy.bad_codecs'],
package_data={'ftfy': ['char_classes.dat']},
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Filters",
"Development Status :: 5 - Production/Stable"
],
entry_points={
'console_scripts': [
'ftfy = ftfy.cli:main'
]
}
)
| Stop claiming support for 2.6 | Stop claiming support for 2.6
I don't even have a Python 2.6 interpreter.
| Python | mit | LuminosoInsight/python-ftfy | ---
+++
@@ -13,7 +13,6 @@
package_data={'ftfy': ['char_classes.dat']},
classifiers=[
"Programming Language :: Python :: 2",
- "Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2", |
576aaf93c8d8ed5c81bef85d0561609252de7169 | setup.py | setup.py | from setuptools import setup, find_packages
import simple_virtuoso_migrate
setup(
name = "simple-virtuoso-migrate",
version = simple_virtuoso_migrate.SIMPLE_VIRTUOSO_MIGRATE_VERSION,
packages = find_packages(),
author = "Percy Rivera",
author_email = "priverasalas@gmail.com",
description = "simple-virtuoso-migrate is a Virtuoso database migration tool inspired on simple-db-migrate.",
license = "Apache License 2.0",
keywords = "database migration tool virtuoso",
url = "http://github.com/globocom/simple-virtuoso-migrate/",
long_description = "simple-virtuoso-migrate is a Virtuoso database migration tool inspired on simple-db-migrate. This tool helps you easily refactor and manage your ontology T-BOX. The main difference is that simple-db-migrate are intended to be used for mysql, ms-sql and oracle projects while simple-virtuoso-migrate makes it possible to have migrations for Virtuoso",
tests_require=['coverage==3.5.1', 'mock==0.8.0', 'nose==1.1.2'],
install_requires=['GitPython>=0.3 ', 'paramiko==1.9.0', 'rdflib==3.4.0', 'rdfextras==0.4', 'rdflib-sparqlstore==0.2'],
# generate script automatically
entry_points = {
'console_scripts': [
'virtuoso-migrate = simple_virtuoso_migrate.run:run_from_argv',
],
}
)
| from setuptools import setup, find_packages
import simple_virtuoso_migrate
setup(
name = "simple-virtuoso-migrate",
version = simple_virtuoso_migrate.SIMPLE_VIRTUOSO_MIGRATE_VERSION,
packages = find_packages(),
author = "Percy Rivera",
author_email = "priverasalas@gmail.com",
description = "simple-virtuoso-migrate is a Virtuoso database migration tool inspired on simple-db-migrate.",
license = "Apache License 2.0",
keywords = "database migration tool virtuoso",
url = "http://github.com/globocom/simple-virtuoso-migrate/",
long_description = "simple-virtuoso-migrate is a Virtuoso database migration tool inspired on simple-db-migrate. This tool helps you easily refactor and manage your ontology T-BOX. The main difference is that simple-db-migrate are intended to be used for mysql, ms-sql and oracle projects while simple-virtuoso-migrate makes it possible to have migrations for Virtuoso",
tests_require=['coverage==3.7', 'mock==1.0.1', 'nose==1.3.0'],
install_requires=['GitPython>=0.3 ', 'paramiko==1.9.0', 'rdflib==3.4.0', 'rdfextras==0.4', 'rdflib-sparqlstore==0.2'],
# generate script automatically
entry_points = {
'console_scripts': [
'virtuoso-migrate = simple_virtuoso_migrate.run:run_from_argv',
],
}
)
| Upgrade versions of test tools | Upgrade versions of test tools
| Python | apache-2.0 | globocom/simple-virtuoso-migrate,globocom/simple-virtuoso-migrate | ---
+++
@@ -13,7 +13,7 @@
keywords = "database migration tool virtuoso",
url = "http://github.com/globocom/simple-virtuoso-migrate/",
long_description = "simple-virtuoso-migrate is a Virtuoso database migration tool inspired on simple-db-migrate. This tool helps you easily refactor and manage your ontology T-BOX. The main difference is that simple-db-migrate are intended to be used for mysql, ms-sql and oracle projects while simple-virtuoso-migrate makes it possible to have migrations for Virtuoso",
- tests_require=['coverage==3.5.1', 'mock==0.8.0', 'nose==1.1.2'],
+ tests_require=['coverage==3.7', 'mock==1.0.1', 'nose==1.3.0'],
install_requires=['GitPython>=0.3 ', 'paramiko==1.9.0', 'rdflib==3.4.0', 'rdfextras==0.4', 'rdflib-sparqlstore==0.2'],
# generate script automatically |
977ffecdef01bd5041c3f206dbf311211f03a054 | setup.py | setup.py | '''
(c) 2014 Farsight Security Inc.
(c) 2010 Victor Ng
Released under the MIT license. See license.txt.
'''
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from os.path import join
import os
ext_modules=[
Extension("mmaparray",
extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE'],
sources = [
"src/mmaparray.pyx",
'src/mmap_writer.c',],
include_dirs = ['src'],
),
]
setup(
name = 'mmaparray',
author='Henry Stern',
author_email = 'stern@fsi.io',
description = 'MMap File-Backed Arrays for Python',
long_description = open('README.rst').read(),
version='0.4',
url='https://github.com/farsightsec/mmaparray',
license = 'MIT License',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
test_suite = 'tests',
requires = [ 'six', 'Cython (>=0.13)' ],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Cython',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
)
| '''
(c) 2014 Farsight Security Inc.
(c) 2010 Victor Ng
Released under the MIT license. See license.txt.
'''
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from os.path import join
import os
ext_modules=[
Extension("mmaparray",
extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE', '-D_GNU_SOURCE'],
sources = [
"src/mmaparray.pyx",
'src/mmap_writer.c',],
include_dirs = ['src'],
),
]
setup(
name = 'mmaparray',
author='Henry Stern',
author_email = 'stern@fsi.io',
description = 'MMap File-Backed Arrays for Python',
long_description = open('README.rst').read(),
version='0.4',
url='https://github.com/farsightsec/mmaparray',
license = 'MIT License',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
test_suite = 'tests',
requires = [ 'six', 'Cython (>=0.13)' ],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Cython',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
)
| Add _GNU_SOURCE definition to ext_module | Add _GNU_SOURCE definition to ext_module
| Python | mit | farsightsec/mmaparray,farsightsec/mmaparray | ---
+++
@@ -14,7 +14,7 @@
ext_modules=[
Extension("mmaparray",
- extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE'],
+ extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE', '-D_GNU_SOURCE'],
sources = [
"src/mmaparray.pyx",
'src/mmap_writer.c',], |
53a597539c5f6ddbec04e51bfafb0402c4e31fdc | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
"""
django twitter bootstrap form setup script
"""
__author__ = "Guillaume Luchet <guillaume@geelweb.org>"
__version__ = "0.1"
import sys
from setuptools import setup, find_packages
author_data = __author__.split(" ")
maintainer = " ".join(author_data[0:-1])
maintainer_email = author_data[-1]
long_desc = open('README.md').read()
if __name__ == "__main__":
setup(
name="django twitter bootstrap form",
version=__version__,
description="Render Django forms as described using the twitter bootstrap HTML layout",
long_description=long_desc,
author=maintainer,
author_email=maintainer_email,
maintainer=maintainer,
maintainer_email=maintainer_email,
url="https://github.com/geelweb/django-twitter-bootstrap-form",
license='MIT',
namespace_packages = ['geelweb', 'geelweb.django'],
packages=find_packages('src'),
package_dir = {'':'src'},
package_data = {
'geelweb.django.twitter_bootstrap_form': [
'templates/twitter_bootstrap_form/*.html',
],
},
zip_safe=False
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
"""
django twitter bootstrap form setup script
"""
__author__ = "Guillaume Luchet <guillaume@geelweb.org>"
__version__ = "0.1"
import sys
from setuptools import setup, find_packages
author_data = __author__.split(" ")
maintainer = " ".join(author_data[0:-1])
maintainer_email = author_data[-1]
long_desc = open('README.md').read()
if __name__ == "__main__":
setup(
name="django-twitterbootstrap-form",
version=__version__,
description="Render Django forms as described using the twitter bootstrap HTML layout",
long_description=long_desc,
author=maintainer,
author_email=maintainer_email,
maintainer=maintainer,
maintainer_email=maintainer_email,
url="https://github.com/geelweb/django-twitter-bootstrap-form",
download_url="https://github.com/geelweb/django-twitter-bootstrap-form/tarball/0.1",
license='MIT',
namespace_packages = ['geelweb', 'geelweb.django'],
packages=find_packages('src'),
package_dir = {'':'src'},
package_data = {
'geelweb.django.twitter_bootstrap_form': [
'templates/twitter_bootstrap_form/*.html',
],
},
keywords = ['django', 'twitter', 'bootstrap', 'form'],
)
| Add keywords and update package name | Add keywords and update package name
| Python | mit | geelweb/django-twitter-bootstrap-form,geelweb/django-twitter-bootstrap-form | ---
+++
@@ -21,7 +21,7 @@
if __name__ == "__main__":
setup(
- name="django twitter bootstrap form",
+ name="django-twitterbootstrap-form",
version=__version__,
description="Render Django forms as described using the twitter bootstrap HTML layout",
long_description=long_desc,
@@ -30,6 +30,7 @@
maintainer=maintainer,
maintainer_email=maintainer_email,
url="https://github.com/geelweb/django-twitter-bootstrap-form",
+ download_url="https://github.com/geelweb/django-twitter-bootstrap-form/tarball/0.1",
license='MIT',
namespace_packages = ['geelweb', 'geelweb.django'],
packages=find_packages('src'),
@@ -39,6 +40,6 @@
'templates/twitter_bootstrap_form/*.html',
],
},
- zip_safe=False
+ keywords = ['django', 'twitter', 'bootstrap', 'form'],
)
|
c4d9508014f1a0deeb2fbe14e9ee693df849ebdb | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
include_package_data=True,
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
| Exclude tests and include sql files in cnx-authoring package | Exclude tests and include sql files in cnx-authoring package
Remove include_package_data=True as it looks for MANIFEST.in instead of
using the package_data that we specified in setup.py.
Tested by running:
```bash
rm -rf cnx_authoring.egg-info dist
python setup.py sdist
```
Close #51
| Python | agpl-3.0 | Connexions/cnx-authoring | ---
+++
@@ -27,13 +27,12 @@
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
- packages=find_packages(),
+ packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
- include_package_data=True,
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main', |
450e9415f90c92d64f814c363248db8250c5a8f2 | rest_framework_json_api/mixins.py | rest_framework_json_api/mixins.py | """
Class Mixins.
"""
class MultipleIDMixin(object):
"""
Override get_queryset for multiple id support
"""
def get_queryset(self):
"""
Override :meth:``get_queryset``
"""
ids = dict(getattr(self.request, 'query_params', self.request.QUERY_PARAMS)).get('ids[]')
if ids:
self.queryset = self.queryset.filter(id__in=ids)
return self.queryset
| """
Class Mixins.
"""
class MultipleIDMixin(object):
"""
Override get_queryset for multiple id support
"""
def get_queryset(self):
"""
Override :meth:``get_queryset``
"""
if hasattr(self.request, 'query_params'):
ids = dict(self.request.query_params).get('ids[]')
else:
ids = dict(self.request.QUERY_PARAMS).get('ids[]')
if ids:
self.queryset = self.queryset.filter(id__in=ids)
return self.queryset
| Fix for deprecation of `request.QUERY_PARAMS` in DRF 3.2` | Fix for deprecation of `request.QUERY_PARAMS` in DRF 3.2`
| Python | bsd-2-clause | grapo/django-rest-framework-json-api,aquavitae/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,kaldras/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api,django-json-api/rest_framework_ember,pombredanne/django-rest-framework-json-api,leo-naeka/rest_framework_ember,schtibe/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api | ---
+++
@@ -10,7 +10,10 @@
"""
Override :meth:``get_queryset``
"""
- ids = dict(getattr(self.request, 'query_params', self.request.QUERY_PARAMS)).get('ids[]')
+ if hasattr(self.request, 'query_params'):
+ ids = dict(self.request.query_params).get('ids[]')
+ else:
+ ids = dict(self.request.QUERY_PARAMS).get('ids[]')
if ids:
self.queryset = self.queryset.filter(id__in=ids)
return self.queryset |
dd11bcd4011ba911642b2e13d0db2440f749afa1 | setup.py | setup.py |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
Version = "0.01"
setup(name = "coverage-reporter",
version = Version,
description = "Coverage reporting tool",
long_description="Allows more complicated reporting of information from figleaf and other coverage tools",
author = "David Christian",
author_email = "david.chrsitian@gmail.com",
url = "http://github.org/dugan/coverage-reporter/",
packages = [ 'coverage_reporter', 'coverage_reporter.filters', 'coverage_reporter.collectors', 'coverage_reporter.reports' ],
license = 'BSD',
scripts = ['scripts/coverage-reporter'],
platforms = 'Posix; MacOS X; Windows',
classifiers = [ 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Development',
],
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
Version = "0.01"
setup(name = "coverage-reporter",
version = Version,
description = "Coverage reporting tool",
long_description="Allows more complicated reporting of information from figleaf and other coverage tools",
author = "David Christian",
author_email = "david.chrsitian@gmail.com",
url = "http://github.org/dugan/coverage-reporter/",
packages = [ 'coverage_reporter', 'coverage_reporter.filters', 'coverage_reporter.collectors', 'coverage_reporter.reports' ],
license = 'MIT',
scripts = ['scripts/coverage-reporter'],
platforms = 'Posix; MacOS X; Windows',
classifiers = [ 'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
| Mark this project as using the MIT License. | Mark this project as using the MIT License.
| Python | mit | dugan/coverage-reporter | ---
+++
@@ -14,12 +14,11 @@
author_email = "david.chrsitian@gmail.com",
url = "http://github.org/dugan/coverage-reporter/",
packages = [ 'coverage_reporter', 'coverage_reporter.filters', 'coverage_reporter.collectors', 'coverage_reporter.reports' ],
- license = 'BSD',
+ license = 'MIT',
scripts = ['scripts/coverage-reporter'],
platforms = 'Posix; MacOS X; Windows',
classifiers = [ 'Intended Audience :: Developers',
- 'License :: OSI Approved :: BSD License',
+ 'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
- 'Topic :: Development',
],
) |
9fcd338b568ec46ac16661a9aa497e619c092eeb | setup.py | setup.py | from distutils.core import setup
setup(name='dshelpers',
version='1.1.0',
description="Provides some helpers functions used by the ScraperWiki Data Services team.",
long_description="Provides some helpers functions used by the ScraperWiki Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="ScraperWiki Limited",
author_email='dataservices@scraperwiki.com',
url='http://scraperwiki.com',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
| from distutils.core import setup
setup(name='dshelpers',
version='1.1.0',
description="Provides some helpers functions used by the ScraperWiki Data Services team.",
long_description="Provides some helpers functions used by the ScraperWiki Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
author="ScraperWiki Limited",
author_email='dataservices@scraperwiki.com',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'],
install_requires=['requests',
'requests_cache',
'mock',
'nose',
'scraperwiki'],
)
| Change URL from ScraperWiki > source | Change URL from ScraperWiki > source | Python | bsd-2-clause | scraperwiki/data-services-helpers | ---
+++
@@ -12,7 +12,7 @@
],
author="ScraperWiki Limited",
author_email='dataservices@scraperwiki.com',
- url='http://scraperwiki.com',
+ url='https://github.com/scraperwiki/data-services-helpers',
license='BSD',
py_modules=['dshelpers'], |
d1951085f60f2d91d5ab0b42d83fbd5733bfa706 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = 'slf-project-one',
version = '0.1dev',
packages = find_packages(),
license = 'BSD',
long_description = open('README.rst').read(),
)
| from setuptools import setup, find_packages
setup(
name = 'slf-project-one',
version = '0.1dev',
packages = find_packages(),
license = 'BSD',
long_description = open('README.rst').read(),
# This causes the main function in project_one to be run when the
# project_one command is executed.
# Use this when setup.py should install an executable command.
entry_points={
'console_scripts': [
'project_one = project_one.project_one:main',
],
},
)
| Configure project_one as a script. | Configure project_one as a script.
This automatically runs main() when typing 'project_one' in the command line (after installing). | Python | bsd-3-clause | dokterbob/slf-project-one | ---
+++
@@ -6,4 +6,13 @@
packages = find_packages(),
license = 'BSD',
long_description = open('README.rst').read(),
+
+ # This causes the main function in project_one to be run when the
+ # project_one command is executed.
+ # Use this when setup.py should install an executable command.
+ entry_points={
+ 'console_scripts': [
+ 'project_one = project_one.project_one:main',
+ ],
+ },
) |
a7e6df9654bb526ed3d88d44fef44bf2a9ae493d | setup.py | setup.py | from setuptools import setup
version = "0.3.1"
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_require=[
"pytest",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| from setuptools import setup
version = "0.4.0"
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_require=[
"pytest",
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| Increment version to 0.4.0 for release | Increment version to 0.4.0 for release
| Python | mit | lukasschwab/arxiv.py | ---
+++
@@ -1,6 +1,6 @@
from setuptools import setup
-version = "0.3.1"
+version = "0.4.0"
setup(
name="arxiv", |
f562e0d2f258df59b9bfb74a5d18424a42bea65d | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "104.236.248.219:3128", # (Example) - set your own proxy here
"example2": "165.227.102.37:3128", # (Example) - set your own proxy here
"example3": "23.244.28.27:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "104.236.248.219:3128", # (Example) - set your own proxy here
"example2": "81.4.255.25:3128", # (Example) - set your own proxy here
"example3": "52.187.121.7:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| Update the proxy server examples | Update the proxy server examples
| Python | mit | seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -20,8 +20,8 @@
PROXY_LIST = {
"example1": "104.236.248.219:3128", # (Example) - set your own proxy here
- "example2": "165.227.102.37:3128", # (Example) - set your own proxy here
- "example3": "23.244.28.27:3128", # (Example) - set your own proxy here
+ "example2": "81.4.255.25:3128", # (Example) - set your own proxy here
+ "example3": "52.187.121.7:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None, |
296223d370baea719c56726d71118ec0d4a8a665 | setup.py | setup.py | import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(sys.argv[0]) or ".")
import libsongtext
version = '%s.%s.%s' % libsongtext.__version__
try:
long_description = open('README.rst', 'U').read()
except IOError:
long_description = 'See https://github.com/ysim/songtext'
setup(
name='songtext',
version=version,
description='a command-line song lyric fetcher',
long_description=long_description,
url='https://github.com/ysim/songtext',
author='ysim',
author_email='opensource@yiqingsim.net',
packages=find_packages(),
entry_points={
'console_scripts': [
'songtext = libsongtext.songtext:main',
],
},
install_requires=[
'click==7.0',
'cssselect==1.0.3',
'lxml==4.3.0',
'requests==2.21.0',
],
license='BSD',
keywords='console command line music song lyrics',
classifiers=[
'Environment :: Console',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
],
)
| import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(sys.argv[0]) or ".")
import libsongtext
version = '%s.%s.%s' % libsongtext.__version__
try:
long_description = open('README.rst', 'U').read()
except IOError:
long_description = 'See https://github.com/ysim/songtext'
setup(
name='songtext',
version=version,
description='a command-line song lyric fetcher',
long_description=long_description,
url='https://github.com/ysim/songtext',
author='ysim',
author_email='opensource@yiqingsim.net',
packages=find_packages(),
entry_points={
'console_scripts': [
'songtext = libsongtext.songtext:main',
],
},
install_requires=[
'click==7.0',
'cssselect==1.0.3',
'lxml==4.3.4',
'requests==2.21.0',
],
license='BSD',
keywords='console command line music song lyrics',
classifiers=[
'Environment :: Console',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
],
)
| Upgrade lxml package from 4.3.0 -> 4.3.4 | Upgrade lxml package from 4.3.0 -> 4.3.4
| Python | bsd-2-clause | ysim/songtext,ysim/songtext | ---
+++
@@ -33,7 +33,7 @@
install_requires=[
'click==7.0',
'cssselect==1.0.3',
- 'lxml==4.3.0',
+ 'lxml==4.3.4',
'requests==2.21.0',
],
|
f6d6cae28b5fdc49a5f56fe1713bd0fbb02c1dff | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
import pubcode
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='PubCode',
version=pubcode.__version__,
description='A simple module for creating barcodes.',
long_description=long_description,
url='https://github.com/Venti-/pubcode',
author='Ari Koivula',
author_email='ari@koivu.la',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Multimedia :: Graphics',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
packages=find_packages(exclude=['tests']),
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
import pubcode
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='PubCode',
version=pubcode.__version__,
description='A simple module for creating barcodes.',
long_description=long_description,
url='https://github.com/Venti-/pubcode',
author='Ari Koivula',
author_email='ari@koivu.la',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Multimedia :: Graphics',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
install_requires=[
"future", # For Python3 like builtins in Python2.
],
packages=find_packages(exclude=['tests']),
)
| Add future to install requirements. | Add future to install requirements.
| Python | mit | Venti-/pubcode | ---
+++
@@ -32,5 +32,9 @@
'Programming Language :: Python :: 3.4',
],
+ install_requires=[
+ "future", # For Python3 like builtins in Python2.
+ ],
+
packages=find_packages(exclude=['tests']),
) |
6775a5c58bd85dce644330dfd509d8f23135c5fe | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.5.40,<2.0.0',
'typing==3.5.3.0',
'six>=1.10.0,<2.0.0',
'pip>=9,<10'
]
setup(
name='chalice',
version='0.10.1',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='js@jamesls.com',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.5.40,<2.0.0',
'typing==3.5.3.0',
'six>=1.10.0,<2.0.0',
'pip>=9,<10'
]
setup(
name='chalice',
version='0.10.1',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='js@jamesls.com',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
],
)
| Change dev status to beta, not pre-alpha | Change dev status to beta, not pre-alpha
There's no RC classifier, so beta looks like the closest
one we can use.
| Python | apache-2.0 | awslabs/chalice | ---
+++
@@ -35,7 +35,7 @@
]
},
classifiers=[
- 'Development Status :: 2 - Pre-Alpha',
+ 'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English', |
94318fdc01afe6c21626ff074bafe46a6efafeb0 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.0.13',
description="Common function when working with excel.",
long_description=readme + '\n\n' + history,
author="Khemanorak Khath",
author_email='khath.khemanorak@gmail.com',
url='https://github.com/NorakGithub/django_excel_tools',
packages=find_packages(include=['django_excel_tools']),
include_package_data=True,
license="MIT license",
zip_safe=False,
keywords='django, excel, tools',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.1.0',
description="Common function when working with excel.",
long_description=readme + '\n\n' + history,
author="Khemanorak Khath",
author_email='khath.khemanorak@gmail.com',
url='https://github.com/NorakGithub/django_excel_tools',
packages=find_packages(include=['django_excel_tools']),
include_package_data=True,
license="MIT license",
zip_safe=False,
keywords='django, excel, tools',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| Update feature version to 0.1.0 | Update feature version to 0.1.0
| Python | mit | NorakGithub/django-excel-tools | ---
+++
@@ -13,7 +13,7 @@
setup(
name='django_excel_tools',
- version='0.0.13',
+ version='0.1.0',
description="Common function when working with excel.",
long_description=readme + '\n\n' + history,
author="Khemanorak Khath", |
8e56648242669697612b4e290e1d5d8e1f06dba9 | setup.py | setup.py | from setuptools import setup, find_packages
import os
from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license
import pypandoc
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
with open('README.md') as readme_md:
readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
setup(
name=name,
version=version,
author=author,
url="https://github.com/khazhyk/osuapi",
license="MIT",
long_description=readme,
keywords="osu",
packages=find_packages(),
description="osu! api wrapper.",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Utilities"
]
)
| from setuptools import setup, find_packages
import os
from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
try:
import pypandoc
except ImportError:
readme = None
else:
with open('README.md') as readme_md:
readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
setup(
name=name,
version=version,
author=author,
url="https://github.com/khazhyk/osuapi",
license="MIT",
long_description=readme,
keywords="osu",
packages=find_packages(),
description="osu! api wrapper.",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Utilities"
]
)
| Fix implicit dependency on pypandoc | Fix implicit dependency on pypandoc
| Python | mit | khazhyk/osuapi | ---
+++
@@ -1,14 +1,18 @@
from setuptools import setup, find_packages
import os
from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license
-import pypandoc
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
-with open('README.md') as readme_md:
- readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
+try:
+ import pypandoc
+except ImportError:
+ readme = None
+else:
+ with open('README.md') as readme_md:
+ readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
setup(
name=name, |
c45b89a6be7df2131dc5ed2e29b1cc2fe6ea061f | setup.py | setup.py | import os
from setuptools import setup
def get_version():
"""
Get the version from version module without importing more than
necessary.
"""
version_module_path = os.path.join(os.path.dirname(__file__), "eliot",
"_version.py")
# The version module contains a variable called __version__
with open(version_module_path) as version_module:
exec(version_module.read())
return locals()["__version__"]
def read(path):
"""
Read the contents of a file.
"""
with open(path) as f:
return f.read()
setup(
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
name='eliot',
version=get_version(),
description="Logging as Storytelling",
install_requires=["six", "zope.interface"],
keywords="logging",
license="APL2",
packages=["eliot", "eliot.tests"],
url="https://github.com/hybridcluster/eliot/",
maintainer='Itamar Turner-Trauring',
maintainer_email='itamar@hybridcluster.com',
long_description=read('README.rst'),
)
| import os
from setuptools import setup
def get_version():
"""
Get the version from version module without importing more than
necessary.
"""
version_module_path = os.path.join(os.path.dirname(__file__), "eliot",
"_version.py")
# The version module contains a variable called __version__
with open(version_module_path) as version_module:
exec(version_module.read())
return locals()["__version__"]
def read(path):
"""
Read the contents of a file.
"""
with open(path) as f:
return f.read()
setup(
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
name='eliot',
version=get_version(),
description="Logging as Storytelling",
install_requires=["six", "zope.interface"],
extras_require={
"dev": [
# Allows us to measure code coverage:
"coverage",
]
},
keywords="logging",
license="APL2",
packages=["eliot", "eliot.tests"],
url="https://github.com/hybridcluster/eliot/",
maintainer='Itamar Turner-Trauring',
maintainer_email='itamar@hybridcluster.com',
long_description=read('README.rst'),
)
| Add coverage as optional dev requirement. | Add coverage as optional dev requirement.
| Python | apache-2.0 | ScatterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot,ClusterHQ/eliot,iffy/eliot | ---
+++
@@ -42,6 +42,12 @@
version=get_version(),
description="Logging as Storytelling",
install_requires=["six", "zope.interface"],
+ extras_require={
+ "dev": [
+ # Allows us to measure code coverage:
+ "coverage",
+ ]
+ },
keywords="logging",
license="APL2",
packages=["eliot", "eliot.tests"], |
4da7debc49cc87a243f8fc93a2fccbd4e276da26 | setup.py | setup.py | import sys
# Make sure we are running python3.5+
if 10 * sys.version_info[0] + sys.version_info[1] < 35:
sys.exit("Sorry, only Python 3.5+ is supported.")
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(
name = 'med2image',
version = '1.1.1',
description = '(Python) utility to convert medical images to jpg and png',
long_description = readme(),
author = 'FNNDSC',
author_email = 'dev@babymri.org',
url = 'https://github.com/FNNDSC/med2image',
packages = ['med2image'],
install_requires = ['nibabel', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
#test_suite = 'nose.collector',
#tests_require = ['nose'],
scripts = ['bin/med2image'],
license = 'MIT',
zip_safe = False
) | import sys
# Make sure we are running python3.5+
if 10 * sys.version_info[0] + sys.version_info[1] < 35:
sys.exit("Sorry, only Python 3.5+ is supported.")
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(
name = 'med2image',
version = '1.1.1',
description = '(Python) utility to convert medical images to jpg and png',
long_description = readme(),
author = 'FNNDSC',
author_email = 'dev@babymri.org',
url = 'https://github.com/FNNDSC/med2image',
packages = ['med2image'],
install_requires = ['nibabel', 'dicom', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
#test_suite = 'nose.collector',
#tests_require = ['nose'],
scripts = ['bin/med2image'],
license = 'MIT',
zip_safe = False
)
| Add 'dicom' package to the requirements | Add 'dicom' package to the requirements
| Python | mit | FNNDSC/med2image,FNNDSC/med2image | ---
+++
@@ -19,7 +19,7 @@
author_email = 'dev@babymri.org',
url = 'https://github.com/FNNDSC/med2image',
packages = ['med2image'],
- install_requires = ['nibabel', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
+ install_requires = ['nibabel', 'dicom', 'pydicom', 'numpy', 'matplotlib', 'pillow'],
#test_suite = 'nose.collector',
#tests_require = ['nose'],
scripts = ['bin/med2image'], |
61eaf65a721ffe5820522a1d4afac5cdafe2a0a3 | deuce/drivers/storage/blocks/disk/DiskStorageDriver.py | deuce/drivers/storage/blocks/disk/DiskStorageDriver.py |
from pecan import conf
import os
class DiskStorageDriver(object):
"""A driver for storing blocks onto local disk
IMPORTANT: This driver should not be considered
secure and therefore should not be ran in
any production environment.
"""
def __init__(self):
# Load the pecan config
self._path = conf.block_storage_driver.options.path
if not os.path.exists(self._path):
# TODO: Use a real exception
raise Exception("Block path does not exist {0}"
.format(self._path))
def block_exists(self, vault_id, block_id):
path = os.path.join(self._path, block_id)
return os.path.exists(path)
def get_block_obj(self, vault_id, block_id):
"""Returns a file-like object capable or streaming the
block data. If the object cannot be retrieved, the list
of objects should be returned
"""
path = os.path.join(self._path, block_id)
if not os.path.exists(path):
return None
return open(path, 'rb')
def get_objects_list(self, vault_id):
"""Lists (and yields) a list of each object that is in
a particular vault
"""
pass
|
from pecan import conf
import os
import io
class DiskStorageDriver(object):
"""A driver for storing blocks onto local disk
IMPORTANT: This driver should not be considered
secure and therefore should not be ran in
any production environment.
"""
def __init__(self):
# Load the pecan config
self._path = conf.block_storage_driver.options.path
if not os.path.exists(self._path):
# TODO: Use a real exception
raise Exception("Block path does not exist {0}"
.format(self._path))
def block_exists(self, vault_id, block_id):
path = os.path.join(self._path, block_id)
return os.path.exists(path)
def insert_block_obj(self, vault_id, block_id, blockdata):
"""
"""
path = os.path.join(self._path, block_id)
if os.path.exists(path):
print ("File ",path," existed")
#TODO: need compare both?
return True
else:
print ("File ",path," not existed")
fd = open (path, 'w+')
fd.write(blockdata)
fd.close()
return True
def get_block_obj(self, vault_id, block_id):
"""Returns a file-like object capable or streaming the
block data. If the object cannot be retrieved, the list
of objects should be returned
"""
path = os.path.join(self._path, block_id)
if not os.path.exists(path):
return None
return open(path, 'rb')
def get_objects_list(self, vault_id):
"""Lists (and yields) a list of each object that is in
a particular vault
"""
pass
| Save one block to storage | Save one block to storage
| Python | apache-2.0 | rackerlabs/deuce | ---
+++
@@ -2,6 +2,7 @@
from pecan import conf
import os
+import io
class DiskStorageDriver(object):
"""A driver for storing blocks onto local disk
@@ -26,6 +27,24 @@
return os.path.exists(path)
+ def insert_block_obj(self, vault_id, block_id, blockdata):
+ """
+ """
+ path = os.path.join(self._path, block_id)
+
+ if os.path.exists(path):
+ print ("File ",path," existed")
+ #TODO: need compare both?
+ return True
+ else:
+ print ("File ",path," not existed")
+
+ fd = open (path, 'w+')
+ fd.write(blockdata)
+ fd.close()
+ return True
+
+
def get_block_obj(self, vault_id, block_id):
"""Returns a file-like object capable or streaming the
block data. If the object cannot be retrieved, the list |
edcdf92d1c9aca515ac05a165e6bfc2392be6d46 | setup.py | setup.py | import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'pyodbc',
'peewee'
]
version = '0.1.3'
setup(
name='peewee_mssql',
version=version,
py_modules=['peewee_mssql'],
description='MS SQL Server support for the peewee ORM',
long_description=README,
author='Constantin Roganov',
author_email='rccbox@gmail.com',
url='https://github.com/brake/peewee_mssql',
download_url='https://github.com/brake/peewee_mssql/archive/' + version + '.zip',
keywords=['database', 'ORM', 'peewee', 'mssql'],
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: MIT License',
'Topic :: Database',
],
install_requires=requires,
)
| import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'pyodbc',
'peewee'
]
version = '0.1.4'
setup(
name='peewee_mssqlserv',
version=version,
py_modules=['peewee_mssqlserv'],
description='MS SQL Server support for the peewee ORM',
long_description=README,
author='Constantin Roganov',
author_email='rccbox@gmail.com',
url='https://github.com/brake/peewee_mssql',
download_url='https://github.com/brake/peewee_mssql/archive/' + version + '.zip',
keywords=['database', 'ORM', 'peewee', 'mssql'],
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: MIT License',
'Topic :: Database',
],
install_requires=requires,
)
| Package name changed due to collision on PyPi | Package name changed due to collision on PyPi
| Python | mit | brake/peewee_mssql | ---
+++
@@ -12,12 +12,12 @@
'peewee'
]
-version = '0.1.3'
+version = '0.1.4'
setup(
- name='peewee_mssql',
+ name='peewee_mssqlserv',
version=version,
- py_modules=['peewee_mssql'],
+ py_modules=['peewee_mssqlserv'],
description='MS SQL Server support for the peewee ORM',
long_description=README,
author='Constantin Roganov', |
29da663d6b27e760087fed62ee5717b47f26531a | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.10.1.dev0',
author='Abhinav Gupta, Aiden Scandella, Bryce Lampe, Grayson Koonce, Junchao Wu',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(include=['tchannel.*']),
install_requires=[
'contextlib2',
'crcmod',
'tornado>=4.0,<5.0',
'toro>=0.8,<0.9',
'threadloop>=0.3,<0.4',
'futures',
],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:start_ioloop'
]
},
)
| from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.10.1.dev0',
author='Abhinav Gupta, Aiden Scandella, Bryce Lampe, Grayson Koonce, Junchao Wu',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(exclude=['tests.*']),
install_requires=[
'contextlib2',
'crcmod',
'tornado>=4.0,<5.0',
'toro>=0.8,<0.9',
'threadloop>=0.3,<0.4',
'futures',
],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:start_ioloop'
]
},
)
| Remove include clause from find_packages | Remove include clause from find_packages
It's not supported on older versions of pip | Python | mit | Willyham/tchannel-python,uber/tchannel-python,uber/tchannel-python,Willyham/tchannel-python | ---
+++
@@ -9,7 +9,7 @@
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
- packages=find_packages(include=['tchannel.*']),
+ packages=find_packages(exclude=['tests.*']),
install_requires=[
'contextlib2',
'crcmod', |
8b4fc00e7a5ac1d416d54952cbb6d09ef328a9c3 | cache_keras_weights.py | cache_keras_weights.py | from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3
resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')
| from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3
from keras.applications.xception import Xception
resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')
xception = Xception(weights='imagenet')
| Add Xception to keras cache | Add Xception to keras cache
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | ---
+++
@@ -2,8 +2,10 @@
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3
+from keras.applications.xception import Xception
resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')
+xception = Xception(weights='imagenet') |
d629cc508cb2d3eab83e259d9aefc9885076a407 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='wagtailcodeblock',
version="0.4.0",
description='Wagtail Code Block provides PrismJS syntax highlighting in Wagtail.',
long_description='A Wagtail Streamfield block for source code with real-time syntax highlighting.',
author='Tim Allen',
author_email='tallen@wharton.upenn.edu',
url='https://github.com/FlipperPA/wagtailcodeblock',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
install_requires=[
'wagtail>=1.8',
],
classifiers=[
'Development Status :: 3 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| from setuptools import setup, find_packages
setup(
name='wagtailcodeblock',
version="0.4.0",
description='Wagtail Code Block provides PrismJS syntax highlighting in Wagtail.',
long_description='A Wagtail Streamfield block for source code with real-time syntax highlighting.',
author='Tim Allen',
author_email='tallen@wharton.upenn.edu',
url='https://github.com/FlipperPA/wagtailcodeblock',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
install_requires=[
'wagtail>=1.8',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| Move up to be a beta. | Move up to be a beta.
| Python | bsd-3-clause | FlipperPA/wagtailcodeblock,FlipperPA/wagtailcodeblock,FlipperPA/wagtailcodeblock | ---
+++
@@ -14,7 +14,7 @@
'wagtail>=1.8',
],
classifiers=[
- 'Development Status :: 3 - Beta',
+ 'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', |
b64c713555bfbfa4eb8d483a6da17853ceaa6078 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.3',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main',
'update-downloads = autobuilder.scripts.update_downloads:main',
'install-sdk = autobuilder.scripts.install_sdk:main',
'autorev-report = autobuilder.scripts.autorev_report:main'
]
},
include_package_data=True,
package_data={
'autobuilder': ['templates/*.txt']
},
install_requires=['buildbot[tls]>=1.4.0',
'buildbot-worker>=1.4.0',
'buildbot-www>=1.4.0',
'buildbot-console-view>=1.4.0',
'buildbot-grid-view>=1.4.0',
'buildbot-waterfall-view>=1.4.0'
'buildbot-badges>=1.4.0',
'boto3', 'botocore',
'treq', 'twisted',
'python-dateutil']
)
| from setuptools import setup, find_packages
setup(
name='autobuilder',
version='1.0.3',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
entry_points={
'console_scripts': [
'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main',
'update-downloads = autobuilder.scripts.update_downloads:main',
'install-sdk = autobuilder.scripts.install_sdk:main',
'autorev-report = autobuilder.scripts.autorev_report:main'
]
},
include_package_data=True,
package_data={
'autobuilder': ['templates/*.txt']
},
install_requires=['buildbot[tls]>=1.5.0',
'buildbot-worker>=1.5.0',
'buildbot-www>=1.5.0',
'buildbot-console-view>=1.5.0',
'buildbot-grid-view>=1.5.0',
'buildbot-waterfall-view>=1.5.0'
'buildbot-badges>=1.5.0',
'boto3', 'botocore',
'treq', 'twisted',
'python-dateutil']
)
| Update buildbot packages to >= 1.5.0. | Update buildbot packages to >= 1.5.0.
| Python | mit | madisongh/autobuilder | ---
+++
@@ -19,13 +19,13 @@
package_data={
'autobuilder': ['templates/*.txt']
},
- install_requires=['buildbot[tls]>=1.4.0',
- 'buildbot-worker>=1.4.0',
- 'buildbot-www>=1.4.0',
- 'buildbot-console-view>=1.4.0',
- 'buildbot-grid-view>=1.4.0',
- 'buildbot-waterfall-view>=1.4.0'
- 'buildbot-badges>=1.4.0',
+ install_requires=['buildbot[tls]>=1.5.0',
+ 'buildbot-worker>=1.5.0',
+ 'buildbot-www>=1.5.0',
+ 'buildbot-console-view>=1.5.0',
+ 'buildbot-grid-view>=1.5.0',
+ 'buildbot-waterfall-view>=1.5.0'
+ 'buildbot-badges>=1.5.0',
'boto3', 'botocore',
'treq', 'twisted',
'python-dateutil'] |
e5ac63b4615b4166d7e7866c9f169e4c9f86f46c | setup.py | setup.py | from distutils.core import setup
setup(
name='django-emailuser',
version='1.0',
description='simple User model identified by email address',
packages=['emailuser'],
author='Mark Paschal',
author_email='markpasc@markpasc.org',
url='https://github.com/duncaningram/django-emailuser',
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
)
| from distutils.core import setup
setup(
name='django-emailuser',
version='1.0',
description='simple User model identified by email address',
packages=['emailuser', 'emailuser.management', 'emailuser.management.commands'],
author='Mark Paschal',
author_email='markpasc@markpasc.org',
url='https://github.com/duncaningram/django-emailuser',
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
)
| Install the management command too when installing as a distribution | Install the management command too when installing as a distribution
| Python | mit | markpasc/django-emailuser,duncaningram/django-emailuser | ---
+++
@@ -5,7 +5,7 @@
name='django-emailuser',
version='1.0',
description='simple User model identified by email address',
- packages=['emailuser'],
+ packages=['emailuser', 'emailuser.management', 'emailuser.management.commands'],
author='Mark Paschal',
author_email='markpasc@markpasc.org', |
1a13e9da4e3955aaa7c52792d91638966d29de9c | sensor_consumers/bathroom_door.py | sensor_consumers/bathroom_door.py | # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "bathroom")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
}
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
| # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
}
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
| Use a single database for all air quality measurements | Use a single database for all air quality measurements
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | ---
+++
@@ -8,7 +8,7 @@
class Bathroom(SensorConsumerBase):
def __init__(self):
- SensorConsumerBase.__init__(self, "bathroom")
+ SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback) |
13c26818cbb217ac4e27b94f188f239152fa85b8 | timer.py | timer.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import division, print_function
from time import time
class Timer(object):
""" Simple timing object.
Usage:
with Timer('Function took'):
do_something()
"""
def __init__(self, msg='Timer'):
"""
:msg: Additional message to show after finishing timing.
"""
self._msg = msg
def __enter__(self):
self._start = time()
def __exit__(self, *args):
print('{}: {}s'.format(self._msg, time() - self._start))
| #!/usr/bin/env python
# encoding: utf-8
from __future__ import division, print_function
from time import time
class Timer(object):
""" Simple timing object.
Usage:
with Timer('Function took'):
do_something()
"""
def __init__(self, msg='Timer'):
"""
:msg: Additional message to show after finishing timing.
"""
self._msg = msg
self._start = None
def __enter__(self):
self._start = time()
def __exit__(self, *args):
print('{}: {}s'.format(self._msg, time() - self._start))
| Set start variable in init function | Set start variable in init function
| Python | unlicense | dseuss/pythonlibs | ---
+++
@@ -20,6 +20,7 @@
"""
self._msg = msg
+ self._start = None
def __enter__(self):
self._start = time() |
af59d91afdddf9a5f3f673dd7bba98ad4538ec55 | go_store_service/tests/test_api_handler.py | go_store_service/tests/test_api_handler.py | from unittest import TestCase
from go_store_service.api_handler import (
ApiApplication, create_urlspec_regex, CollectionHandler,
ElementHandler)
class TestCreateUrlspecRegex(TestCase):
def test_no_variables(self):
self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar")
class TestApiApplication(TestCase):
def test_build_routes(self):
collection_factory = lambda **kw: "collection"
app = ApiApplication()
app.collections = (
('/:owner_id/store', collection_factory),
)
[collection_route, elem_route] = app._build_routes()
self.assertEqual(collection_route.handler_class, CollectionHandler)
self.assertEqual(collection_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store$")
self.assertEqual(collection_route.kwargs, {
"collection_factory": collection_factory,
})
self.assertEqual(elem_route.handler_class, ElementHandler)
self.assertEqual(elem_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$")
self.assertEqual(elem_route.kwargs, {
"collection_factory": collection_factory,
})
| from unittest import TestCase
from go_store_service.api_handler import (
ApiApplication, create_urlspec_regex, CollectionHandler,
ElementHandler)
class TestCreateUrlspecRegex(TestCase):
def test_no_variables(self):
self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar")
def test_one_variable(self):
self.assertEqual(
create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar")
def test_two_variables(self):
self.assertEqual(
create_urlspec_regex("/:foo/bar/:baz"),
"/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)")
class TestApiApplication(TestCase):
def test_build_routes(self):
collection_factory = lambda **kw: "collection"
app = ApiApplication()
app.collections = (
('/:owner_id/store', collection_factory),
)
[collection_route, elem_route] = app._build_routes()
self.assertEqual(collection_route.handler_class, CollectionHandler)
self.assertEqual(collection_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store$")
self.assertEqual(collection_route.kwargs, {
"collection_factory": collection_factory,
})
self.assertEqual(elem_route.handler_class, ElementHandler)
self.assertEqual(elem_route.regex.pattern,
"/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$")
self.assertEqual(elem_route.kwargs, {
"collection_factory": collection_factory,
})
| Add test for passing paths with variables to create_urlspec_regex. | Add test for passing paths with variables to create_urlspec_regex.
| Python | bsd-3-clause | praekelt/go-store-service | ---
+++
@@ -8,6 +8,15 @@
class TestCreateUrlspecRegex(TestCase):
def test_no_variables(self):
self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar")
+
+ def test_one_variable(self):
+ self.assertEqual(
+ create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar")
+
+ def test_two_variables(self):
+ self.assertEqual(
+ create_urlspec_regex("/:foo/bar/:baz"),
+ "/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)")
class TestApiApplication(TestCase): |
539fae27f9911b9ad13edc5244ffbd12b1509006 | utils.py | utils.py | """
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['mstack', 'wget']
def mstack(vs, fs):
import chumpy as ch
import numpy as np
lengths = [v.shape[0] for v in vs]
f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))])
v = ch.vstack(vs)
return v, f
def wget(url, dest_fname=None):
import urllib.request, urllib.error, urllib.parse
from os.path import split, join
curdir = split(__file__)[0]
print(url)
if dest_fname is None:
dest_fname = join(curdir, split(url)[1])
try:
contents = urllib.request.urlopen(url).read()
except:
raise Exception('Unable to get url: %s' % (url,))
open(dest_fname, 'w').write(contents)
| """
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['mstack', 'wget']
def mstack(vs, fs):
import chumpy as ch
import numpy as np
lengths = [v.shape[0] for v in vs]
f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))])
v = ch.vstack(vs)
return v, f
def wget(url, dest_fname=None):
try: #python3
from urllib.request import urlopen
except: #python2
from urllib2 import urlopen
from os.path import split, join
curdir = split(__file__)[0]
print(url)
if dest_fname is None:
dest_fname = join(curdir, split(url)[1])
try:
contents = urlopen(url).read()
except:
raise Exception('Unable to get url: %s' % (url,))
open(dest_fname, 'w').write(contents)
| Fix for python2/3 compatibility issue with urllib | Fix for python2/3 compatibility issue with urllib
| Python | mit | mattloper/opendr,mattloper/opendr | ---
+++
@@ -16,7 +16,11 @@
def wget(url, dest_fname=None):
- import urllib.request, urllib.error, urllib.parse
+ try: #python3
+ from urllib.request import urlopen
+ except: #python2
+ from urllib2 import urlopen
+
from os.path import split, join
curdir = split(__file__)[0]
@@ -27,7 +31,7 @@
dest_fname = join(curdir, split(url)[1])
try:
- contents = urllib.request.urlopen(url).read()
+ contents = urlopen(url).read()
except:
raise Exception('Unable to get url: %s' % (url,))
open(dest_fname, 'w').write(contents) |
69d1f91c48ab022a56232debdec14f5a5a449cbc | src/handlers/custom.py | src/handlers/custom.py | import flask
from handlers import app
import db.query as q
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/api/perspective/random')
def random_perspective():
return flask.jsonify(
q.random_perspective().to_dict()
)
| import flask
from handlers import app
import db.query as q
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/api/perspective/random')
def random_perspective():
random_id = q.random_perspective().id
return flask.redirect('/api/perspective/%s' % random_id)
@app.route('/api/round/latest')
def latest_round():
round_id = q.latest_round().id
return flask.redirect("/api/round/%s" % round_id)
| Use flask redirects for random perspective and latest round | Use flask redirects for random perspective and latest round
| Python | apache-2.0 | pascalc/narrative-roulette,pascalc/narrative-roulette | ---
+++
@@ -9,6 +9,10 @@
@app.route('/api/perspective/random')
def random_perspective():
- return flask.jsonify(
- q.random_perspective().to_dict()
- )
+ random_id = q.random_perspective().id
+ return flask.redirect('/api/perspective/%s' % random_id)
+
+@app.route('/api/round/latest')
+def latest_round():
+ round_id = q.latest_round().id
+ return flask.redirect("/api/round/%s" % round_id) |
cf20a04b0fb50993e746945f586160b96a0f16b1 | magnum/api/validation.py | magnum/api/validation.py | # Copyright 2015 Huawei Technologies Co.,LTD.
#
# 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 decorator
import pecan
from magnum.common import exception
from magnum import objects
def enforce_bay_types(*bay_types):
def decorate(func):
@decorator.decorator
def handler(func, *args, **kwargs):
obj = args[1]
bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid)
baymodel = objects.BayModel.get_by_uuid(pecan.request.context,
bay.baymodel_id)
if baymodel.coe not in bay_types:
raise exception.InvalidParameterValue(
'Cannot fulfill request with a %(bay_type)s bay, '
'expecting a %(supported_bay_types)s bay.' %
{'bay_type': baymodel.coe,
'supported_bay_types': '/'.join(bay_types)})
return func(*args, **kwargs)
return handler(func)
return decorate
| # Copyright 2015 Huawei Technologies Co.,LTD.
#
# 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 decorator
import pecan
from magnum.common import exception
from magnum import objects
def enforce_bay_types(*bay_types):
@decorator.decorator
def wrapper(func, *args, **kwargs):
obj = args[1]
bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid)
baymodel = objects.BayModel.get_by_uuid(pecan.request.context,
bay.baymodel_id)
if baymodel.coe not in bay_types:
raise exception.InvalidParameterValue(
'Cannot fulfill request with a %(bay_type)s bay, '
'expecting a %(supported_bay_types)s bay.' %
{'bay_type': baymodel.coe,
'supported_bay_types': '/'.join(bay_types)})
return func(*args, **kwargs)
return wrapper
| Correct the usage of decorator.decorator | Correct the usage of decorator.decorator
Correct the usage of decorator.decorator as described in [1].
[1]http://pythonhosted.org/decorator/documentation.html#decorator-decorator
Change-Id: Ia71b751f364e09541faecf6a43f252e0b856558e
Closes-Bug: #1483464
| Python | apache-2.0 | Alzon/SUR,eshijia/SUR,jay-lau/magnum,dimtruck/magnum,ArchiFleKs/magnum,Tennyson53/magnum,Alzon/SUR,eshijia/magnum,Tennyson53/magnum,ddepaoli3/magnum,annegentle/magnum,ramielrowe/magnum,eshijia/magnum,ArchiFleKs/magnum,openstack/magnum,ramielrowe/magnum,mjbrewer/testindex,mjbrewer/testindex,Tennyson53/SUR,ffantast/magnum,eshijia/SUR,dimtruck/magnum,annegentle/magnum,ffantast/magnum,ddepaoli3/magnum,mjbrewer/testindex,Tennyson53/SUR,openstack/magnum | ---
+++
@@ -21,21 +21,19 @@
def enforce_bay_types(*bay_types):
- def decorate(func):
- @decorator.decorator
- def handler(func, *args, **kwargs):
- obj = args[1]
- bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid)
- baymodel = objects.BayModel.get_by_uuid(pecan.request.context,
- bay.baymodel_id)
- if baymodel.coe not in bay_types:
- raise exception.InvalidParameterValue(
- 'Cannot fulfill request with a %(bay_type)s bay, '
- 'expecting a %(supported_bay_types)s bay.' %
- {'bay_type': baymodel.coe,
- 'supported_bay_types': '/'.join(bay_types)})
+ @decorator.decorator
+ def wrapper(func, *args, **kwargs):
+ obj = args[1]
+ bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid)
+ baymodel = objects.BayModel.get_by_uuid(pecan.request.context,
+ bay.baymodel_id)
+ if baymodel.coe not in bay_types:
+ raise exception.InvalidParameterValue(
+ 'Cannot fulfill request with a %(bay_type)s bay, '
+ 'expecting a %(supported_bay_types)s bay.' %
+ {'bay_type': baymodel.coe,
+ 'supported_bay_types': '/'.join(bay_types)})
- return func(*args, **kwargs)
- return handler(func)
+ return func(*args, **kwargs)
- return decorate
+ return wrapper |
daeb8e38ec5b15650b9c5933789b6eab14b4a0a8 | website/jdevents/models.py | website/jdevents/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class Event(Displayable, RichText):
"""
Main object for each event.
Derives from Displayable, which by default
- it is related to a certain Site object
- it has a title and a slug
- it has SEO metadata
- it gets automated timestamps when the object is updated
Besides that, it derives from RichText, which provides a WYSIWYG field.
"""
class Occurence(models.Model):
"""
Represents an occurence of an event. Can be automatically repeated
"""
event = models.ForeignKey(Event)
start = models.DateTimeField()
end = models.DateTimeField()
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class Event(Displayable, RichText):
"""
Main object for each event.
Derives from Displayable, which by default
- it is related to a certain Site object
- it has a title and a slug
- it has SEO metadata
- it gets automated timestamps when the object is updated
Besides that, it derives from RichText, which provides a WYSIWYG field.
"""
class Occurence(models.Model):
"""
Represents an occurence of an event. Can be automatically repeated
"""
event = models.ForeignKey(Event)
start = models.DateTimeField()
end = models.DateTimeField()
extra_information = models.CharField(max_length=255, blank=True, null=True)
| Add posibility to add extra information to occurence. | Add posibility to add extra information to occurence.
| Python | mit | jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website | ---
+++
@@ -25,4 +25,5 @@
event = models.ForeignKey(Event)
start = models.DateTimeField()
end = models.DateTimeField()
+ extra_information = models.CharField(max_length=255, blank=True, null=True)
|
cbe39a8f63ca792715370bac7d28b39bae8b0c86 | LandPortalEntities/lpentities/measurement_unit.py | LandPortalEntities/lpentities/measurement_unit.py | '''
Created on 02/02/2014
@author: Miguel Otero
'''
class MeasurementUnit(object):
'''
classdocs
'''
RANK = "rank"
INDEX = "index"
UNITS = "units"
SQ_KM = "sq. km"
PERCENTAGE = "%"
#Enum possible convert_to values
def __init__(self, name=None, convert_to=None, factor=1):
'''
Constructor
'''
self.name = name
self.convert_to = convert_to
self.factor = factor
def __get_convert_to(self):
return self.convert_to
def __set_convert_to(self, value):
if value not in [self.RANK, self.INDEX, self.UNITS, self.SQ_KM, self.PERCENTAGE]:
raise ValueError("Invalid provided convert_to value: {0}".format(value))
self.convert_to = value
convert_to = property(fget=__get_convert_to,
fset=__set_convert_to,
doc="The MeasurementUnit is convertible to this value")
| '''
Created on 02/02/2014
@author: Miguel Otero
'''
class MeasurementUnit(object):
'''
classdocs
'''
RANK = "rank"
INDEX = "index"
UNITS = "units"
SQ_KM = "sq. km"
PERCENTAGE = "%"
#Enum possible convert_to values
def __init__(self, name=None, convert_to=None, factor=1):
'''
Constructor
'''
self.name = name
self._convert_to = convert_to
self.factor = factor
def __get_convert_to(self):
return self._convert_to
def __set_convert_to(self, value):
if value not in [self.RANK, self.INDEX, self.UNITS, self.SQ_KM, self.PERCENTAGE]:
raise ValueError("Invalid provided convert_to value: {0}".format(value))
self._convert_to = value
convert_to = property(fget=__get_convert_to,
fset=__set_convert_to,
doc="The MeasurementUnit is convertible to this value")
| Fix small problem with properties | Fix small problem with properties
| Python | mit | weso/landportal-importers,landportal/landbook-importers,landportal/landbook-importers | ---
+++
@@ -24,16 +24,16 @@
Constructor
'''
self.name = name
- self.convert_to = convert_to
+ self._convert_to = convert_to
self.factor = factor
def __get_convert_to(self):
- return self.convert_to
+ return self._convert_to
def __set_convert_to(self, value):
if value not in [self.RANK, self.INDEX, self.UNITS, self.SQ_KM, self.PERCENTAGE]:
raise ValueError("Invalid provided convert_to value: {0}".format(value))
- self.convert_to = value
+ self._convert_to = value
convert_to = property(fget=__get_convert_to,
fset=__set_convert_to, |
ff39617b554d0feefc8d5518d33894e4c2e88941 | python/setup.py | python/setup.py | from setuptools import setup, find_packages
setup(
name='dex',
version='0.0.1',
description='A research language for typed, functional array processing',
license='BSD',
author='Adam Paszke',
author_email='apaszke@google.com',
packages=find_packages(),
package_data={'dex': ['libDex.so']},
install_requires=['numpy'],
)
| from setuptools import setup, find_packages
import os
# Check dex so file exists in dex directory.
so_file = "libDex.so"
dex_dir = os.path.join(os.path.dirname(__file__), 'dex')
if not os.path.exists(os.path.join(dex_dir, so_file)):
raise FileNotFoundError(f"{so_file} not found in dex/, "
"please run `make build-python`")
setup(
name='dex',
version='0.0.1',
description='A research language for typed, functional array processing',
license='BSD',
author='Adam Paszke',
author_email='apaszke@google.com',
packages=find_packages(),
package_data={'dex': ['libDex.so']},
install_requires=['numpy'],
)
| Add check for libDex.so file in dex dir. | Add check for libDex.so file in dex dir.
| Python | bsd-3-clause | google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang | ---
+++
@@ -1,5 +1,12 @@
from setuptools import setup, find_packages
+import os
+# Check dex so file exists in dex directory.
+so_file = "libDex.so"
+dex_dir = os.path.join(os.path.dirname(__file__), 'dex')
+if not os.path.exists(os.path.join(dex_dir, so_file)):
+ raise FileNotFoundError(f"{so_file} not found in dex/, "
+ "please run `make build-python`")
setup(
name='dex',
version='0.0.1', |
6ff8ffe74c5d107133258f051430d17cf421d105 | ella/ellaadmin/management/__init__.py | ella/ellaadmin/management/__init__.py | """
Copied over from django.contrib.auth.management
"""
from django.dispatch import dispatcher
from django.db.models import get_models, signals
def _get_permission_codename(action, opts):
return u'%s_%s' % (action, opts.object_name.lower())
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ]
def create_permissions(app, created_models, verbosity):
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
app_models = get_models(app)
if not app_models:
return
for klass in app_models:
ctype = ContentType.objects.get_for_model(klass)
for codename, name in _get_all_permissions(klass._meta):
p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
defaults={'name': name, 'content_type': ctype})
if created and verbosity >= 2:
print "Adding permission '%s'" % p
dispatcher.connect(create_permissions, signal=signals.post_syncdb)
| """
Copied over from django.contrib.auth.management
"""
from django.dispatch import dispatcher
from django.db.models import get_models, signals
def _get_permission_codename(action, opts):
return u'%s_%s' % (action, opts.object_name.lower())
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ]
def create_permissions(app, created_models, verbosity, **kwargs):
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
app_models = get_models(app)
if not app_models:
return
for klass in app_models:
ctype = ContentType.objects.get_for_model(klass)
for codename, name in _get_all_permissions(klass._meta):
p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
defaults={'name': name, 'content_type': ctype})
if created and verbosity >= 2:
print "Adding permission '%s'" % p
# TODO: check functionality - its new signals in django 1.0.x
signals.post_syncdb.connect(create_permissions)
| Update signals for latest django | Update signals for latest django
git-svn-id: 80df2eab91b5a6f595a6fdab3c86ff0105eb9aae@1867 2d143e24-0a30-0410-89d7-a2e95868dc81
| Python | bsd-3-clause | ella/ella,WhiskeyMedia/ella,petrlosa/ella,whalerock/ella,WhiskeyMedia/ella,MichalMaM/ella,whalerock/ella,petrlosa/ella,MichalMaM/ella,whalerock/ella | ---
+++
@@ -11,7 +11,7 @@
"Returns (codename, name) for all permissions in the given opts."
return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ]
-def create_permissions(app, created_models, verbosity):
+def create_permissions(app, created_models, verbosity, **kwargs):
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
app_models = get_models(app)
@@ -25,5 +25,6 @@
if created and verbosity >= 2:
print "Adding permission '%s'" % p
-dispatcher.connect(create_permissions, signal=signals.post_syncdb)
+# TODO: check functionality - its new signals in django 1.0.x
+signals.post_syncdb.connect(create_permissions)
|
b170c077ccd86280715dbc57cf2cac9a2327ff4b | django/__init__.py | django/__init__.py | VERSION = (1, 5, 0, 'final', 2)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| VERSION = (1, 5, 0, 'final', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
| Correct final element of version tuple. | [1.5.x] Correct final element of version tuple.
| Python | bsd-3-clause | ccn-2m/django,bliti/django-nonrel-1.5,ccn-2m/django,hasadna/django,alx-eu/django,ccn-2m/django,alx-eu/django,hasadna/django,alx-eu/django,imtapps/django-imt-fork,ccn-2m/django,bliti/django-nonrel-1.5,bliti/django-nonrel-1.5,alx-eu/django,imtapps/django-imt-fork,imtapps/django-imt-fork,hasadna/django | ---
+++
@@ -1,4 +1,4 @@
-VERSION = (1, 5, 0, 'final', 2)
+VERSION = (1, 5, 0, 'final', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the get_version stuff. |
2b07fdcefdc915e69580016d9c0a08ab8e478ce7 | chatterbot/adapters/logic/closest_match.py | chatterbot/adapters/logic/closest_match.py | # -*- coding: utf-8 -*-
from .base_match import BaseMatchAdapter
from fuzzywuzzy import fuzz
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter selects a response to an
input statement by selecting the closest known matching
statement based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text, statement.text)
if ratio > confidence:
confidence = ratio
closest_match = statement
'''
closest_match, confidence = process.extractOne(
input_statement.text,
text_of_all_statements
)
'''
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
| # -*- coding: utf-8 -*-
from .base_match import BaseMatchAdapter
from fuzzywuzzy import fuzz
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter selects a response to an
input statement by selecting the closest known matching
statement based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text, statement.text)
if ratio > confidence:
confidence = ratio
closest_match = statement
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
| Remove commented out method call. | Remove commented out method call.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot,vkosuri/ChatterBot,gunthercox/ChatterBot,Reinaesaya/OUIRL-ChatBot,davizucon/ChatterBot | ---
+++
@@ -38,13 +38,6 @@
confidence = ratio
closest_match = statement
- '''
- closest_match, confidence = process.extractOne(
- input_statement.text,
- text_of_all_statements
- )
- '''
-
# Convert the confidence integer to a percent
confidence /= 100.0
|
a6441de03522f9352742cba5a8a656785de05455 | tests/mock_vws/test_query.py | tests/mock_vws/test_query.py | """
Tests for the mock of the query endpoint.
https://library.vuforia.com/articles/Solution/How-To-Perform-an-Image-Recognition-Query.
"""
import pytest
import requests
from tests.mock_vws.utils import Endpoint, assert_query_success
@pytest.mark.usefixtures('verify_mock_vuforia')
class TestQuery:
"""
Tests for the query endpoint.
"""
def test_no_results(
self,
query_endpoint: Endpoint,
) -> None:
"""
When there are no matching images in the database, an empty list of
results is returned.
"""
session = requests.Session()
response = session.send( # type: ignore
request=query_endpoint.prepared_request,
)
assert_query_success(response=response)
assert response.json()['results'] == []
| """
Tests for the mock of the query endpoint.
https://library.vuforia.com/articles/Solution/How-To-Perform-an-Image-Recognition-Query.
"""
import io
from urllib.parse import urljoin
import pytest
import requests
from requests_mock import POST
from urllib3.filepost import encode_multipart_formdata
from tests.mock_vws.utils import (
VuforiaDatabaseKeys,
assert_query_success,
authorization_header,
rfc_1123_date,
)
VWQ_HOST = 'https://cloudreco.vuforia.com'
@pytest.mark.usefixtures('verify_mock_vuforia')
class TestQuery:
"""
Tests for the query endpoint.
"""
def test_no_results(
self,
high_quality_image: io.BytesIO,
vuforia_database_keys: VuforiaDatabaseKeys,
) -> None:
"""
When there are no matching images in the database, an empty list of
results is returned.
"""
image_content = high_quality_image.read()
date = rfc_1123_date()
request_path = '/v1/query'
files = {'image': ('image.jpeg', image_content, 'image/jpeg')}
content, content_type_header = encode_multipart_formdata(files)
method = POST
access_key = vuforia_database_keys.client_access_key
secret_key = vuforia_database_keys.client_secret_key
authorization_string = authorization_header(
access_key=access_key,
secret_key=secret_key,
method=method,
content=content,
# Note that this is not the actual Content-Type header value sent.
content_type='multipart/form-data',
date=date,
request_path=request_path,
)
headers = {
'Authorization': authorization_string,
'Date': date,
'Content-Type': content_type_header,
}
response = requests.request(
method=method,
url=urljoin(base=VWQ_HOST, url=request_path),
headers=headers,
data=content,
)
assert_query_success(response=response)
assert response.json()['results'] == []
| Use raw request making in query test | Use raw request making in query test
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python | ---
+++
@@ -4,10 +4,23 @@
https://library.vuforia.com/articles/Solution/How-To-Perform-an-Image-Recognition-Query.
"""
+import io
+from urllib.parse import urljoin
+
import pytest
import requests
+from requests_mock import POST
+from urllib3.filepost import encode_multipart_formdata
-from tests.mock_vws.utils import Endpoint, assert_query_success
+from tests.mock_vws.utils import (
+ VuforiaDatabaseKeys,
+ assert_query_success,
+ authorization_header,
+ rfc_1123_date,
+)
+
+
+VWQ_HOST = 'https://cloudreco.vuforia.com'
@pytest.mark.usefixtures('verify_mock_vuforia')
@@ -18,15 +31,45 @@
def test_no_results(
self,
- query_endpoint: Endpoint,
+ high_quality_image: io.BytesIO,
+ vuforia_database_keys: VuforiaDatabaseKeys,
) -> None:
"""
When there are no matching images in the database, an empty list of
results is returned.
"""
- session = requests.Session()
- response = session.send( # type: ignore
- request=query_endpoint.prepared_request,
+ image_content = high_quality_image.read()
+ date = rfc_1123_date()
+ request_path = '/v1/query'
+ files = {'image': ('image.jpeg', image_content, 'image/jpeg')}
+ content, content_type_header = encode_multipart_formdata(files)
+ method = POST
+
+ access_key = vuforia_database_keys.client_access_key
+ secret_key = vuforia_database_keys.client_secret_key
+ authorization_string = authorization_header(
+ access_key=access_key,
+ secret_key=secret_key,
+ method=method,
+ content=content,
+ # Note that this is not the actual Content-Type header value sent.
+ content_type='multipart/form-data',
+ date=date,
+ request_path=request_path,
)
+
+ headers = {
+ 'Authorization': authorization_string,
+ 'Date': date,
+ 'Content-Type': content_type_header,
+ }
+
+ response = requests.request(
+ method=method,
+ url=urljoin(base=VWQ_HOST, url=request_path),
+ headers=headers,
+ data=content,
+ )
+
assert_query_success(response=response)
assert response.json()['results'] == [] |
2295ccdca2ae208bcfb44c09b2a07cf525baebfc | docker/settings.py | docker/settings.py | from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
| from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 100
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
| Increase rest client pool size to 100 | Increase rest client pool size to 100
| Python | apache-2.0 | uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics | ---
+++
@@ -23,5 +23,5 @@
}
}
-RESTCLIENTS_CANVAS_POOL_SIZE = 50
+RESTCLIENTS_CANVAS_POOL_SIZE = 100
ACADEMIC_CANVAS_ACCOUNT_ID = '84378' |
7798de3a4ce6428e15394c5e3d00f5db5745f7af | src/puzzle/steps/image/_base_image_step.py | src/puzzle/steps/image/_base_image_step.py | from typing import Any, NamedTuple, Optional
import numpy as np
from data.image import image
from puzzle.steps import step
class ImageChangeEvent(NamedTuple):
pass
class BaseImageStep(step.Step):
_source: image.Image
_result: Optional[image.Image]
def __init__(self,
source: image.Image,
dependencies: Optional[step.Dependencies] = None,
constraints: Optional[step.Constraints] = None) -> None:
super(BaseImageStep, self).__init__(
dependencies=dependencies,
constraints=constraints)
if constraints:
for constraint in constraints:
constraint.subscribe(self._on_constraints_changed)
self._source = source
self._result = None
def get_result(self) -> image.Image:
if self._result is None:
self._result = self._modify_result(self._source.fork())
return self._result
def get_debug_data(self) -> np.ndarray:
return self.get_result().get_debug_data()
def _modify_result(self, result: image.Image) -> image.Image:
raise NotImplementedError()
def _on_constraints_changed(self, change: Any) -> None:
del change
self._result = None
self._subject.on_next(ImageChangeEvent())
| from typing import Any, NamedTuple, Optional
import numpy as np
from data.image import image
from puzzle.steps import step
class ImageChangeEvent(NamedTuple):
pass
class BaseImageStep(step.Step):
_source: image.Image
_result: Optional[image.Image]
def __init__(self,
source: image.Image,
dependencies: Optional[step.Dependencies] = None,
constraints: Optional[step.Constraints] = None) -> None:
super(BaseImageStep, self).__init__(
dependencies=dependencies,
constraints=constraints)
if constraints:
for constraint in constraints:
constraint.subscribe(self._on_constraints_changed)
self._source = source
self._result = None
def get_result(self) -> image.Image:
if self._result is None:
self._result = self._modify_result(self._get_new_source())
return self._result
def get_debug_data(self) -> np.ndarray:
return self.get_result().get_debug_data()
def _get_new_source(self) -> image.Image:
return self._source.fork()
def _modify_result(self, result: image.Image) -> image.Image:
raise NotImplementedError()
def _on_constraints_changed(self, change: Any) -> None:
del change
self._result = None
self._subject.on_next(ImageChangeEvent())
| Allow descendents of BaseImageStep to override source Image. | Allow descendents of BaseImageStep to override source Image.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge | ---
+++
@@ -29,11 +29,14 @@
def get_result(self) -> image.Image:
if self._result is None:
- self._result = self._modify_result(self._source.fork())
+ self._result = self._modify_result(self._get_new_source())
return self._result
def get_debug_data(self) -> np.ndarray:
return self.get_result().get_debug_data()
+
+ def _get_new_source(self) -> image.Image:
+ return self._source.fork()
def _modify_result(self, result: image.Image) -> image.Image:
raise NotImplementedError() |
d3ebf779f3da800145e84913cb202a1e508c9d30 | abelfunctions/__init__.py | abelfunctions/__init__.py | """
abelfunctions is a Python library for computing with Abelian functions,
algebraic curves, and solving integrable Partial Differential Equations.
The code is available as a git repository at
https://github.com/cswiercz/abelfunctions
"""
# from puiseux import puiseux
# from integralbasis import integral_basis
# from singularities import singularities, homogenize, _transform, genus
# from differentials import differentials
# from monodromy import monodromy, show_paths, monodromy_graph
# from homology import homology, show_homology
# from riemannsurface import (
# RiemannSurface,
# RiemannSurfacePath,
# RiemannSurfacePoint,
# )
# from riemanntheta import RiemannTheta
| """
abelfunctions is a Python library for computing with Abelian functions,
algebraic curves, and solving integrable Partial Differential Equations.
The code is available as a git repository at
https://github.com/cswiercz/abelfunctions
"""
from riemann_surface import RiemannSurface
from riemanntheta import RiemannTheta
| Make 'from abelfunctions import *' work. | Make 'from abelfunctions import *' work.
| Python | mit | abelfunctions/abelfunctions,cswiercz/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions | ---
+++
@@ -7,15 +7,5 @@
https://github.com/cswiercz/abelfunctions
"""
-# from puiseux import puiseux
-# from integralbasis import integral_basis
-# from singularities import singularities, homogenize, _transform, genus
-# from differentials import differentials
-# from monodromy import monodromy, show_paths, monodromy_graph
-# from homology import homology, show_homology
-# from riemannsurface import (
-# RiemannSurface,
-# RiemannSurfacePath,
-# RiemannSurfacePoint,
-# )
-# from riemanntheta import RiemannTheta
+from riemann_surface import RiemannSurface
+from riemanntheta import RiemannTheta |
4e2237d53d3f78e1cc11aeba1a1599c296e0c280 | tests/integration/test_wordpress_import.py | tests/integration/test_wordpress_import.py | # -*- coding: utf-8 -*-
"""
Testing the wordpress import.
It will do create a new site with the import_wordpress command
and use that newly created site to make a build.
"""
import os
import os.path
import pytest
from nikola import __main__
from ..base import cd
from .test_empty_build import ( # NOQA
test_archive_exists, test_avoid_double_slash_in_rss, test_check_files)
def test_import_created_files(build, target_dir):
assert os.path.exists(target_dir)
assert os.path.exists(os.path.join(target_dir, 'conf.py'))
pages = os.path.join(target_dir, 'pages')
assert os.path.isdir(pages)
@pytest.fixture(scope="module")
def build(target_dir, import_file):
__main__.main(["import_wordpress",
"--no-downloads",
"--output-folder", target_dir,
import_file])
with cd(target_dir):
result = __main__.main(["build"])
assert not result
@pytest.fixture(scope="module")
def import_file():
"""Path to the Wordpress export file."""
test_directory = os.path.dirname(__file__)
return os.path.join(test_directory, '..', 'wordpress_export_example.xml')
| # -*- coding: utf-8 -*-
"""
Testing the wordpress import.
It will do create a new site with the import_wordpress command
and use that newly created site to make a build.
"""
import os.path
from glob import glob
import pytest
from nikola import __main__
from ..base import cd
from .test_empty_build import ( # NOQA
test_archive_exists, test_avoid_double_slash_in_rss, test_check_files)
def test_import_created_files(build, target_dir):
assert os.path.exists(target_dir)
assert os.path.exists(os.path.join(target_dir, 'conf.py'))
@pytest.mark.parametrize("dirname", ["pages", "posts"])
def test_filled_directories(build, target_dir, dirname):
folder = os.path.join(target_dir, dirname)
assert os.path.isdir(folder)
assert glob(os.path.join(folder, '*'))
@pytest.fixture(scope="module")
def build(target_dir, import_file):
__main__.main(["import_wordpress",
"--no-downloads",
"--output-folder", target_dir,
import_file])
with cd(target_dir):
result = __main__.main(["build"])
assert not result
@pytest.fixture(scope="module")
def import_file():
"""Path to the Wordpress export file."""
test_directory = os.path.dirname(__file__)
return os.path.join(test_directory, '..', 'wordpress_export_example.xml')
| Test that pages and posts are filled. | Test that pages and posts are filled.
| Python | mit | getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,okin/nikola,okin/nikola,okin/nikola,getnikola/nikola | ---
+++
@@ -6,8 +6,8 @@
and use that newly created site to make a build.
"""
-import os
import os.path
+from glob import glob
import pytest
@@ -22,8 +22,12 @@
assert os.path.exists(target_dir)
assert os.path.exists(os.path.join(target_dir, 'conf.py'))
- pages = os.path.join(target_dir, 'pages')
- assert os.path.isdir(pages)
+
+@pytest.mark.parametrize("dirname", ["pages", "posts"])
+def test_filled_directories(build, target_dir, dirname):
+ folder = os.path.join(target_dir, dirname)
+ assert os.path.isdir(folder)
+ assert glob(os.path.join(folder, '*'))
@pytest.fixture(scope="module") |
db1af67bab58b831dcf63f63bfefc0e28e4ced55 | congress_tempest_tests/config.py | congress_tempest_tests/config.py | # Copyright 2015 Intel Corp
# 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 oslo_config import cfg
from tempest import config # noqa
congressha_group = cfg.OptGroup(name="congressha", title="Congress HA Options")
CongressHAGroup = [
cfg.StrOpt("replica_type",
default="policyha",
help="service type used to create a replica congress server."),
cfg.IntOpt("replica_port",
default=4001,
help="The listening port for a replica congress server. "),
]
| # Copyright 2015 Intel Corp
# 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 oslo_config import cfg
from tempest import config # noqa
service_available_group = cfg.OptGroup(name="service_available",
title="Available OpenStack Services")
ServiceAvailableGroup = [
cfg.BoolOpt('congress',
default=True,
help="Whether or not Congress is expected to be available"),
]
congressha_group = cfg.OptGroup(name="congressha", title="Congress HA Options")
CongressHAGroup = [
cfg.StrOpt("replica_type",
default="policyha",
help="service type used to create a replica congress server."),
cfg.IntOpt("replica_port",
default=4001,
help="The listening port for a replica congress server. "),
]
| Add congress to service_available group | Add congress to service_available group
Add congress to service_available group. used in tempest plugin
to check if service is available or not
Change-Id: Ia3edbb545819d76a6563ee50c2dcdad6013f90e9
| Python | apache-2.0 | ramineni/my_congress,ramineni/my_congress,ramineni/my_congress,ramineni/my_congress,openstack/congress,openstack/congress | ---
+++
@@ -18,6 +18,13 @@
from tempest import config # noqa
+service_available_group = cfg.OptGroup(name="service_available",
+ title="Available OpenStack Services")
+ServiceAvailableGroup = [
+ cfg.BoolOpt('congress',
+ default=True,
+ help="Whether or not Congress is expected to be available"),
+]
congressha_group = cfg.OptGroup(name="congressha", title="Congress HA Options")
CongressHAGroup = [ |
609864faf36b9a82db9fd63d28b5a0da7a22c4f5 | eforge/__init__.py | eforge/__init__.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 0, 'beta 1')
def get_version():
return '%d.%d.%d %s' % VERSION | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
from eforge.menu import ItemOrder
EFORGE_PLUGIN = {
'name': 'EForge Core',
'credit': 'Copyright © 2010 Element43 and contributors',
'provides': {
'mnu': [('project-page', ItemOrder(000, 'Summary'))],
},
}
VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION | Change master version information to 0.5.99 (git master) | Change master version information to 0.5.99 (git master)
Todo: We should probably add the smarts to EForge to grab the git
revision for master, at least if Dulwich is installed :-)
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge | ---
+++
@@ -25,7 +25,7 @@
},
}
-VERSION = (0, 5, 0, 'beta 1')
+VERSION = (0, 5, 99, '(git master)')
def get_version():
return '%d.%d.%d %s' % VERSION |
b6645c81c4e45a03297ebb5e4fb65fcef952a1f9 | ci/get_latest_conda_build_path.py | ci/get_latest_conda_build_path.py | import sys
import os
import yaml
import jinja2
import glob
from conda_build.config import config
from conda_build.metadata import MetaData
from distutils.version import LooseVersion
recipe_metadata = MetaData(os.path.join(sys.argv[1]))
binary_package_glob = os.path.join(config.bldpkgs_dir, '{0}*.tar.bz2'.format(recipe_metadata.name()))
binary_package = sorted(glob.glob(binary_package_glob), key=LooseVersion, reverse = True)[0]
print(binary_package)
| import sys
import os
import yaml
import jinja2
import glob
from conda_build.config import Config
from conda_build.metadata import MetaData
from distutils.version import LooseVersion
config = Config()
recipe_metadata = MetaData(os.path.join(sys.argv[1]))
binary_package_glob = os.path.join(config.bldpkgs_dir, '{0}*.tar.bz2'.format(recipe_metadata.name()))
binary_package = sorted(glob.glob(binary_package_glob), key=LooseVersion, reverse = True)[0]
print(binary_package)
| Update get build path script for conda-build 2.0 | Update get build path script for conda-build 2.0
In conda-build 2.0 the config API changed.
| Python | bsd-3-clause | amacd31/hydromath,amacd31/hydromath | ---
+++
@@ -3,10 +3,11 @@
import yaml
import jinja2
import glob
-from conda_build.config import config
+from conda_build.config import Config
from conda_build.metadata import MetaData
from distutils.version import LooseVersion
+config = Config()
recipe_metadata = MetaData(os.path.join(sys.argv[1]))
binary_package_glob = os.path.join(config.bldpkgs_dir, '{0}*.tar.bz2'.format(recipe_metadata.name()))
binary_package = sorted(glob.glob(binary_package_glob), key=LooseVersion, reverse = True)[0] |
f4550e5a341baab9b1193766595a86d57e253806 | rnacentral/apiv1/urls.py | rnacentral/apiv1/urls.py | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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 django.views.generic import TemplateView
from django.conf.urls import patterns, url, include
from rest_framework import routers
from apiv1 import views
router = routers.DefaultRouter()
router.register(r'rna', views.RnaViewSet)
router.register(r'accession', views.AccessionViewSet)
urlpatterns = patterns('',
url(r'^v1/', include(router.urls)),
url(r'^v1/', include('rest_framework.urls', namespace='rest_framework_v1')),
url(r'^current/', include(router.urls)),
url(r'^current/', include('rest_framework.urls', namespace='rest_framework_v1')),
)
| """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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 django.views.generic import TemplateView
from django.conf.urls import patterns, url, include
from rest_framework import routers
from apiv1 import views
router = routers.DefaultRouter()
router.register(r'rna', views.RnaViewSet)
router.register(r'accession', views.AccessionViewSet)
urlpatterns = patterns('',
url(r'^current/', include(router.urls)),
url(r'^current/', include('rest_framework.urls', namespace='current_api', app_name='current_api')),
url(r'^v1/', include(router.urls)),
url(r'^v1/', include('rest_framework.urls', namespace='api_v1', app_name='api_v1')),
)
| Add url namespaces and app_names to apiv1 | Add url namespaces and app_names to apiv1
| Python | apache-2.0 | RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode | ---
+++
@@ -21,8 +21,8 @@
router.register(r'accession', views.AccessionViewSet)
urlpatterns = patterns('',
+ url(r'^current/', include(router.urls)),
+ url(r'^current/', include('rest_framework.urls', namespace='current_api', app_name='current_api')),
url(r'^v1/', include(router.urls)),
- url(r'^v1/', include('rest_framework.urls', namespace='rest_framework_v1')),
- url(r'^current/', include(router.urls)),
- url(r'^current/', include('rest_framework.urls', namespace='rest_framework_v1')),
+ url(r'^v1/', include('rest_framework.urls', namespace='api_v1', app_name='api_v1')),
) |
894fea9aecf62cb5a04d1fd02b48d3a263e16a81 | corehq/motech/const.py | corehq/motech/const.py |
PASSWORD_PLACEHOLDER = '*' * 16
# If any remote service does not respond within 10 minutes, time out
REQUEST_TIMEOUT = 600
ALGO_AES = 'aes'
DATA_TYPE_UNKNOWN = None
COMMCARE_DATA_TYPE_TEXT = 'cc_text'
COMMCARE_DATA_TYPE_INTEGER = 'cc_integer'
COMMCARE_DATA_TYPE_DECIMAL = 'cc_decimal'
COMMCARE_DATA_TYPE_DATE = 'cc_date'
COMMCARE_DATA_TYPE_DATETIME = 'cc_datetime'
COMMCARE_DATA_TYPE_TIME = 'cc_time'
COMMCARE_DATA_TYPES = (
COMMCARE_DATA_TYPE_TEXT,
COMMCARE_DATA_TYPE_INTEGER,
COMMCARE_DATA_TYPE_DECIMAL,
COMMCARE_DATA_TYPE_DATE,
COMMCARE_DATA_TYPE_DATETIME,
COMMCARE_DATA_TYPE_TIME,
)
DIRECTION_IMPORT = 'in'
DIRECTION_EXPORT = 'out'
DIRECTION_BOTH = None
DIRECTIONS = (
DIRECTION_IMPORT,
DIRECTION_EXPORT,
DIRECTION_BOTH,
)
|
PASSWORD_PLACEHOLDER = '*' * 16
# If any remote service does not respond within 5 minutes, time out
REQUEST_TIMEOUT = 5 * 60
ALGO_AES = 'aes'
DATA_TYPE_UNKNOWN = None
COMMCARE_DATA_TYPE_TEXT = 'cc_text'
COMMCARE_DATA_TYPE_INTEGER = 'cc_integer'
COMMCARE_DATA_TYPE_DECIMAL = 'cc_decimal'
COMMCARE_DATA_TYPE_DATE = 'cc_date'
COMMCARE_DATA_TYPE_DATETIME = 'cc_datetime'
COMMCARE_DATA_TYPE_TIME = 'cc_time'
COMMCARE_DATA_TYPES = (
COMMCARE_DATA_TYPE_TEXT,
COMMCARE_DATA_TYPE_INTEGER,
COMMCARE_DATA_TYPE_DECIMAL,
COMMCARE_DATA_TYPE_DATE,
COMMCARE_DATA_TYPE_DATETIME,
COMMCARE_DATA_TYPE_TIME,
)
DIRECTION_IMPORT = 'in'
DIRECTION_EXPORT = 'out'
DIRECTION_BOTH = None
DIRECTIONS = (
DIRECTION_IMPORT,
DIRECTION_EXPORT,
DIRECTION_BOTH,
)
| Reduce normal request timeout to 5 minutes | Reduce normal request timeout to 5 minutes
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -2,8 +2,8 @@
PASSWORD_PLACEHOLDER = '*' * 16
-# If any remote service does not respond within 10 minutes, time out
-REQUEST_TIMEOUT = 600
+# If any remote service does not respond within 5 minutes, time out
+REQUEST_TIMEOUT = 5 * 60
ALGO_AES = 'aes'
|
2f5e8d51db04520600738064a0a97742a5f59dbb | nengo_spinnaker/utils/__init__.py | nengo_spinnaker/utils/__init__.py | import nengo
from . import fixpoint as fp
def totuple(a):
"""Convert any object (e.g., numpy array) to a Tuple.
http://stackoverflow.com/questions/10016352/convert-numpy-array-to-tuple
"""
try:
return totuple(totuple(i) for i in a)
except TypeError:
return a
def get_connection_width(connection):
"""Return the width of a Connection."""
if isinstance(connection, int):
return connection
elif isinstance(connection.post, nengo.Ensemble):
return connection.post.dimensions
elif isinstance(connection.post, nengo.Node):
return connection.post.size_in
| import nengo
from . import fixpoint as fp
def totuple(a):
"""Convert any object (e.g., numpy array) to a Tuple.
http://stackoverflow.com/questions/10016352/convert-numpy-array-to-tuple
"""
try:
return tuple(totuple(i) for i in a)
except TypeError:
return a
def get_connection_width(connection):
"""Return the width of a Connection."""
if isinstance(connection, int):
return connection
elif isinstance(connection.post, nengo.Ensemble):
return connection.post.dimensions
elif isinstance(connection.post, nengo.Node):
return connection.post.size_in
| Fix recursive bug in totuple. Not sure how it got there. | Fix recursive bug in totuple. Not sure how it got there.
(cherry picked from commit ae1f7beb5188eaf09fc3f7efc1061a15a12aecf2)
| Python | mit | ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014 | ---
+++
@@ -9,7 +9,7 @@
http://stackoverflow.com/questions/10016352/convert-numpy-array-to-tuple
"""
try:
- return totuple(totuple(i) for i in a)
+ return tuple(totuple(i) for i in a)
except TypeError:
return a
|
099b8d9b6d546d035e63b6db8714c44364537efd | yolapy/services.py | yolapy/services.py | from demands import HTTPServiceClient
from yolapy.resources import campaign, partner, site, subscription, user
class Yola(
HTTPServiceClient, campaign.CampaignResourceMixin,
partner.PartnerResourceMixin, site.SiteResourceMixin,
subscription.SubscriptionResourceMixin, user.UserResourceMixin):
"""Client for Yola's API.
```
yola = Yola(
url='https://wl.yola.net/',
auth=('username', 'password'))
yola.get_user('user_id')
```
When appropriate, successful responses will return parsed json objects.
Failures will raise instances of `demands.HTTPServiceError`.
See [TODO] for available methods with documentation.
"""
def __init__(self, **kwargs):
"""Initialize with url, auth, and optional headers.
```
Yola(
url='https://wl.yola.net/',
auth=('username', 'password'),
headers={'Header-Name': 'value'})
```
"""
kwargs['send_as_json'] = True
super(Yola, self).__init__(**kwargs)
| from demands import HTTPServiceClient
from yolapy.configuration import get_config
from yolapy.resources import campaign, partner, site, subscription, user
class Yola(
HTTPServiceClient, campaign.CampaignResourceMixin,
partner.PartnerResourceMixin, site.SiteResourceMixin,
subscription.SubscriptionResourceMixin, user.UserResourceMixin):
"""Client for Yola's API.
If using yolapy.configuration:
```
configure(yola={
'url': 'https://wl.yola.net/',
'auth': ('username', 'password')),
})
yola = Yola()
yola.get_user('user_id')
```
Or configured manually:
```
yola = Yola(
url='https://wl.yola.net/',
auth=('username', 'password'))
yola.get_user('user_id')
```
When appropriate, successful responses will return parsed json objects.
Failures will raise instances of `demands.HTTPServiceError`.
See [TODO] for available methods with documentation.
"""
def __init__(self, **kwargs):
"""Initialize with optional headers.
Auth and url are expected to be present in the 'yola' configuration.
Passed arguments will override configuration.
```
Yola(headers={'Header-Name': 'value'})
```
"""
config = {'send_as_json': True}
config.update(get_config('yola', {}))
config.update(kwargs)
assert(config['url'])
assert(config['auth'])
super(Yola, self).__init__(**config)
| Update client init, use configuration to set default `auth` and `url` | Update client init, use configuration to set default `auth` and `url`
| Python | mit | yola/yolapy | ---
+++
@@ -1,5 +1,5 @@
from demands import HTTPServiceClient
-
+from yolapy.configuration import get_config
from yolapy.resources import campaign, partner, site, subscription, user
@@ -9,11 +9,21 @@
subscription.SubscriptionResourceMixin, user.UserResourceMixin):
"""Client for Yola's API.
+ If using yolapy.configuration:
+ ```
+ configure(yola={
+ 'url': 'https://wl.yola.net/',
+ 'auth': ('username', 'password')),
+ })
+ yola = Yola()
+ yola.get_user('user_id')
+ ```
+
+ Or configured manually:
```
yola = Yola(
url='https://wl.yola.net/',
auth=('username', 'password'))
-
yola.get_user('user_id')
```
@@ -25,14 +35,19 @@
"""
def __init__(self, **kwargs):
- """Initialize with url, auth, and optional headers.
+ """Initialize with optional headers.
+
+ Auth and url are expected to be present in the 'yola' configuration.
+
+ Passed arguments will override configuration.
```
- Yola(
- url='https://wl.yola.net/',
- auth=('username', 'password'),
- headers={'Header-Name': 'value'})
+ Yola(headers={'Header-Name': 'value'})
```
"""
- kwargs['send_as_json'] = True
- super(Yola, self).__init__(**kwargs)
+ config = {'send_as_json': True}
+ config.update(get_config('yola', {}))
+ config.update(kwargs)
+ assert(config['url'])
+ assert(config['auth'])
+ super(Yola, self).__init__(**config) |
1ff766471df0c0171722c97f21ea1033f21e44f3 | src/valid_parentheses.py | src/valid_parentheses.py |
def isValid( s):
if not s:
return False
stack = []
map = {'(':')', '[':']', '{':'}'}
for c in s:
if c in map.keys():
stack.append(c)
else:
if len(stack) > 0:
top = stack.pop()
if map[top] != c:
return False
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == '__main__':
test_list = ['','(){}[]','({})','(',')',')(','()','([)]','([{])}']
result_list = [0, 1, 1, 0, 0, 0, 1, 0, 0]
success = True
for i, s in enumerate(test_list):
result = isValid(s)
if result != result_list[i]:
success = False
print s
print 'Expected value %d' % result_list[i]
print 'Actual value %d' % result
if success:
print 'All the tests passed'
else:
print 'Please fix the failed test'
| """
Source : https://oj.leetcode.com/problems/valid-parentheses/
Author : Changxi Wu
Date : 2015-01-20
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid
but "(]" and "([)]" are not.
"""
def isValid( s):
if not s:
return False
stack = []
map = {'(':')', '[':']', '{':'}'}
for c in s:
if c in map.keys():
stack.append(c)
else:
if len(stack) > 0:
top = stack.pop()
if map[top] != c:
return False
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == '__main__':
test_list = ['','(){}[]','({})','(',')',')(','()','([)]','([{])}']
result_list = [0, 1, 1, 0, 0, 0, 1, 0, 0]
success = True
for i, s in enumerate(test_list):
result = isValid(s)
if result != result_list[i]:
success = False
print s
print 'Expected value %d' % result_list[i]
print 'Actual value %d' % result
if success:
print 'All the tests passed'
else:
print 'Please fix the failed test'
| Add question desciption for valid parentheses | Add question desciption for valid parentheses
| Python | mit | chancyWu/leetcode | ---
+++
@@ -1,4 +1,15 @@
+"""
+Source : https://oj.leetcode.com/problems/valid-parentheses/
+Author : Changxi Wu
+Date : 2015-01-20
+Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
+determine if the input string is valid.
+
+The brackets must close in the correct order, "()" and "()[]{}" are all valid
+but "(]" and "([)]" are not.
+
+"""
def isValid( s):
if not s: |
eacc79f1e1a7a0748d9202eb2c9a90291abe3fd7 | dwitter/templatetags/insert_magic_links.py | dwitter/templatetags/insert_magic_links.py | import re
from django import template
register = template.Library()
def to_link(m):
text = m.group('text')
dweet_id = m.group('dweet_id')
username = m.group('username')
if username is None:
path = '/d/' + dweet_id # hardcode for speed!
# path = reverse('dweet_show', kwargs={'dweet_id': dweet_id})
else:
path = '/u/' + username # hardcode for speed!
# path = reverse('user_feed', kwargs={'url_username': username})
return '<a href="%s">%s</a>' % (path, text)
@register.filter(is_safe=True)
def insert_magic_links(text):
return re.sub(
r'(?:^|(?<=\s))' # start of string or whitespace
r'/?' # optional /
r'(?P<text>' # capture original pattern
r'd/(?P<dweet_id>\d+)' # dweet reference
r'|' # or
r'u/(?P<username>[\w.@+-]+))' # user reference
r'(?=$|\s)', # end of string or whitespace
to_link,
text
)
| import re
from django import template
register = template.Library()
def to_link(m):
text = m.group('text')
dweet_id = m.group('dweet_id')
username = m.group('username')
if username is None:
url = 'd/' + dweet_id
else:
url = 'u/' + username
result = '<a href="/{0}">{0}</a>'.format(url)
return text.replace(url, result)
@register.filter(is_safe=True)
def insert_magic_links(text):
return re.sub(
r'(?:^|(?<=\s))' # start of string or whitespace
r'/?' # optional /
r'(?P<text>' # capture original pattern
r'[^a-zA-Z\d]?d/(?P<dweet_id>\d+)[^a-zA-Z]?' # dweet reference
r'|' # or
r'[^a-zA-Z\d]?u/(?P<username>[\w.@+-]+)[^a-zA-Z\d]?)' # user reference
r'(?=$|\s)', # end of string or whitespace
to_link,
text
)
| Update magic links for dweet and user links | Update magic links for dweet and user links
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | ---
+++
@@ -10,25 +10,24 @@
username = m.group('username')
if username is None:
- path = '/d/' + dweet_id # hardcode for speed!
- # path = reverse('dweet_show', kwargs={'dweet_id': dweet_id})
+ url = 'd/' + dweet_id
else:
- path = '/u/' + username # hardcode for speed!
- # path = reverse('user_feed', kwargs={'url_username': username})
+ url = 'u/' + username
- return '<a href="%s">%s</a>' % (path, text)
+ result = '<a href="/{0}">{0}</a>'.format(url)
+ return text.replace(url, result)
@register.filter(is_safe=True)
def insert_magic_links(text):
return re.sub(
- r'(?:^|(?<=\s))' # start of string or whitespace
- r'/?' # optional /
- r'(?P<text>' # capture original pattern
- r'd/(?P<dweet_id>\d+)' # dweet reference
- r'|' # or
- r'u/(?P<username>[\w.@+-]+))' # user reference
- r'(?=$|\s)', # end of string or whitespace
+ r'(?:^|(?<=\s))' # start of string or whitespace
+ r'/?' # optional /
+ r'(?P<text>' # capture original pattern
+ r'[^a-zA-Z\d]?d/(?P<dweet_id>\d+)[^a-zA-Z]?' # dweet reference
+ r'|' # or
+ r'[^a-zA-Z\d]?u/(?P<username>[\w.@+-]+)[^a-zA-Z\d]?)' # user reference
+ r'(?=$|\s)', # end of string or whitespace
to_link,
text
) |
48d02d2c9cea083946c68e494309d7597ec2d878 | pyfire/tests/__init__.py | pyfire/tests/__init__.py | # -*- coding: utf-8 -*-
"""
pyfire.tests
~~~~~~~~~~~~
All unittests live here
:copyright: (c) 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
""" | # -*- coding: utf-8 -*-
"""
pyfire.tests
~~~~~~~~~~~~
All unittests live here
:copyright: (c) 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import unittest
class PyfireTestCase(unittest.TestCase):
"""All our unittests are based on this class"""
pass | Create unit test base class | Create unit test base class
| Python | bsd-3-clause | IgnitedAndExploded/pyfire,IgnitedAndExploded/pyfire | ---
+++
@@ -8,3 +8,9 @@
:copyright: (c) 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
+
+import unittest
+
+class PyfireTestCase(unittest.TestCase):
+ """All our unittests are based on this class"""
+ pass |
7e2b60a7f7b32c235f931f9e7263ccefc84c79e2 | gittip/orm/__init__.py | gittip/orm/__init__.py | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback() | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback() | Add convenience methods for creating/deleting all tables, for bootstrapping/testing use | Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com>
| Python | mit | studio666/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,MikeFair/www.gittip.com,MikeFair/www.gittip.com,studio666/gratipay.com,mccolgst/www.gittip.com,bountysource/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,bountysource/www.gittip.com,MikeFair/www.gittip.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,bountysource/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,bountysource/www.gittip.com | ---
+++
@@ -41,6 +41,12 @@
base.query = self.session.query_property()
return base
+ def drop_all(self):
+ self.Model.metadata.drop_all(bind=self.engine)
+
+ def create_all(self):
+ self.Model.metadata.create_all(bind=self.engine)
+
db = SQLAlchemy()
all = [db] |
d7a8162ab33224742258838b90e11f8845198a95 | src/sentry/quotas/base.py | src/sentry/quotas/base.py | """
sentry.quotas.base
~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.conf import settings
class Quota(object):
"""
Quotas handle tracking a project's event usage (at a per minute tick) and
respond whether or not a project has been configured to throttle incoming
events if they go beyond the specified quota.
"""
def __init__(self, **options):
pass
def is_rate_limited(self, project):
return False
def translate_quota(self, quota, parent_quota):
if quota.endswith('%'):
pct = int(quota[:-1])
quota = parent_quota * pct / 100
return int(quota)
def get_project_quota(self, project):
from sentry.models import ProjectOption
project_quota = ProjectOption.objects.get_value(project, 'per_minute', '')
if project_quota is None:
project_quota = settings.SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE
return self.translate_quota(
project_quota,
self.get_team_quota(project.team),
)
def get_team_quota(self, team):
return self.translate_quota(
settings.SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE,
self.get_system_quota()
)
def get_system_quota(self):
return settings.SENTRY_SYSTEM_MAX_EVENTS_PER_MINUTE
| """
sentry.quotas.base
~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.conf import settings
class Quota(object):
"""
Quotas handle tracking a project's event usage (at a per minute tick) and
respond whether or not a project has been configured to throttle incoming
events if they go beyond the specified quota.
"""
def __init__(self, **options):
pass
def is_rate_limited(self, project):
return False
def translate_quota(self, quota, parent_quota):
if quota.endswith('%'):
pct = int(quota[:-1])
quota = parent_quota * pct / 100
return int(quota or 0)
def get_project_quota(self, project):
from sentry.models import ProjectOption
project_quota = ProjectOption.objects.get_value(project, 'per_minute', '')
if project_quota is None:
project_quota = settings.SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE
return self.translate_quota(
project_quota,
self.get_team_quota(project.team),
)
def get_team_quota(self, team):
return self.translate_quota(
settings.SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE,
self.get_system_quota()
)
def get_system_quota(self):
return settings.SENTRY_SYSTEM_MAX_EVENTS_PER_MINUTE
| Handle empty quota in translate_quota | Handle empty quota in translate_quota
| Python | bsd-3-clause | mvaled/sentry,mvaled/sentry,ifduyue/sentry,zenefits/sentry,kevinlondon/sentry,1tush/sentry,Natim/sentry,argonemyth/sentry,BayanGroup/sentry,jean/sentry,fuziontech/sentry,BayanGroup/sentry,drcapulet/sentry,felixbuenemann/sentry,ifduyue/sentry,kevinastone/sentry,llonchj/sentry,mitsuhiko/sentry,looker/sentry,Kryz/sentry,felixbuenemann/sentry,Natim/sentry,zenefits/sentry,ewdurbin/sentry,daevaorn/sentry,gg7/sentry,JTCunning/sentry,BuildingLink/sentry,gencer/sentry,wujuguang/sentry,Kryz/sentry,hongliang5623/sentry,nicholasserra/sentry,beeftornado/sentry,BuildingLink/sentry,jokey2k/sentry,boneyao/sentry,looker/sentry,felixbuenemann/sentry,korealerts1/sentry,songyi199111/sentry,camilonova/sentry,1tush/sentry,gencer/sentry,ifduyue/sentry,wong2/sentry,imankulov/sentry,camilonova/sentry,wong2/sentry,boneyao/sentry,hongliang5623/sentry,jean/sentry,SilentCircle/sentry,mvaled/sentry,fuziontech/sentry,ewdurbin/sentry,JamesMura/sentry,zenefits/sentry,songyi199111/sentry,ifduyue/sentry,TedaLIEz/sentry,alexm92/sentry,fotinakis/sentry,kevinlondon/sentry,llonchj/sentry,fuziontech/sentry,JackDanger/sentry,pauloschilling/sentry,korealerts1/sentry,alexm92/sentry,looker/sentry,rdio/sentry,nicholasserra/sentry,Kryz/sentry,gg7/sentry,beeftornado/sentry,korealerts1/sentry,pauloschilling/sentry,jean/sentry,zenefits/sentry,TedaLIEz/sentry,kevinlondon/sentry,JTCunning/sentry,daevaorn/sentry,nicholasserra/sentry,ngonzalvez/sentry,gencer/sentry,BuildingLink/sentry,ngonzalvez/sentry,jokey2k/sentry,argonemyth/sentry,wong2/sentry,ngonzalvez/sentry,gencer/sentry,JamesMura/sentry,mvaled/sentry,jean/sentry,daevaorn/sentry,imankulov/sentry,JamesMura/sentry,gg7/sentry,ifduyue/sentry,drcapulet/sentry,wujuguang/sentry,BayanGroup/sentry,looker/sentry,JTCunning/sentry,boneyao/sentry,BuildingLink/sentry,llonchj/sentry,SilentCircle/sentry,rdio/sentry,SilentCircle/sentry,looker/sentry,beeftornado/sentry,drcapulet/sentry,1tush/sentry,jean/sentry,fotinakis/sentry,rdio/sentry,Natim/sentry,kevinastone/sentry,BuildingLink/sentry,vperron/sentry,kevinastone/sentry,TedaLIEz/sentry,camilonova/sentry,gencer/sentry,mvaled/sentry,imankulov/sentry,JackDanger/sentry,wujuguang/sentry,pauloschilling/sentry,JamesMura/sentry,hongliang5623/sentry,mvaled/sentry,fotinakis/sentry,vperron/sentry,songyi199111/sentry,SilentCircle/sentry,zenefits/sentry,argonemyth/sentry,fotinakis/sentry,JamesMura/sentry,vperron/sentry,mitsuhiko/sentry,alexm92/sentry,rdio/sentry,jokey2k/sentry,JackDanger/sentry,ewdurbin/sentry,daevaorn/sentry | ---
+++
@@ -26,7 +26,7 @@
if quota.endswith('%'):
pct = int(quota[:-1])
quota = parent_quota * pct / 100
- return int(quota)
+ return int(quota or 0)
def get_project_quota(self, project):
from sentry.models import ProjectOption |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.