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 |
|---|---|---|---|---|---|---|---|---|---|---|
2029256cda7e3bc752d30361357932053cb98744 | shell.py | shell.py | from person import Person
def go(db):
global status
while status == 1:
inputText = input("command>")
for i in commands:
if inputText == i:
commands[i](db)
def helpMe(db):
print("help:")
for i in commandsHelp:
print(i, ":", commandsHelp[i])
def add(db):
print("add")
firstName = input("firstName:")
secondName = input("secondName:")
birthdayDate = input("birthdayDate:")
namedayDate = input("namedayDate:")
mail = input("mail:")
telNumber = input("telNumber:")
facebook = input("facebook:")
group = input("group:")
newPerson = Person(firstName, secondName, birthdayDate,namedayDate, mail, telNumber, facebook, group)
db.add(newPerson)
def showDb(db):
for index in db.db:
print(index)
def quit(db):
global status
status = 0
status = 1
commands = {"h": helpMe, "a": add, "q": quit, "l": showDb}
commandsHelp = {"h": "help for command help", "a": "help for command add", "q": "help for command quit"}
| from person import Person
def go(db):
global status
while status == 1:
inputText = input("command> ")
for i in commands:
if inputText == i:
commands[i](db)
def helpMe(db):
print("help:")
for i in commandsHelp:
print("\t", i, ":", commandsHelp[i])
def add(db):
print("add")
firstName = input("\tfirstName: ")
secondName = input("\tsecondName: ")
birthdayDate = input("\tbirthdayDate: ")
namedayDate = input("\tnamedayDate: ")
mail = input("\tmail: ")
telNumber = input("\ttelNumber: ")
facebook = input("\tfacebook: ")
group = input("\tgroup: ")
newPerson = Person(firstName, secondName, birthdayDate,namedayDate, mail, telNumber, facebook, group)
db.add(newPerson)
def showDb(db):
for index in db.db:
print(index)
def quit(db):
global status
status = 0
status = 1
commands = {"h": helpMe, "a": add, "q": quit, "l": showDb}
commandsHelp = {"h": "help for command help", "a": "help for command add", "q": "help for command quit"}
| Add whitespaces to print it better. | Add whitespaces to print it better.
Signed-off-by: Matej Dujava <03ce64f61b3ea1fda633fb2a103b989e3272d16b@gmail.com>
| Python | mit | matejd11/birthdayNotify | ---
+++
@@ -4,7 +4,7 @@
def go(db):
global status
while status == 1:
- inputText = input("command>")
+ inputText = input("command> ")
for i in commands:
if inputText == i:
commands[i](db)
@@ -12,19 +12,19 @@
def helpMe(db):
print("help:")
for i in commandsHelp:
- print(i, ":", commandsHelp[i])
+ print("\t", i, ":", commandsHelp[i])
def add(db):
print("add")
- firstName = input("firstName:")
- secondName = input("secondName:")
- birthdayDate = input("birthdayDate:")
- namedayDate = input("namedayDate:")
- mail = input("mail:")
- telNumber = input("telNumber:")
- facebook = input("facebook:")
- group = input("group:")
+ firstName = input("\tfirstName: ")
+ secondName = input("\tsecondName: ")
+ birthdayDate = input("\tbirthdayDate: ")
+ namedayDate = input("\tnamedayDate: ")
+ mail = input("\tmail: ")
+ telNumber = input("\ttelNumber: ")
+ facebook = input("\tfacebook: ")
+ group = input("\tgroup: ")
newPerson = Person(firstName, secondName, birthdayDate,namedayDate, mail, telNumber, facebook, group)
|
a612e39f2395aa04bb3fd063188c4a1038324b04 | stock.py | stock.py | class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price = None
def update(self, timestamp, price):
self.price = price
| class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price = None
def update(self, timestamp, price):
if price < 0:
raise ValueError("price should not be negative")
self.price = price
| Update update method for negative price exception. | Update update method for negative price exception.
| Python | mit | bsmukasa/stock_alerter | ---
+++
@@ -4,4 +4,6 @@
self.price = None
def update(self, timestamp, price):
+ if price < 0:
+ raise ValueError("price should not be negative")
self.price = price |
0b7c0c727b3b56cc20b90da90732fae28aaaf479 | iis/jobs/__init__.py | iis/jobs/__init__.py | from flask import Blueprint
jobs = Blueprint('jobs', __name__, template_folder='./templates')
from . import views, models # noqa: E402, F401
| from flask import Blueprint
jobs = Blueprint('jobs', __name__,
template_folder='./templates') # type: Blueprint
from . import views, models # noqa: E402, F401
| Fix mypy complaint about unknown type | Fix mypy complaint about unknown type
| Python | agpl-3.0 | interactomix/iis,interactomix/iis | ---
+++
@@ -1,6 +1,7 @@
from flask import Blueprint
-jobs = Blueprint('jobs', __name__, template_folder='./templates')
+jobs = Blueprint('jobs', __name__,
+ template_folder='./templates') # type: Blueprint
from . import views, models # noqa: E402, F401 |
bfdb2c41c06375d1fe8ff196486ffd71873e0264 | wush/utils.py | wush/utils.py | import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
super(CustomQueue, self).__init__(self, *args, **kwargs)
| import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
super(CustomQueue, self).__init__(*args, **kwargs)
| Fix a recursion error caused by wrong signature. | Fix a recursion error caused by wrong signature.
| Python | mit | theju/wush | ---
+++
@@ -18,4 +18,4 @@
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
- super(CustomQueue, self).__init__(self, *args, **kwargs)
+ super(CustomQueue, self).__init__(*args, **kwargs) |
731935873ee4c342bfaa5825cdc9e39ce79d71a5 | invocations/_version.py | invocations/_version.py | __version_info__ = (0, 9, 2)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (0, 10, 0)
__version__ = '.'.join(map(str, __version_info__))
| Cut 0.10 for new feature in docs module | Cut 0.10 for new feature in docs module
| Python | bsd-2-clause | pyinvoke/invocations,mrjmad/invocations,singingwolfboy/invocations | ---
+++
@@ -1,2 +1,2 @@
-__version_info__ = (0, 9, 2)
+__version_info__ = (0, 10, 0)
__version__ = '.'.join(map(str, __version_info__)) |
a8ccc99aa0923be9a102bb6d42590d3214d4d229 | tests.py | tests.py | import json
import unittest
from pyunio import pyunio
pyunio.use('httpbin')
params = {
'body': {
'name': 'James Bond'
}
}
def test_get():
response = json.loads(pyunio.get('get', params).text)
assert(response['args']['name'] == 'James Bond')
def test_post():
response = json.loads(pyunio.post('post', params).text)
assert(response['args']['name'] == 'James Bond')
def test_put():
response = json.loads(pyunio.put('put', params).text)
assert(response['args']['name'] == 'James Bond')
def test_delete():
response = json.loads(pyunio.delete('delete', params).text)
assert(response['args']['name'] == 'James Bond')
| import json
import unittest
from pyunio import pyunio
pyunio.use('httpbin')
params = {
'body': {
'name': 'James Bond'
}
}
class pyuniotTest(unittest.TestCase):
def test_get(self):
response = json.loads(pyunio.get('get', params).text)
self.assertEqual(response['args']['name'], 'James Bond')
def test_post(self):
response = json.loads(pyunio.post('post', params).text)
self.assertEqual(response['args']['name'], 'James Bond')
def test_put(self):
response = json.loads(pyunio.put('put', params).text)
self.assertEqual(response['args']['name'], 'James Bond')
def test_delete(self):
response = json.loads(pyunio.delete('delete', params).text)
self.assertEqual(response['args']['name'], 'James Bond')
if __name__ == '__main__':
unittest.main()
| Add pyuniotest class for unittest, but still lake mock server for test. | Add pyuniotest class for unittest, but still lake mock server for test.
| Python | mit | citruspi/PyUnio | ---
+++
@@ -10,30 +10,27 @@
}
}
+class pyuniotTest(unittest.TestCase):
-def test_get():
-
- response = json.loads(pyunio.get('get', params).text)
-
- assert(response['args']['name'] == 'James Bond')
+ def test_get(self):
+ response = json.loads(pyunio.get('get', params).text)
+ self.assertEqual(response['args']['name'], 'James Bond')
-def test_post():
-
- response = json.loads(pyunio.post('post', params).text)
-
- assert(response['args']['name'] == 'James Bond')
+ def test_post(self):
+ response = json.loads(pyunio.post('post', params).text)
+ self.assertEqual(response['args']['name'], 'James Bond')
-def test_put():
-
- response = json.loads(pyunio.put('put', params).text)
-
- assert(response['args']['name'] == 'James Bond')
+ def test_put(self):
+ response = json.loads(pyunio.put('put', params).text)
+ self.assertEqual(response['args']['name'], 'James Bond')
-def test_delete():
+ def test_delete(self):
+ response = json.loads(pyunio.delete('delete', params).text)
+ self.assertEqual(response['args']['name'], 'James Bond')
- response = json.loads(pyunio.delete('delete', params).text)
- assert(response['args']['name'] == 'James Bond')
+if __name__ == '__main__':
+ unittest.main() |
1aaa261af71d8f8a57f360b9525a38fb537858d1 | sites/us/apps/shipping/repository.py | sites/us/apps/shipping/repository.py | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')
class Repository(repository.Repository):
methods = [Standard, Express]
def get_shipping_methods(self, basket, user=None, shipping_addr=None,
request=None, **kwargs):
methods = super(Repository, self).get_shipping_methods(
basket, user, shipping_addr, request, **kwargs)
if shipping_addr:
item_methods = models.OrderAndItemCharges.objects.filter(
countries=shipping_addr.country)
for method in item_methods:
methods.append(self.prime_method(basket, method))
return methods
| from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')
class Repository(repository.Repository):
def get_available_shipping_methods(
self, basket, shipping_addr=None, **kwargs):
methods = [Standard(), Express()]
if shipping_addr:
item_methods = models.OrderAndItemCharges.objects.filter(
countries=shipping_addr.country)
methods.extend(list(item_methods))
return methods
| Bring US site shipping repo up-to-date | Bring US site shipping repo up-to-date
The repo internals had changed since the US site was born.
| Python | bsd-3-clause | jinnykoo/wuyisj,john-parton/django-oscar,rocopartners/django-oscar,QLGu/django-oscar,michaelkuty/django-oscar,WillisXChen/django-oscar,eddiep1101/django-oscar,kapari/django-oscar,sonofatailor/django-oscar,jinnykoo/wuyisj,faratro/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,WillisXChen/django-oscar,jmt4/django-oscar,bnprk/django-oscar,mexeniz/django-oscar,binarydud/django-oscar,spartonia/django-oscar,machtfit/django-oscar,WillisXChen/django-oscar,kapari/django-oscar,kapt/django-oscar,WillisXChen/django-oscar,machtfit/django-oscar,okfish/django-oscar,eddiep1101/django-oscar,anentropic/django-oscar,jlmadurga/django-oscar,nickpack/django-oscar,thechampanurag/django-oscar,michaelkuty/django-oscar,ka7eh/django-oscar,jinnykoo/christmas,nfletton/django-oscar,faratro/django-oscar,Bogh/django-oscar,dongguangming/django-oscar,rocopartners/django-oscar,pasqualguerrero/django-oscar,adamend/django-oscar,bschuon/django-oscar,pdonadeo/django-oscar,django-oscar/django-oscar,rocopartners/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,monikasulik/django-oscar,spartonia/django-oscar,jinnykoo/wuyisj.com,vovanbo/django-oscar,marcoantoniooliveira/labweb,WadeYuChen/django-oscar,josesanch/django-oscar,jlmadurga/django-oscar,monikasulik/django-oscar,nickpack/django-oscar,WadeYuChen/django-oscar,ka7eh/django-oscar,pasqualguerrero/django-oscar,spartonia/django-oscar,QLGu/django-oscar,ahmetdaglarbas/e-commerce,nickpack/django-oscar,Jannes123/django-oscar,QLGu/django-oscar,MatthewWilkes/django-oscar,bnprk/django-oscar,pdonadeo/django-oscar,ademuk/django-oscar,mexeniz/django-oscar,nfletton/django-oscar,ademuk/django-oscar,marcoantoniooliveira/labweb,taedori81/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,vovanbo/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,taedori81/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,jinnykoo/wuyisj,monikasulik/django-oscar,faratro/django-oscar,amirrpp/django-oscar,django-oscar/django-oscar,jmt4/django-oscar,kapt/django-oscar,jinnykoo/christmas,saadatqadri/django-oscar,WillisXChen/django-oscar,josesanch/django-oscar,okfish/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,rocopartners/django-oscar,jinnykoo/wuyisj.com,binarydud/django-oscar,kapari/django-oscar,kapt/django-oscar,amirrpp/django-oscar,kapari/django-oscar,MatthewWilkes/django-oscar,manevant/django-oscar,anentropic/django-oscar,dongguangming/django-oscar,adamend/django-oscar,binarydud/django-oscar,lijoantony/django-oscar,saadatqadri/django-oscar,nickpack/django-oscar,jinnykoo/wuyisj,jmt4/django-oscar,sonofatailor/django-oscar,bnprk/django-oscar,lijoantony/django-oscar,sasha0/django-oscar,jinnykoo/wuyisj.com,jlmadurga/django-oscar,dongguangming/django-oscar,eddiep1101/django-oscar,eddiep1101/django-oscar,anentropic/django-oscar,MatthewWilkes/django-oscar,bschuon/django-oscar,amirrpp/django-oscar,michaelkuty/django-oscar,marcoantoniooliveira/labweb,Jannes123/django-oscar,jinnykoo/christmas,Jannes123/django-oscar,ka7eh/django-oscar,mexeniz/django-oscar,manevant/django-oscar,thechampanurag/django-oscar,nfletton/django-oscar,michaelkuty/django-oscar,saadatqadri/django-oscar,vovanbo/django-oscar,MatthewWilkes/django-oscar,anentropic/django-oscar,ahmetdaglarbas/e-commerce,ahmetdaglarbas/e-commerce,Bogh/django-oscar,taedori81/django-oscar,saadatqadri/django-oscar,Jannes123/django-oscar,lijoantony/django-oscar,thechampanurag/django-oscar,josesanch/django-oscar,Bogh/django-oscar,vovanbo/django-oscar,sasha0/django-oscar,jlmadurga/django-oscar,sonofatailor/django-oscar,pasqualguerrero/django-oscar,solarissmoke/django-oscar,itbabu/django-oscar,thechampanurag/django-oscar,bschuon/django-oscar,ademuk/django-oscar,QLGu/django-oscar,itbabu/django-oscar,amirrpp/django-oscar,nfletton/django-oscar,manevant/django-oscar,adamend/django-oscar,bnprk/django-oscar,sonofatailor/django-oscar,dongguangming/django-oscar,itbabu/django-oscar,jmt4/django-oscar,bschuon/django-oscar,ka7eh/django-oscar,binarydud/django-oscar,faratro/django-oscar,john-parton/django-oscar,WadeYuChen/django-oscar,monikasulik/django-oscar,mexeniz/django-oscar,okfish/django-oscar,john-parton/django-oscar,taedori81/django-oscar,ahmetdaglarbas/e-commerce,jinnykoo/wuyisj.com,ademuk/django-oscar,Bogh/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,marcoantoniooliveira/labweb,manevant/django-oscar,john-parton/django-oscar,itbabu/django-oscar,pdonadeo/django-oscar,pdonadeo/django-oscar,spartonia/django-oscar | ---
+++
@@ -16,17 +16,13 @@
class Repository(repository.Repository):
- methods = [Standard, Express]
- def get_shipping_methods(self, basket, user=None, shipping_addr=None,
- request=None, **kwargs):
- methods = super(Repository, self).get_shipping_methods(
- basket, user, shipping_addr, request, **kwargs)
-
+ def get_available_shipping_methods(
+ self, basket, shipping_addr=None, **kwargs):
+ methods = [Standard(), Express()]
if shipping_addr:
item_methods = models.OrderAndItemCharges.objects.filter(
countries=shipping_addr.country)
- for method in item_methods:
- methods.append(self.prime_method(basket, method))
+ methods.extend(list(item_methods))
return methods |
c2c9efed928b1414cb906cb23356e4af2baaf6e4 | LanguageServerClient.py | LanguageServerClient.py | import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
# ['langserver-go', '-trace', '-logfile', '/tmp/langserver-go.log'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
@neovim.command('GetDocumentation')
def GetDocumentation(self):
MESSAGE = {
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"processId": os.getpid(),
"rootPath": "/private/tmp/sample-rs",
"capabilities":{},
"trace":"verbose"
}
}
body = json.dumps(MESSAGE)
response = (
"Content-Length: {}\r\n\r\n"
"{}".format(len(body), body)
)
self.server.stdin.write(response.encode('utf-8'))
self.server.stdin.flush()
while True:
line = self.server.stdout.readline().decode('utf-8')
if line:
print(line)
break
def test_LanguageServerClient():
client = LanguageServerClient(None)
client.GetDocumentation()
| import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["/bin/bash", "/opt/rls/wrapper.sh"],
# ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
# ['langserver-go', '-trace', '-logfile', '/tmp/langserver-go.log'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
@neovim.command('GetDocumentation')
def GetDocumentation(self):
MESSAGE = {
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"processId": os.getpid(),
"rootPath": "/private/tmp/sample-rs",
"capabilities":{},
"trace":"verbose"
}
}
body = json.dumps(MESSAGE)
response = (
"Content-Length: {}\r\n\r\n"
"{}".format(len(body), body)
)
self.server.stdin.write(response.encode('utf-8'))
self.server.stdin.flush()
while True:
line = self.server.stdout.readline().decode('utf-8')
if line:
print(line)
break
def test_LanguageServerClient():
client = LanguageServerClient(None)
client.GetDocumentation()
| Use inout proxy script for log. | Use inout proxy script for log.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim | ---
+++
@@ -8,7 +8,8 @@
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
- ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
+ ["/bin/bash", "/opt/rls/wrapper.sh"],
+ # ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
# ['langserver-go', '-trace', '-logfile', '/tmp/langserver-go.log'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, |
4c0ad1cbf346c6d34a924c77081f2dd37e7f86ac | mochi/utils/pycloader.py | mochi/utils/pycloader.py | """Import a Python object made by compiling a Mochi file.
"""
import os
from mochi.core import pyc_compile_monkeypatch
def get_function(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
imported function.
"""
return getattr(get_module(name, file_path), name)
def get_module(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
Python module.
"""
base_path = os.path.dirname(file_path)
mochi_name = os.path.join(base_path, name + '.mochi')
py_name = os.path.join(base_path, name + '.pyc')
pyc_compile_monkeypatch(mochi_name, py_name)
return __import__(name)
| """Import a Python object made by compiling a Mochi file.
"""
import os
from mochi.core import init, pyc_compile_monkeypatch
def get_function(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
imported function.
"""
return getattr(get_module(name, file_path), name)
def get_module(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
Python module.
"""
base_path = os.path.dirname(file_path)
mochi_name = os.path.join(base_path, name + '.mochi')
py_name = os.path.join(base_path, name + '.pyc')
pyc_compile_monkeypatch(mochi_name, py_name)
return __import__(name)
init()
| Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch | Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch
| Python | mit | slideclick/mochi,i2y/mochi,pya/mochi,slideclick/mochi,i2y/mochi,pya/mochi | ---
+++
@@ -3,7 +3,7 @@
import os
-from mochi.core import pyc_compile_monkeypatch
+from mochi.core import init, pyc_compile_monkeypatch
def get_function(name, file_path):
@@ -26,3 +26,5 @@
py_name = os.path.join(base_path, name + '.pyc')
pyc_compile_monkeypatch(mochi_name, py_name)
return __import__(name)
+
+init() |
33198314eb70b079b2fdb918abd66d7296f65219 | website/addons/forward/tests/test_models.py | website/addons/forward/tests/test_models.py | # -*- coding: utf-8 -*-
from nose.tools import * # PEP8 asserts
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
from website.addons.forward.tests.factories import ForwardSettingsFactory
class TestSettingsValidation(OsfTestCase):
def setUp(self):
super(TestSettingsValidation, self).setUp()
self.settings = ForwardSettingsFactory()
def test_validate_url_bad(self):
self.settings.url = 'badurl'
with assert_raises(ValidationError):
self.settings.save()
def test_validate_url_good(self):
self.settings.url = 'http://frozen.pizza.reviews/'
try:
self.settings.save()
except ValidationError:
assert 0
def test_label_sanitary(self):
self.settings.label = 'safe'
try:
self.settings.save()
except ValidationError:
assert False
def test_label_unsanitary(self):
self.settings.label = 'un<br />safe'
with assert_raises(ValidationError):
self.settings.save()
| # -*- coding: utf-8 -*-
from nose.tools import * # PEP8 asserts
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
from tests.factories import ProjectFactory, RegistrationFactory
from website.addons.forward.tests.factories import ForwardSettingsFactory
class TestNodeSettings(OsfTestCase):
def setUp(self):
super(TestNodeSettings, self).setUp()
self.node = ProjectFactory()
self.settings = ForwardSettingsFactory(owner=self.node)
self.node.save()
def test_forward_registered(self):
registration = RegistrationFactory(project=self.node)
assert registration.has_addon('forward')
forward = registration.get_addon('forward')
assert_equal(forward.url, 'http://frozen.pizza.reviews/')
class TestSettingsValidation(OsfTestCase):
def setUp(self):
super(TestSettingsValidation, self).setUp()
self.settings = ForwardSettingsFactory()
def test_validate_url_bad(self):
self.settings.url = 'badurl'
with assert_raises(ValidationError):
self.settings.save()
def test_validate_url_good(self):
self.settings.url = 'http://frozen.pizza.reviews/'
try:
self.settings.save()
except ValidationError:
assert 0
def test_label_sanitary(self):
self.settings.label = 'safe'
try:
self.settings.save()
except ValidationError:
assert False
def test_label_unsanitary(self):
self.settings.label = 'un<br />safe'
with assert_raises(ValidationError):
self.settings.save()
| Add test for forward registering | Add test for forward registering
| Python | apache-2.0 | alexschiller/osf.io,mluo613/osf.io,emetsger/osf.io,chrisseto/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,mluo613/osf.io,caneruguz/osf.io,laurenrevere/osf.io,adlius/osf.io,aaxelb/osf.io,SSJohns/osf.io,SSJohns/osf.io,felliott/osf.io,saradbowman/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,mattclark/osf.io,rdhyee/osf.io,emetsger/osf.io,adlius/osf.io,acshi/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,icereval/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,mfraezz/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,mattclark/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,laurenrevere/osf.io,amyshi188/osf.io,TomBaxter/osf.io,baylee-d/osf.io,samchrisinger/osf.io,baylee-d/osf.io,erinspace/osf.io,caseyrollins/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,mluo613/osf.io,amyshi188/osf.io,rdhyee/osf.io,icereval/osf.io,acshi/osf.io,leb2dg/osf.io,cslzchen/osf.io,cslzchen/osf.io,samchrisinger/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,alexschiller/osf.io,adlius/osf.io,crcresearch/osf.io,SSJohns/osf.io,chennan47/osf.io,brianjgeiger/osf.io,mattclark/osf.io,pattisdr/osf.io,acshi/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,crcresearch/osf.io,SSJohns/osf.io,binoculars/osf.io,TomBaxter/osf.io,felliott/osf.io,sloria/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,wearpants/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,acshi/osf.io,Nesiehr/osf.io,binoculars/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,mfraezz/osf.io,amyshi188/osf.io,leb2dg/osf.io,aaxelb/osf.io,chrisseto/osf.io,Nesiehr/osf.io,felliott/osf.io,sloria/osf.io,caneruguz/osf.io,hmoco/osf.io,wearpants/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,caseyrollins/osf.io,hmoco/osf.io,hmoco/osf.io,binoculars/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,wearpants/osf.io,aaxelb/osf.io,alexschiller/osf.io,caneruguz/osf.io,DanielSBrown/osf.io,amyshi188/osf.io,hmoco/osf.io,emetsger/osf.io,alexschiller/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,mluo613/osf.io,icereval/osf.io,sloria/osf.io,wearpants/osf.io,saradbowman/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,chennan47/osf.io,chennan47/osf.io,cslzchen/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,acshi/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,caneruguz/osf.io | ---
+++
@@ -5,8 +5,24 @@
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
+from tests.factories import ProjectFactory, RegistrationFactory
from website.addons.forward.tests.factories import ForwardSettingsFactory
+
+class TestNodeSettings(OsfTestCase):
+
+ def setUp(self):
+ super(TestNodeSettings, self).setUp()
+ self.node = ProjectFactory()
+ self.settings = ForwardSettingsFactory(owner=self.node)
+ self.node.save()
+
+ def test_forward_registered(self):
+ registration = RegistrationFactory(project=self.node)
+ assert registration.has_addon('forward')
+
+ forward = registration.get_addon('forward')
+ assert_equal(forward.url, 'http://frozen.pizza.reviews/')
class TestSettingsValidation(OsfTestCase):
|
6413ce937fbdfdf1acc5cffab4f01f0b40fb2cfc | views.py | views.py | #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_style='compressed'
)
@app.route('/<page>')
def get_page(page):
md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
html=Markup(markdown.markdown(md.read(), output_format='html5'))
md.close()
if page=='index':
return render_template('page.html', content=html)
return render_template('page.html', content=html, title=page)
@app.route('/')
def index():
return get_page('index')
if __name__=='__main__':
app.run()
| #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup, abort
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_style='compressed'
)
@app.route('/<page>')
def get_page(page):
try:
md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
html=Markup(markdown.markdown(md.read(), output_format='html5'))
md.close()
if page=='index':
return render_template('page.html', content=html)
return render_template('page.html', content=html, title=page)
except OSError:
abort(404)
@app.route('/')
def index():
return get_page('index')
if __name__=='__main__':
app.run()
| Add basic page request exception handling | Add basic page request exception handling
| Python | mpl-2.0 | vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http | ---
+++
@@ -1,5 +1,5 @@
#!/usr/bin/python3.4
-from flask import Flask, render_template, url_for, Markup
+from flask import Flask, render_template, url_for, Markup, abort
from flask.ext.libsass import *
import pkg_resources
import markdown
@@ -16,12 +16,15 @@
@app.route('/<page>')
def get_page(page):
- md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
- html=Markup(markdown.markdown(md.read(), output_format='html5'))
- md.close()
- if page=='index':
- return render_template('page.html', content=html)
- return render_template('page.html', content=html, title=page)
+ try:
+ md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8')
+ html=Markup(markdown.markdown(md.read(), output_format='html5'))
+ md.close()
+ if page=='index':
+ return render_template('page.html', content=html)
+ return render_template('page.html', content=html, title=page)
+ except OSError:
+ abort(404)
@app.route('/')
def index(): |
066d2db105e4ac1cc5f52c0987c6c6832054bd78 | pygraphc/clustering/ConnectedComponents.py | pygraphc/clustering/ConnectedComponents.py | import networkx as nx
class ConnectedComponents:
def __init__(self, g):
self.g = g
def get_connected_components(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
cluster_id = 0
for cluster in clusters:
for node in cluster:
self.g[node]['cluster'] = cluster_id
cluster_id += 1
return clusters
| import networkx as nx
class ConnectedComponents:
def __init__(self, g):
self.g = g
def get_clusters(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
cluster_id = 0
for cluster in clusters:
for node in cluster:
self.g.node[node]['cluster'] = cluster_id
cluster_id += 1
return clusters
| Rename method get_cluster and revise self.g.node when accessing a node | Rename method get_cluster and revise self.g.node when accessing a node
| Python | mit | studiawan/pygraphc | ---
+++
@@ -5,7 +5,7 @@
def __init__(self, g):
self.g = g
- def get_connected_components(self):
+ def get_clusters(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
@@ -13,7 +13,7 @@
cluster_id = 0
for cluster in clusters:
for node in cluster:
- self.g[node]['cluster'] = cluster_id
+ self.g.node[node]['cluster'] = cluster_id
cluster_id += 1
return clusters |
ef323ee8d607b8b9e6a2ee8107324e62297e14ea | nesCart.py | nesCart.py | # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
self.romData = open(romPath, 'rb').read()
if "NES" not in self.romData[0:3]:
print "Unrecognized format!"
return None
# byte 4 - number of 16kB ROM banks
# byte 5 - number of 8kB VROM banks
(nrb, nvrb) = struct.unpack('BB', self.romData[4:6])
self.numRomBanks = nrb
self.numVromBanks = nvrb
| # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
romData = open(romPath, 'rb').read()
headerSize = 0x10
bankSize = 0x4000
vromBankSize = 0x2000
if "NES" not in romData[0:4]:
print "Unrecognized format!"
return None
# byte 4 - number of 16kB ROM banks
# byte 5 - number of 8kB VROM banks
(nrb, nvrb) = struct.unpack('BB', romData[4:6])
self.numRomBanks = nrb
self.numVromBanks = nvrb
(flags6, flags7, flags8, flags9) = \
struct.unpack('BBBB', romData[6:10])
# byte 6 flags
self.mirroring = flags6 & 1
self.battRam = flags6 & 2
self.trainer = flags6 & 4
self.fourScreen = flags6 & 8
self.lowMapper = flags6 >> 4
# byte 7 flags
self.vsSystem = flags7 & 1
self.hiMapper = flags7 >> 4
# byte 8 - num 8kB RAM banks
self.numRamBanks = flags8 if flags8 != 0 else 1
# byte 9 flags
self.pal = flags9 & 1
index = headerSize
if self.trainer == 1:
self.trainerData = romData[index:index+512]
cpu.initMemory(0x7000, self.trainderData)
index += 512
self.romBanks = []
for i in range(0, self.numRomBanks):
self.romBanks.append(romData[index:index+bankSize])
index += bankSize
self.vromBanks = []
for i in range(0, self.numVromBanks):
self.vromBanks.append(romData[index:index+vromBankSize])
index += vromBankSize
| Add the rest of the basic parsing code | Add the rest of the basic parsing code
| Python | bsd-2-clause | pusscat/refNes | ---
+++
@@ -5,14 +5,53 @@
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
- self.romData = open(romPath, 'rb').read()
+ romData = open(romPath, 'rb').read()
- if "NES" not in self.romData[0:3]:
+ headerSize = 0x10
+ bankSize = 0x4000
+ vromBankSize = 0x2000
+
+ if "NES" not in romData[0:4]:
print "Unrecognized format!"
return None
# byte 4 - number of 16kB ROM banks
# byte 5 - number of 8kB VROM banks
- (nrb, nvrb) = struct.unpack('BB', self.romData[4:6])
+ (nrb, nvrb) = struct.unpack('BB', romData[4:6])
self.numRomBanks = nrb
self.numVromBanks = nvrb
+
+ (flags6, flags7, flags8, flags9) = \
+ struct.unpack('BBBB', romData[6:10])
+
+ # byte 6 flags
+ self.mirroring = flags6 & 1
+ self.battRam = flags6 & 2
+ self.trainer = flags6 & 4
+ self.fourScreen = flags6 & 8
+ self.lowMapper = flags6 >> 4
+
+ # byte 7 flags
+ self.vsSystem = flags7 & 1
+ self.hiMapper = flags7 >> 4
+
+ # byte 8 - num 8kB RAM banks
+ self.numRamBanks = flags8 if flags8 != 0 else 1
+
+ # byte 9 flags
+ self.pal = flags9 & 1
+
+ index = headerSize
+ if self.trainer == 1:
+ self.trainerData = romData[index:index+512]
+ cpu.initMemory(0x7000, self.trainderData)
+ index += 512
+
+ self.romBanks = []
+ for i in range(0, self.numRomBanks):
+ self.romBanks.append(romData[index:index+bankSize])
+ index += bankSize
+ self.vromBanks = []
+ for i in range(0, self.numVromBanks):
+ self.vromBanks.append(romData[index:index+vromBankSize])
+ index += vromBankSize |
781a0cdce589c0b0f4ecc6966cb3abb9e79e98eb | kolibri/__init__.py | kolibri/__init__.py | """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version import get_version
# Setup the environment before loading anything else from the application
env.set_env()
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 10, 4, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version import get_version
# Setup the environment before loading anything else from the application
env.set_env()
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 10, 3, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| Revert "Updating VERSION for a new alpha" | Revert "Updating VERSION for a new alpha"
This reverts commit c0ea9cf95e38f84f9edb4576dd45290ecf42ca1f.
| Python | mit | mrpau/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri | ---
+++
@@ -15,7 +15,7 @@
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
-VERSION = (0, 10, 4, 'alpha', 0)
+VERSION = (0, 10, 3, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org' |
e40f44cf090428eea3cab01913bef614d5dae121 | pnrg/filters.py | pnrg/filters.py | from jinja2._compat import text_type
from datetime import datetime
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r'"'), r"''"),
(re.compile(r'\.\.\.+'), r'\\ldots'),
(re.compile(r'&'), r'&'),
(re.compile(r'LaTeX'), r'\\textrm{\\LaTeX}')
)
def escape_tex(value):
"""
Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers.
Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/
"""
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
def strftime(value, _format="%b %Y"):
"""
Formats a datetime object into a string. Just a simple facade around datetime.strftime.
"""
return value.strftime(_format)
| from jinja2._compat import text_type
import datetime
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r'"'), r"''"),
(re.compile(r'\.\.\.+'), r'\\ldots'),
(re.compile(r'&'), r'&'),
(re.compile(r'LaTeX'), r'\\textrm{\\LaTeX}')
)
def escape_tex(value):
"""
Escapes TeX characters to avoid breaking {La,Lua,Xe}Tex compilers.
Kang'd (with permission!) from http://flask.pocoo.org/snippets/55/
"""
newval = value
for pattern, replacement in _LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
def strftime(value, _format="%b %Y"):
"""
Formats a datetime object into a string. Just a simple facade around datetime.strftime.
"""
if isinstance(value, datetime.date):
return value.strftime(_format)
else:
return value
| Make strftime filter safe for non-date types | Make strftime filter safe for non-date types
It should probably also support datetime.datetime, but since I only have
datetime.date right now, that's not a pressing concern.
| Python | mit | sjbarag/poorly-named-resume-generator,sjbarag/poorly-named-resume-generator | ---
+++
@@ -1,5 +1,5 @@
from jinja2._compat import text_type
-from datetime import datetime
+import datetime
import re
def do_right(value, width=80):
@@ -32,4 +32,7 @@
"""
Formats a datetime object into a string. Just a simple facade around datetime.strftime.
"""
- return value.strftime(_format)
+ if isinstance(value, datetime.date):
+ return value.strftime(_format)
+ else:
+ return value |
5b712a639b2de9015e5d1a25b4edf8482254e064 | mangopay/tasks.py | mangopay/tasks.py | from celery.task import task
from .models import MangoPayNaturalUser, MangoPayBankAccount
@task
def create_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=True).create()
@task
def update_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=False).update()
@task
def create_mangopay_bank_account(id):
MangoPayBankAccount.objects.get(id=id, mangopay_id__isnull=True).create()
| from celery.task import task
from .models import MangoPayNaturalUser, MangoPayBankAccount, MangoPayDocument
@task
def create_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=True).create()
@task
def update_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=False).update()
@task
def create_mangopay_bank_account(id):
MangoPayBankAccount.objects.get(id=id, mangopay_id__isnull=True).create()
@task
def create_mangopay_document_and_page_and_ask_for_validation(id):
document = MangoPayDocument.objects.get(
id=id, mangopay_id__isnull=True, file__isnull=False,
type__isnull=False)
document.create()
document.create_page()
document.ask_for_validation()
| Add mangopay document creation task | Add mangopay document creation task
| Python | mit | FundedByMe/django-mangopay,webu/django-mangopay,DylannCordel/django-mangopay,charlietjhin/django-mangopay | ---
+++
@@ -1,6 +1,6 @@
from celery.task import task
-from .models import MangoPayNaturalUser, MangoPayBankAccount
+from .models import MangoPayNaturalUser, MangoPayBankAccount, MangoPayDocument
@task
@@ -16,3 +16,13 @@
@task
def create_mangopay_bank_account(id):
MangoPayBankAccount.objects.get(id=id, mangopay_id__isnull=True).create()
+
+
+@task
+def create_mangopay_document_and_page_and_ask_for_validation(id):
+ document = MangoPayDocument.objects.get(
+ id=id, mangopay_id__isnull=True, file__isnull=False,
+ type__isnull=False)
+ document.create()
+ document.create_page()
+ document.ask_for_validation() |
27fa3be6b7dd55637ad2b683f4027f32578ee04a | utils.py | utils.py | import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes VALUES (?, ?, ?)
''', (author, quote, created_at))
| import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY,
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes (author, quote, created_at) VALUES (?, ?, ?)
''', (author, quote, created_at))
| Add id field to quotes table | Add id field to quotes table
Specify names for insert fields
| Python | mit | nickdibari/Get-Quote | ---
+++
@@ -30,6 +30,7 @@
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
+ id INTEGER PRIMARY KEY,
author TEXT,
quote TEXT,
created_at TEXT
@@ -52,5 +53,5 @@
"""
with self.conn:
self.conn.execute('''
- INSERT INTO quotes VALUES (?, ?, ?)
+ INSERT INTO quotes (author, quote, created_at) VALUES (?, ?, ?)
''', (author, quote, created_at)) |
bc95ab06932378b3befe1c5628735f25a2807b14 | utils.py | utils.py | from google.appengine.api import users
from model import User
def create_user(google_user):
user = User(
google_user=google_user,
)
user.put()
return user
def get_current_user_model():
return get_user_model_for(users.get_current_user())
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get() | from google.appengine.api import users
from model import User
def create_user(google_user):
user = User(
google_user=google_user
)
user.put()
return user
def get_current_user_model():
return get_user_model_for(users.get_current_user())
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get() | Fix potential issue when creating users | Fix potential issue when creating users | Python | mit | studyindenmark/newscontrol,youtify/newscontrol,studyindenmark/newscontrol,youtify/newscontrol | ---
+++
@@ -3,7 +3,7 @@
def create_user(google_user):
user = User(
- google_user=google_user,
+ google_user=google_user
)
user.put()
return user |
25fc6aa427769e0d75e90e1ae0fbe41e2ca24931 | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
) | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core | Add Core Views import to the application | Add Core Views import to the application
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | ---
+++
@@ -33,3 +33,5 @@
output='css_all.css'
)
)
+
+from manager.views import core |
f84466d96bf1d9ce1525857bcbd821f7b6ee3486 | pycon/dev-settings.py | pycon/dev-settings.py | from pycon.settings import *
DEFAULT_URL_PREFIX='http://localhost:8000'
DEBUG=True
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True | from pycon.settings import *
DEFAULT_URL_PREFIX='http://localhost:8000'
DEBUG=True
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) | Add django-extensions in the dev settings | Add django-extensions in the dev settings
| Python | bsd-2-clause | artcz/epcon,EuroPython/epcon,artcz/epcon,artcz/epcon,artcz/epcon,artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon,EuroPython/epcon | ---
+++
@@ -6,3 +6,5 @@
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True
+
+INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) |
d45e40e9093b88d204335e6e0bae5dac30595d66 | pyface/qt/__init__.py | pyface/qt/__init__.py | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and PySide
#------------------------------------------------------------------------------
import os
def prepare_pyqt4():
# Set PySide compatible APIs.
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
prepare_pyqt4()
import PyQt4
qt_api = 'pyqt'
except ImportError:
raise ImportError('Cannot import PySide or PyQt4')
elif qt_api == 'pyqt':
prepare_pyqt4()
elif qt_api != 'pyside':
raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'"
% qt_api)
| #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and PySide
#------------------------------------------------------------------------------
import os
def prepare_pyqt4():
# Set PySide compatible APIs.
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
sip.setapi('QDate', 2)
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
prepare_pyqt4()
import PyQt4
qt_api = 'pyqt'
except ImportError:
raise ImportError('Cannot import PySide or PyQt4')
elif qt_api == 'pyqt':
prepare_pyqt4()
elif qt_api != 'pyside':
raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'"
% qt_api)
| Set the sip QDate API for enaml interop. | Set the sip QDate API for enaml interop.
| Python | bsd-3-clause | geggo/pyface,geggo/pyface | ---
+++
@@ -16,6 +16,7 @@
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
+ sip.setapi('QDate', 2)
qt_api = os.environ.get('QT_API')
|
d833d3f1ae0305466b691d37f3a5560821b24490 | easy/beautiful_strings/beautiful_strings.py | easy/beautiful_strings/beautiful_strings.py | from collections import Counter
import string
import sys
def beautiful_strings(line):
line = line.rstrip()
if line:
beauty = 0
count = Counter(''.join(letter for letter in line.lower()
if letter in string.lowercase))
for value in xrange(26, 26 - len(count), -1):
if count:
most_common = count.most_common(1)
beauty += most_common[0][1] * value
del count[most_common[0][0]]
return beauty
if __name__ == '__main__':
from pdb import set_trace; set_trace()
with open(sys.argv[1], 'rt') as f:
for line in f:
print beautiful_strings(line)
| from collections import Counter
import string
import sys
def beautiful_strings(line):
line = line.rstrip()
if line:
beauty = 0
count = Counter(''.join(letter for letter in line.lower()
if letter in string.lowercase))
for value in xrange(26, 26 - len(count), -1):
if count:
most_common = count.most_common(1)
beauty += most_common[0][1] * value
del count[most_common[0][0]]
return beauty
if __name__ == '__main__':
with open(sys.argv[1], 'rt') as f:
for line in f:
print beautiful_strings(line)
| Update solution to handle numbers | Update solution to handle numbers
| Python | mit | MikeDelaney/CodeEval | ---
+++
@@ -18,7 +18,6 @@
if __name__ == '__main__':
- from pdb import set_trace; set_trace()
with open(sys.argv[1], 'rt') as f:
for line in f:
print beautiful_strings(line) |
13ba4fba90f6ff654c26daf4a44d77bda3992b1f | model/__init__.py | model/__init__.py | import model.wu.user
from model.wu.user import User
def init_context(app):
model.wu.user.init_context(app)
# todo evaluate a parameter and decide which package to use (wu, hss, test(?))
| import os
model_name = os.getenv('SIPA_MODEL', 'sample')
module = __import__('{}.{}.user'.format(__name__, model_name),
fromlist='{}.{}'.format(__name__, model_name))
init_context = module.init_context
User = module.User
query_gauge_data = module.query_gauge_data
| Load model dynamically via envvar 'SIPA_MODEL' | Load model dynamically via envvar 'SIPA_MODEL'
| Python | mit | lukasjuhrich/sipa,agdsn/sipa,agdsn/sipa,fgrsnau/sipa,agdsn/sipa,agdsn/sipa,MarauderXtreme/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,fgrsnau/sipa,fgrsnau/sipa,MarauderXtreme/sipa,MarauderXtreme/sipa | ---
+++
@@ -1,8 +1,10 @@
-import model.wu.user
-from model.wu.user import User
+import os
+model_name = os.getenv('SIPA_MODEL', 'sample')
-def init_context(app):
- model.wu.user.init_context(app)
+module = __import__('{}.{}.user'.format(__name__, model_name),
+ fromlist='{}.{}'.format(__name__, model_name))
-# todo evaluate a parameter and decide which package to use (wu, hss, test(?))
+init_context = module.init_context
+User = module.User
+query_gauge_data = module.query_gauge_data |
39dd8bb26523106ed3d4ea26cd63b8732482b0cf | relationships/urls.py | relationships/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
url(r'^(?P<username>[\w-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
url(r'^add/(?P<username>[\w-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': True}, name='relationship_add'),
url(r'^remove/(?P<username>[\w-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': False}, name='relationship_remove'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
url(r'^(?P<username>[\w.@+-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
url(r'^add/(?P<username>[\w.@+-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': True}, name='relationship_add'),
url(r'^remove/(?P<username>[\w.@+-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': False}, name='relationship_remove'),
)
| Update url username matching to match regex allowed by Django. | Update url username matching to match regex allowed by Django. | Python | mit | coleifer/django-relationships,maroux/django-relationships,maroux/django-relationships,coleifer/django-relationships | ---
+++
@@ -2,7 +2,7 @@
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
- url(r'^(?P<username>[\w-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
- url(r'^add/(?P<username>[\w-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': True}, name='relationship_add'),
- url(r'^remove/(?P<username>[\w-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': False}, name='relationship_remove'),
+ url(r'^(?P<username>[\w.@+-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
+ url(r'^add/(?P<username>[\w.@+-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': True}, name='relationship_add'),
+ url(r'^remove/(?P<username>[\w.@+-]+)/(?P<status_slug>[\w-]+)/$', 'relationship_handler', {'add': False}, name='relationship_remove'),
) |
5779380fd4ec28367c1f232710291b3f81e1791f | nested_comments/views.py | nested_comments/views.py | # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.reverse import reverse
from rest_framework.response import Response
# Other AstroBin apps
from common.mixins import AjaxableResponseMixin
# This app
from .forms import NestedCommentForm
from .models import NestedComment
from .permissions import IsOwnerOrReadOnly
from .serializers import *
class NestedCommentList(generics.ListCreateAPIView):
"""
API endpoint that represents a list of nested comment.s
"""
model = NestedComment
queryset = NestedComment.objects.order_by('pk')
serializer_class = NestedCommentSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('content_type', 'object_id',)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.author = self.request.user
class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint that represents a single nested comment.
"""
model = NestedComment
serializer_class = NestedCommentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.author = self.request.user
| # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.reverse import reverse
from rest_framework.response import Response
# Other AstroBin apps
from common.mixins import AjaxableResponseMixin
# This app
from .forms import NestedCommentForm
from .models import NestedComment
from .permissions import IsOwnerOrReadOnly
from .serializers import *
class NestedCommentList(generics.ListCreateAPIView):
"""
API endpoint that represents a list of nested comment.s
"""
model = NestedComment
queryset = NestedComment.objects.order_by('pk')
serializer_class = NestedCommentSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('content_type', 'object_id',)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.author = self.request.user
class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint that represents a single nested comment.
"""
model = NestedComment
queryset = NestedComment.objects.all()
serializer_class = NestedCommentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.author = self.request.user
| Add queryset attribute to NestedCommentDetail view | Add queryset attribute to NestedCommentDetail view
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -41,6 +41,7 @@
API endpoint that represents a single nested comment.
"""
model = NestedComment
+ queryset = NestedComment.objects.all()
serializer_class = NestedCommentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,) |
761c6538d33daf59135d519f1aeaaac9b920c5ff | nova/objects/__init__.py | nova/objects/__init__.py | # Copyright 2013 IBM Corp.
#
# 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.
def register_all():
# NOTE(danms): You must make sure your object gets imported in this
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.instance')
| # Copyright 2013 IBM Corp.
#
# 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.
def register_all():
# NOTE(danms): You must make sure your object gets imported in this
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.instance')
__import__('nova.objects.instance_info_cache')
| Fix importing InstanceInfoCache during register_all() | Fix importing InstanceInfoCache during register_all()
Related to blueprint unified-object-model
Change-Id: Ib5edd0d0af46d9ba9d0fcaa14c9601ad75b8d50d
| Python | apache-2.0 | openstack/oslo.versionedobjects,citrix-openstack-build/oslo.versionedobjects | ---
+++
@@ -18,3 +18,4 @@
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.instance')
+ __import__('nova.objects.instance_info_cache') |
638e531d2007e63b45e19521c0f9a05f339dc12e | numpy/numarray/setup.py | numpy/numarray/setup.py | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('numpy/')
config.add_extension('_capi',
sources=['_capi.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('numpy/*')
config.add_extension('_capi',
sources=['_capi.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| Fix installation of numarray headers on Windows. | Fix installation of numarray headers on Windows.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7048 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | Ademan/NumPy-GSoC,illume/numpy3k,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,illume/numpy3k,teoliphant/numpy-refactor,illume/numpy3k | ---
+++
@@ -4,7 +4,7 @@
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
- config.add_data_files('numpy/')
+ config.add_data_files('numpy/*')
config.add_extension('_capi',
sources=['_capi.c'], |
555637aa86bef0b3cf5d3fe67b0341bcee5e271a | findaconf/tests/test_autocomplete_routes.py | findaconf/tests/test_autocomplete_routes.py | # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomplete.py
def test_keywords(self):
url = '/autocomplete/keywords?query=sociology&limit=10'
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
def test_google_places(self):
url = '/autocomplete/places?query=University%20of%20Essex'
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
| # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomplete.py
def test_keywords(self):
url = '/autocomplete/keywords?query=sociology&limit=10'
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
def test_google_places(self):
url = '/autocomplete/places?query=University%20of%20Essex'
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
def test_google_places_blank(self):
resp = self.app.get('/autocomplete/places?query=')
assert resp.status_code == 404
print resp.data
def test_google_places_wrong_proxy(self):
original_proxy = app.config['GOOGLE_PLACES_PROXY']
app.config['GOOGLE_PLACES_PROXY'] = 'http://python.org/ruby'
url = '/autocomplete/places?query=University'
resp = self.app.get(url)
assert resp.status_code == 404
app.config['GOOGLE_PLACES_PROXY'] = original_proxy
| Add tests for 404 on invalid routes | Add tests for 404 on invalid routes
| Python | mit | cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf | ---
+++
@@ -26,3 +26,16 @@
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
+
+ def test_google_places_blank(self):
+ resp = self.app.get('/autocomplete/places?query=')
+ assert resp.status_code == 404
+ print resp.data
+
+ def test_google_places_wrong_proxy(self):
+ original_proxy = app.config['GOOGLE_PLACES_PROXY']
+ app.config['GOOGLE_PLACES_PROXY'] = 'http://python.org/ruby'
+ url = '/autocomplete/places?query=University'
+ resp = self.app.get(url)
+ assert resp.status_code == 404
+ app.config['GOOGLE_PLACES_PROXY'] = original_proxy |
47fb142f285f989f7b911915b7b130bf4a72254b | opencraft/urls.py | opencraft/urls.py | """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', namespace="api")),
url(r'^task/', include('task.urls', namespace="task")),
url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico')),
url(r'^$', 'task.views.index'),
]
| """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', namespace="api")),
url(r'^task/', include('task.urls', namespace="task")),
url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico', permanent=False)),
url(r'^$', 'task.views.index'),
]
| Remove 1.8 warning about redirect | Remove 1.8 warning about redirect
| Python | agpl-3.0 | omarkhan/opencraft,open-craft/opencraft,open-craft/opencraft,brousch/opencraft,omarkhan/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,brousch/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft | ---
+++
@@ -10,6 +10,6 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', namespace="api")),
url(r'^task/', include('task.urls', namespace="task")),
- url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico')),
+ url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico', permanent=False)),
url(r'^$', 'task.views.index'),
] |
8d392a0723205a8229512a47355452bb94b36cfb | examples/visualization/eeg_on_scalp.py | examples/visualization/eeg_on_scalp.py | """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plot_alignment, set_3d_view
print(__doc__)
data_path = mne.datasets.sample.data_path()
subjects_dir = data_path + '/subjects'
trans = mne.read_trans(data_path + '/MEG/sample/sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
# Plot electrode locations on scalp
fig = plot_alignment(raw.info, trans, subject='sample', dig=False,
eeg=['original', 'projected'], meg=[],
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
# %%
# A similar effect can be achieved using :class:`mne.viz.Brain`:
brain = mne.viz.Brain(
'sample', 'both', 'pial', 'frontal', background='w',
subjects_dir=subjects_dir)
brain.add_head()
brain.add_sensors(raw.info, trans, meg=False, eeg=('original', 'projected'))
| """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plot_alignment, set_3d_view
print(__doc__)
data_path = mne.datasets.sample.data_path()
subjects_dir = data_path + '/subjects'
trans = mne.read_trans(data_path + '/MEG/sample/sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
# Plot electrode locations on scalp
fig = plot_alignment(raw.info, trans, subject='sample', dig=False,
eeg=['original', 'projected'], meg=[],
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
| Remove brain example [skip azp] [skip actions] | FIX: Remove brain example [skip azp] [skip actions]
| Python | bsd-3-clause | wmvanvliet/mne-python,Eric89GXL/mne-python,Teekuningas/mne-python,mne-tools/mne-python,pravsripad/mne-python,larsoner/mne-python,drammock/mne-python,mne-tools/mne-python,olafhauk/mne-python,Teekuningas/mne-python,bloyl/mne-python,larsoner/mne-python,drammock/mne-python,kingjr/mne-python,Eric89GXL/mne-python,larsoner/mne-python,wmvanvliet/mne-python,mne-tools/mne-python,bloyl/mne-python,pravsripad/mne-python,Teekuningas/mne-python,drammock/mne-python,kingjr/mne-python,olafhauk/mne-python,olafhauk/mne-python,pravsripad/mne-python,wmvanvliet/mne-python,kingjr/mne-python | ---
+++
@@ -28,12 +28,3 @@
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
-
-# %%
-# A similar effect can be achieved using :class:`mne.viz.Brain`:
-
-brain = mne.viz.Brain(
- 'sample', 'both', 'pial', 'frontal', background='w',
- subjects_dir=subjects_dir)
-brain.add_head()
-brain.add_sensors(raw.info, trans, meg=False, eeg=('original', 'projected')) |
6eec6ac19073e5bef6d8d4fc9451d173015407f7 | examples/plot_pmt_time_slewing.py | examples/plot_pmt_time_slewing.py | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import matplotlib.pyplot as plt
kp.style.use()
tots = np.arange(256)
slews = {variant: kp.calib.slew(tots, variant=variant) for variant in (1, 2, 3)}
fig, ax = plt.subplots()
for variant, slew in slews.items():
ax.plot(tots, slew, label=f"Variant {variant}")
ax.set_xlabel("ToT / ns")
ax.set_ylabel("time slewing / ns")
ax.legend()
fig.tight_layout()
plt.show()
| # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Time slewing corrects the hit time due to different rise times of the
PMT signals depending on the number of photo electrons.
The reference point is at 26.4ns and hits with a different ToT values
are corrected to refer to comparable arrival times.
The time slewing is subtracted from the measured hit time, in contrast
to the time calibration (t0), which is added.
Variant 3 is currently (as of 2020-10-16) also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import matplotlib.pyplot as plt
kp.style.use()
tots = np.arange(256)
slews = {variant: kp.calib.slew(tots, variant=variant) for variant in (1, 2, 3)}
fig, ax = plt.subplots()
for variant, slew in slews.items():
ax.plot(tots, slew, label=f"Variant {variant}")
ax.set_xlabel("ToT / ns")
ax.set_ylabel("time slewing / ns")
ax.legend()
fig.tight_layout()
plt.show()
| Add some docs to PMT time slewing | Add some docs to PMT time slewing
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -7,7 +7,14 @@
Show different variants of PMT time slewing calculations.
-Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
+Time slewing corrects the hit time due to different rise times of the
+PMT signals depending on the number of photo electrons.
+The reference point is at 26.4ns and hits with a different ToT values
+are corrected to refer to comparable arrival times.
+The time slewing is subtracted from the measured hit time, in contrast
+to the time calibration (t0), which is added.
+
+Variant 3 is currently (as of 2020-10-16) also used in Jpp.
"""
|
cc4211e2a3cdc58bf5ac3bf64711b881d1c046d0 | modules/currency.py | modules/currency.py | import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
else:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5]
to = self.msg[6]
if isinstance( amount, float ):
frm = urllib.parse.quote(frm)
to = urllib.parse.quote(to)
url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
html = syscmd.getHtml(self, url, True)
try:
soup = BeautifulSoup(html)
result = soup.findAll("div", {"id" : "currency_converter_result"})
result = "{0}".format(result[0])
trimmed = re.sub('<[^<]+?>', '', result)
self.send_chan(trimmed)
except:
pass
| import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5].upper()
to = self.msg[6].upper()
combined = frm, to
## If first value is float and currencies are valid
if isinstance( amount, float ) and frm in open("modules/data/currencies.txt").read():
print("Moi")
frm = urllib.parse.quote(frm)
to = urllib.parse.quote(to)
url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
html = syscmd.getHtml(self, url, True)
else:
self.send_chan("Usage: !currency <amount> <from> <to>")
try:
soup = BeautifulSoup(html)
result = soup.findAll("div", {"id" : "currency_converter_result"})
result = "{0}".format(result[0])
trimmed = re.sub('<[^<]+?>', '', result)
self.send_chan(trimmed)
except:
pass
| Check for valid currencies in a file | Check for valid currencies in a file
| Python | mit | jasuka/pyBot,jasuka/pyBot | ---
+++
@@ -11,18 +11,23 @@
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
- else:
+ if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
- frm = self.msg[5]
- to = self.msg[6]
- if isinstance( amount, float ):
- frm = urllib.parse.quote(frm)
- to = urllib.parse.quote(to)
- url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
- html = syscmd.getHtml(self, url, True)
+ frm = self.msg[5].upper()
+ to = self.msg[6].upper()
+ combined = frm, to
+ ## If first value is float and currencies are valid
+ if isinstance( amount, float ) and frm in open("modules/data/currencies.txt").read():
+ print("Moi")
+ frm = urllib.parse.quote(frm)
+ to = urllib.parse.quote(to)
+ url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to)
+ html = syscmd.getHtml(self, url, True)
+ else:
+ self.send_chan("Usage: !currency <amount> <from> <to>")
try:
soup = BeautifulSoup(html) |
fa5f50a4a257477f7dc0cbacec6d1cd3d8f0d217 | hdc1008test.py | hdc1008test.py | """Tests for the hdc1008 module"""
import pyb
from hdc1008 import HDC1008
i2c = pyb.I2C(2)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
while True:
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
print("Relative humidity (percent): %.2f" % (hdc.humi()))
#print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi())
print("Battery low: %s" % (hdc.battery_low()))
pyb.delay(1000)
| """Tests for the hdc1008 module"""
from hdc1008 import HDC1008
import utime
i2c = pyb.I2C(1)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
def read_sensors():
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
print("Relative humidity (percent): %.2f" % (hdc.humi()))
print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi())
print("Battery low: %s" % (hdc.battery_low()))
print("Reading sensors 10 times using normal pyb.delay() ...")
for i in range(10):
read_sensors()
utime.sleep(1000)
#print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...")
#rtc = pyb.RTC()
#rtc.wakeup(1000)
#for i in range(10):
# read_sensors()
# pyb.stop()
#rtc.wakeup(None)
| Update to the new API and small cosmetic changes. | Update to the new API and small cosmetic changes. | Python | mit | kfricke/micropython-hdc1008 | ---
+++
@@ -1,9 +1,8 @@
"""Tests for the hdc1008 module"""
+from hdc1008 import HDC1008
+import utime
-import pyb
-from hdc1008 import HDC1008
-
-i2c = pyb.I2C(2)
+i2c = pyb.I2C(1)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
@@ -11,9 +10,21 @@
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
-while True:
+def read_sensors():
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
print("Relative humidity (percent): %.2f" % (hdc.humi()))
- #print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi())
+ print("Both sensors read at once: %.2f %.2f" % hdc.temp_humi())
print("Battery low: %s" % (hdc.battery_low()))
- pyb.delay(1000)
+
+print("Reading sensors 10 times using normal pyb.delay() ...")
+for i in range(10):
+ read_sensors()
+ utime.sleep(1000)
+
+#print("Reading sensors 10 times using power-saving pyb.stop() and rtc.wakeup() ...")
+#rtc = pyb.RTC()
+#rtc.wakeup(1000)
+#for i in range(10):
+# read_sensors()
+# pyb.stop()
+#rtc.wakeup(None) |
fdb63cca26170d1348526ce8c357803ac6b37cf6 | hybrid_analysis/file_reader/hybrid_reader.py | hybrid_analysis/file_reader/hybrid_reader.py | #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
def read_afterburner_output(filename, read_initial=False):
id_event = 0
particlelist = []
if os.path.isfile(filename):
read_data = False
initial_list = False
for line in open(filename, "r"):
inputline = line.split()
if (inputline and inputline[0] == "#event"):
id_event += 1
read_data = False
if (inputline and inputline[0] == "#cols:"):
if not initial_list:
initial_list = True
if read_initial:
read_data = True
else:
initial_list = False
if read_initial:
read_data = False
else:
read_data = True
if read_data:
try:
x = float(inputline[0])
ptype = int(inputline[8])
except ValueError:
continue
particlelist.append((tuple(inputline), id_event))
return particlelist
| #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
import copy
from .. import dataobjects.particledata
def read_afterburner_output(filename, read_initial=False):
id_event = 0
if os.path.isfile(filename):
read_data = False
initial_list = False
eventlist = []
particlelist = []
for line in open(filename, "r"):
inputline = line.split()
if (inputline and inputline[0] == "#event"):
id_event += 1
read_data = False
if (len(particlelist) > 0):
eventlist.append(copy.copy(particlelist))
del particlelist[:]
if (inputline and inputline[0] == "#cols:"):
if not initial_list:
initial_list = True
if read_initial:
read_data = True
else:
initial_list = False
if read_initial:
read_data = False
else:
read_data = True
if read_data:
try:
px = float(inputline[4])
py = float(inputline[5])
pz = float(inputline[6])
E = float(inputline[7])
ptype = int(inputline[8])
charge = int(inputline[10])
except ValueError:
continue
particledata = ParticleData([E, px, py, pz], ptype, charge)
particlelist.append(particledata)
if (len(particlelist) > 0):
eventlist.append(copy.copy(particlelist))
del particlelist[:]
return eventlist
| Use ParticleData class in file reader | Use ParticleData class in file reader
File reader now creates lists of ParticleData objects.
Signed-off-by: Jussi Auvinen <16b8c81f9479dec4f5eedf7ae5a2413c6a10bc13@phy.duke.edu>
| Python | mit | jauvinen/hybrid-model-analysis | ---
+++
@@ -3,18 +3,24 @@
# Functions for reading hybrid model output(s)
import os
+import copy
+from .. import dataobjects.particledata
def read_afterburner_output(filename, read_initial=False):
id_event = 0
- particlelist = []
if os.path.isfile(filename):
read_data = False
initial_list = False
+ eventlist = []
+ particlelist = []
for line in open(filename, "r"):
inputline = line.split()
if (inputline and inputline[0] == "#event"):
id_event += 1
read_data = False
+ if (len(particlelist) > 0):
+ eventlist.append(copy.copy(particlelist))
+ del particlelist[:]
if (inputline and inputline[0] == "#cols:"):
if not initial_list:
initial_list = True
@@ -29,10 +35,19 @@
if read_data:
try:
- x = float(inputline[0])
+ px = float(inputline[4])
+ py = float(inputline[5])
+ pz = float(inputline[6])
+ E = float(inputline[7])
ptype = int(inputline[8])
+ charge = int(inputline[10])
except ValueError:
continue
- particlelist.append((tuple(inputline), id_event))
+ particledata = ParticleData([E, px, py, pz], ptype, charge)
+ particlelist.append(particledata)
- return particlelist
+ if (len(particlelist) > 0):
+ eventlist.append(copy.copy(particlelist))
+ del particlelist[:]
+
+ return eventlist |
a23641edf1fd941768eebb1938340d2173ac2e11 | iputil/parser.py | iputil/parser.py | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
match = IP_REGEX.findall(line)
if match:
matches += match
return set(sorted(matches)) if matches else set()
def store_ips(cache_path, ips):
"""Stores the IPs into a cache for later retrieval."""
cache = []
if os.path.exists(cache_path):
with open(cache_path, 'rb') as f:
cache = json.loads(f.read())
new_ips = 0
existing_ips = [i['ip'] for i in cache]
for ip in ips:
if ip not in existing_ips:
cache.append({'ip': ip})
new_ips += 1
with open(cache_path, 'wb') as f:
f.write(json.dumps(cache))
return new_ips
| import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
matches += IP_REGEX.findall(line)
return set(sorted(matches)) if matches else set()
def store_ips(cache_path, ips):
"""Stores the IPs into a cache for later retrieval."""
cache = []
if os.path.exists(cache_path):
with open(cache_path, 'rb') as f:
cache = json.loads(f.read())
new_ips = 0
existing_ips = [i['ip'] for i in cache]
for ip in ips:
if ip not in existing_ips:
cache.append({'ip': ip})
new_ips += 1
with open(cache_path, 'wb') as f:
f.write(json.dumps(cache))
return new_ips
| Remove unnecessary check, used to re functions returning different types | Remove unnecessary check, used to re functions returning different types
| Python | mit | kolanos/iputil | ---
+++
@@ -10,9 +10,7 @@
matches = []
with open(filename) as f:
for line in f:
- match = IP_REGEX.findall(line)
- if match:
- matches += match
+ matches += IP_REGEX.findall(line)
return set(sorted(matches)) if matches else set()
|
18d5b71dbbef2112d9fa8c48e2e894aa7321a4dc | tests/end2end/testapp/wsgi.py | tests/end2end/testapp/wsgi.py | """
WSGI config for testsite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.settings")
application = get_wsgi_application()
| """
WSGI config for testapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
application = get_wsgi_application()
| Rename references to "testsite" to "testapp". | Rename references to "testsite" to "testapp".
| Python | apache-2.0 | obytes/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,wangwanzhong/django-prometheus,DingaGa/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus | ---
+++
@@ -1,5 +1,5 @@
"""
-WSGI config for testsite project.
+WSGI config for testapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
@@ -11,6 +11,6 @@
from django.core.wsgi import get_wsgi_application
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.settings")
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
application = get_wsgi_application() |
2e1774aa0505873f7a3e8fe5a120e8931200fa35 | pokr/models/__init__.py | pokr/models/__init__.py | import assembly
import bill
import bill_feed
import bill_keyword
import bill_review
import bill_status
import bill_withdrawal
import candidacy
import cosponsorship
import election
import favorite_keyword
import favorite_person
import feed
import keyword
import meeting
import meeting_attendee
import party
import person
import pledge
import region
import school
import statement
import user
import query_log
| from assembly import *
from bill import *
from bill_feed import *
from bill_keyword import *
from bill_review import *
from bill_status import *
from bill_withdrawal import *
from candidacy import *
from cosponsorship import *
from election import *
from favorite_keyword import *
from favorite_person import *
from feed import *
from keyword import *
from meeting import *
from meeting_attendee import *
from party import *
from person import *
from pledge import *
from region import *
from school import *
from statement import *
from user import *
from query_log import *
| Make 'from pokr.models import ~' possible | Make 'from pokr.models import ~' possible
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | ---
+++
@@ -1,24 +1,24 @@
-import assembly
-import bill
-import bill_feed
-import bill_keyword
-import bill_review
-import bill_status
-import bill_withdrawal
-import candidacy
-import cosponsorship
-import election
-import favorite_keyword
-import favorite_person
-import feed
-import keyword
-import meeting
-import meeting_attendee
-import party
-import person
-import pledge
-import region
-import school
-import statement
-import user
-import query_log
+from assembly import *
+from bill import *
+from bill_feed import *
+from bill_keyword import *
+from bill_review import *
+from bill_status import *
+from bill_withdrawal import *
+from candidacy import *
+from cosponsorship import *
+from election import *
+from favorite_keyword import *
+from favorite_person import *
+from feed import *
+from keyword import *
+from meeting import *
+from meeting_attendee import *
+from party import *
+from person import *
+from pledge import *
+from region import *
+from school import *
+from statement import *
+from user import *
+from query_log import * |
09225071761ae059c46393d41180b6c37d1b3edc | portal/models/locale.py | portal/models/locale.py | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
| from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
| Correct coding error - need to return coding from property function or it'll cache None. | Correct coding error - need to return coding from property function or it'll cache None.
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal | ---
+++
@@ -10,7 +10,6 @@
within for easy access and testing
"""
-
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
@@ -19,12 +18,12 @@
@lazyprop
def AmericanEnglish(self):
- Coding(
+ return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
- Coding(
+ return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True) |
3664b2d9b7590b6750e35abba2c0fe77c7afd4cd | bin/license_finder_pip.py | bin/license_finder_pip.py | #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
from pip._internal.download import PipSession
except ImportError:
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
reqs = []
for req in parse_requirements(sys.argv[1], session=PipSession()):
if req.req == None or (req.markers != None and not req.markers.evaluate()): continue
reqs.append(req)
requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs]
transform = lambda dist: {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),
}
packages = [transform(dist) for dist
in pkg_resources.working_set.resolve(requirements)]
print_(json.dumps(packages))
| #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
# since pip 19.3
from pip._internal.network.session import PipSession
except ImportError:
try:
# since pip 10
from pip._internal.download import PipSession
except ImportError:
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
reqs = []
for req in parse_requirements(sys.argv[1], session=PipSession()):
if req.req == None or (req.markers != None and not req.markers.evaluate()): continue
reqs.append(req)
requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs]
transform = lambda dist: {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),
}
packages = [transform(dist) for dist
in pkg_resources.working_set.resolve(requirements)]
print_(json.dumps(packages))
| Support finding licenses with pip>=19.3 | Support finding licenses with pip>=19.3
| Python | mit | pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder | ---
+++
@@ -7,9 +7,15 @@
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
+
try:
+ # since pip 19.3
+ from pip._internal.network.session import PipSession
+except ImportError:
+ try:
+ # since pip 10
from pip._internal.download import PipSession
-except ImportError:
+ except ImportError:
from pip.download import PipSession
from pip._vendor import pkg_resources |
f4209f7be27ef1ce0725f525a7029246c4c54631 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| Switch to more optimal non-generator solution | Switch to more optimal non-generator solution
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,13 +1,10 @@
def sieve(n):
- return list(primes(n))
-
-
-def primes(n):
if n < 2:
- raise StopIteration
- yield 2
+ return []
not_prime = set()
+ prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
- yield i
- not_prime.update(range(i*i, n, i))
+ prime.append(i)
+ not_prime.update(range(i*i, n, i))
+ return prime |
fd78ef63d6f4f39886a16e495c79ca42109e7886 | ip/__init__.py | ip/__init__.py | # -*- coding: utf-8 -*-
from ip import Ip
from ipv4 import Ipv4
from ipv6 import Ipv6
__name__ = 'ip'
__version__ = '0.1'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff'
__all__ = ['Ip', 'Ipv4', 'Ipv6'] | # -*- coding: utf-8 -*-
from ip import Ip
from ipv4 import Ipv4
from ipv6 import Ipv6
__name__ = 'ip'
__version__ = '0.2'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff'
__all__ = ['Ip', 'Ipv4', 'Ipv6'] | Increase version number due to usable Ipv4 class | Increase version number due to usable Ipv4 class
| Python | mit | foxfluff/ip-py | ---
+++
@@ -5,7 +5,7 @@
from ipv6 import Ipv6
__name__ = 'ip'
-__version__ = '0.1'
+__version__ = '0.2'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff' |
a633e7c1c5ca2fff4018ab7f51136ba9ad1b9cde | grammpy_transforms/contextfree.py | grammpy_transforms/contextfree.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree():
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False):
return remove_nongenerating_symbols(grammar, transform_grammar)
@staticmethod
def is_grammar_generating(grammar: Grammar):
g = ContextFree.remove_nongenerating_symbols(grammar)
return g.start_get() in g.nonterms()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree:
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False):
return remove_nongenerating_symbols(grammar, transform_grammar)
@staticmethod
def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True):
g = grammar
if perform_remove:
g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar)
return g.start_get() in g.nonterms()
| Add additional parameters into CotextFree.is_grammar_generating method | Add additional parameters into CotextFree.is_grammar_generating method
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -11,12 +11,14 @@
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
-class ContextFree():
+class ContextFree:
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False):
return remove_nongenerating_symbols(grammar, transform_grammar)
@staticmethod
- def is_grammar_generating(grammar: Grammar):
- g = ContextFree.remove_nongenerating_symbols(grammar)
+ def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True):
+ g = grammar
+ if perform_remove:
+ g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar)
return g.start_get() in g.nonterms() |
fafd048452ebfb3379ab428cc74e795d3406478f | apps/comments/models.py | apps/comments/models.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.ForeignKey('profiles.User', related_name='users')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
comment = models.TextField()
def __unicode__(self):
return '{0}: {1}...'.format(self.user.first_name, self.comment[:50])
class Meta:
ordering = ('date_created',)
def comment_saved(sender, instance, created, **kwargs):
mentor = instance.content_object.mentor
protege = instance.content_object.protege
meeting_url = instance.content_object.get_url_with_domain()
if created:
if instance.user == mentor:
recipient = protege
elif instance.user == protege:
recipient = mentor
notification.send(
[recipient],
'comment',
{'comment': instance,
'recipient': recipient,
'meeting_url': meeting_url})
post_save.connect(comment_saved, sender=Comment)
| from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.ForeignKey('profiles.User', related_name='users')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
comment = models.TextField()
def __unicode__(self):
return '{0}: {1}...'.format(self.user.first_name, self.comment[:50])
class Meta:
ordering = ('date_created',)
def comment_saved(sender, instance, created, **kwargs):
mentor = instance.content_object.mentor
protege = instance.content_object.protege
meeting_url = instance.content_object.get_url_with_domain()
if instance.user == mentor:
recipient = protege
elif instance.user == protege:
recipient = mentor
if created and recipient:
notification.send(
[recipient],
'comment',
{'comment': instance,
'recipient': recipient,
'meeting_url': meeting_url})
post_save.connect(comment_saved, sender=Comment)
| Make sure we have a recipient before sending notification | Make sure we have a recipient before sending notification | Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas | ---
+++
@@ -27,13 +27,13 @@
protege = instance.content_object.protege
meeting_url = instance.content_object.get_url_with_domain()
- if created:
- if instance.user == mentor:
- recipient = protege
+ if instance.user == mentor:
+ recipient = protege
- elif instance.user == protege:
- recipient = mentor
+ elif instance.user == protege:
+ recipient = mentor
+ if created and recipient:
notification.send(
[recipient],
'comment', |
db4611b6e3585321e84876332ac84a26ec623ae9 | valuenetwork/local_settings_development.py | valuenetwork/local_settings_development.py |
#for a development machine
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#this is nice for development
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'valuenetwork.sqlite'
}
}
# valueaccounting settings can be overridden
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
#example: Greece
MAP_LATITUDE = 38.2749497
MAP_LONGITUDE = 23.8102717
MAP_ZOOM = 6
#and you can override any other settings in settings.py |
#for a development machine
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#this is nice for development
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'valuenetwork.sqlite'
}
}
# valueaccounting settings can be overridden
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
STATIC_URL = "/static/"
#example: Greece
MAP_LATITUDE = 38.2749497
MAP_LONGITUDE = 23.8102717
MAP_ZOOM = 6
#and you can override any other settings in settings.py | Add static URL to development settings | Add static URL to development settings
| Python | agpl-3.0 | thierrymarianne/valuenetwork,FreedomCoop/valuenetwork,valnet/valuenetwork,thierrymarianne/valuenetwork,django-rea/nrp,FreedomCoop/valuenetwork,valnet/valuenetwork,FreedomCoop/valuenetwork,django-rea/nrp,simontegg/valuenetwork,simontegg/valuenetwork,thierrymarianne/valuenetwork,FreedomCoop/valuenetwork,django-rea/nrp,thierrymarianne/valuenetwork,valnet/valuenetwork,django-rea/nrp,simontegg/valuenetwork,simontegg/valuenetwork,valnet/valuenetwork | ---
+++
@@ -17,6 +17,8 @@
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
+STATIC_URL = "/static/"
+
#example: Greece
MAP_LATITUDE = 38.2749497
MAP_LONGITUDE = 23.8102717 |
be746c870f2015507af5513a8636905cf9018001 | image_cropping/thumbnail_processors.py | image_cropping/thumbnail_processors.py | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if isinstance(box, basestring):
if box.startswith('-'):
pass # TBC: what does this indicate? No-op value?
else:
try:
box = map(int, box.split(','))
except (ValueError, IndexError):
# There's garbage in the cropping field, ignore
logger.warning(
'Unable to parse "box" parameter "%s". Ignoring.' % box)
if isinstance(box, (list, tuple)):
if len(box) == 4:
if sum(box) < 0:
pass # TODO: add explanatory comment for this please
else:
width = abs(box[2] - box[0])
height = abs(box[3] - box[1])
if width and height and (width, height) != image.size:
image = image.crop(box)
else:
logger.warning(
'"box" parameter requires four values. Ignoring "%r".' % (box,)
)
return image
| import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if box and not box.startswith('-'):
# a leading - indicates that cropping is disabled
try:
box = map(int, box.split(','))
except ValueError:
# there's garbage in the cropping field, ignore
logger.warning(
'Unable to parse "box" parameter "%s". Ignoring.' % box)
if len(box) == 4:
if sum(box) > 0:
# negative box values indicate that cropping is disabled
width = abs(box[2] - box[0])
height = abs(box[3] - box[1])
if width and height and (width, height) != image.size:
image = image.crop(box)
else:
logger.warning(
'"box" parameter requires four values. Ignoring "%r".' % box)
return image
| Tweak thumbnail processor a little | Tweak thumbnail processor a little
| Python | bsd-3-clause | henriquechehad/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping | ---
+++
@@ -2,6 +2,7 @@
logger = logging.getLogger(__name__)
+
def crop_corners(image, box=None, **kwargs):
"""
@@ -9,30 +10,23 @@
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
- if isinstance(box, basestring):
- if box.startswith('-'):
- pass # TBC: what does this indicate? No-op value?
- else:
- try:
- box = map(int, box.split(','))
- except (ValueError, IndexError):
- # There's garbage in the cropping field, ignore
- logger.warning(
- 'Unable to parse "box" parameter "%s". Ignoring.' % box)
+ if box and not box.startswith('-'):
+ # a leading - indicates that cropping is disabled
+ try:
+ box = map(int, box.split(','))
+ except ValueError:
+ # there's garbage in the cropping field, ignore
+ logger.warning(
+ 'Unable to parse "box" parameter "%s". Ignoring.' % box)
- if isinstance(box, (list, tuple)):
if len(box) == 4:
- if sum(box) < 0:
- pass # TODO: add explanatory comment for this please
- else:
+ if sum(box) > 0:
+ # negative box values indicate that cropping is disabled
width = abs(box[2] - box[0])
height = abs(box[3] - box[1])
if width and height and (width, height) != image.size:
image = image.crop(box)
else:
logger.warning(
- '"box" parameter requires four values. Ignoring "%r".' % (box,)
- )
-
+ '"box" parameter requires four values. Ignoring "%r".' % box)
return image
- |
f6d4f822d8f0f34316c5a2c92c8ceade7bc7fdbd | movieman/movieman.py | movieman/movieman.py | import requests
import os
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, dirs, files in os.walk(dir_):
for file_ in files:
movies.append({
'title': os.path.splitext(file_)[0].rsplit(' ', 1),
'fpath': os.path.join(root, file_)
})
return movies
def main(dir_='/Users/kashavmadan/Downloads/movies'):
table = list()
table.append(['Title', 'Plot', 'Genre', 'Actors', 'Rating', 'Runtime', 'Released', 'Score'])
for t in get_titles(dir_):
movie = request_data(t['title'][0], t['title'][1])
table.append([
movie['Title'],
movie['Plot'],
movie['Genre'],
movie['Actors'],
movie['Rated'],
movie['Runtime'],
movie['Released'],
movie['imdbRating']])
f = open('movies.txt', 'w')
f.write(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
f.close()
if __name__ == '__main__':
main()
| import requests
import os
import sys
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, dirs, files in os.walk(dir_):
for file_ in files:
movies.append({
'title': os.path.splitext(file_)[0].rsplit(' ', 1),
'fpath': os.path.join(root, file_)
})
return movies
def main(dir_=MOVIEDIR):
f = open(dir_ + '/movies.txt', 'w')
for t in get_titles(dir_):
movie = request_data(t['title'], t['year'])
f.write('{}\n{}\n\n{} | {}\n{} | {} | {} | {} on IMDb\n{}\n\n\n'.format(
movie['Title'],
movie['Plot'],
movie['Director'],
movie['Actors'],
movie['Released'],
movie['Runtime'],
movie['Rated'],
movie['imdbRating'],
'http://www.imdb.com/title/' + movie['imdbID'] + '/',
))
f.close()
if __name__ == '__main__':
main()
| Replace console output for raw txt | Replace console output for raw txt
| Python | mit | kshvmdn/movieman | ---
+++
@@ -1,5 +1,6 @@
import requests
import os
+import sys
from pprint import pprint
from tabulate import tabulate
@@ -22,22 +23,24 @@
return movies
-def main(dir_='/Users/kashavmadan/Downloads/movies'):
- table = list()
- table.append(['Title', 'Plot', 'Genre', 'Actors', 'Rating', 'Runtime', 'Released', 'Score'])
+def main(dir_=MOVIEDIR):
+ f = open(dir_ + '/movies.txt', 'w')
+
for t in get_titles(dir_):
- movie = request_data(t['title'][0], t['title'][1])
- table.append([
+ movie = request_data(t['title'], t['year'])
+
+ f.write('{}\n{}\n\n{} | {}\n{} | {} | {} | {} on IMDb\n{}\n\n\n'.format(
movie['Title'],
movie['Plot'],
- movie['Genre'],
+ movie['Director'],
movie['Actors'],
+ movie['Released'],
+ movie['Runtime'],
movie['Rated'],
- movie['Runtime'],
- movie['Released'],
- movie['imdbRating']])
- f = open('movies.txt', 'w')
- f.write(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
+ movie['imdbRating'],
+ 'http://www.imdb.com/title/' + movie['imdbID'] + '/',
+ ))
+
f.close()
|
0c027086cf6491a301b08b8e0cb1565715e615fe | webapp/byceps/blueprints/ticket/service.py | webapp/byceps/blueprints/ticket/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""Return the ticket used by the user for the party, or `None` if not
found.
"""
if user.is_anonymous:
return None
return Ticket.query \
.filter(Ticket.used_by == user) \
.options(
db.joinedload('occupied_seat').joinedload('area'),
) \
.for_party(party) \
.first()
def get_attended_parties(user):
"""Return the parties the user has attended."""
return Party.query \
.join(Category).join(Ticket).filter(Ticket.used_by == user) \
.all()
def count_tickets_for_party(party):
"""Return the number of "sold" (i.e. generated) tickets for that party."""
return Ticket.query \
.join(Category).filter(Category.party_id == party.id) \
.count()
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
def find_ticket_for_user(user, party):
"""Return the ticket used by the user for the party, or `None` if not
found.
"""
if user.is_anonymous:
return None
return Ticket.query \
.filter_by(used_by=user) \
.options(
db.joinedload('occupied_seat').joinedload('area'),
) \
.for_party(party) \
.first()
def get_attended_parties(user):
"""Return the parties the user has attended."""
return Party.query \
.join(Category).join(Ticket).filter(Ticket.used_by == user) \
.all()
def count_tickets_for_party(party):
"""Return the number of "sold" (i.e. generated) tickets for that party."""
return Ticket.query \
.join(Category).filter(Category.party_id == party.id) \
.count()
| Use more succinct syntax to filter in database query. | Use more succinct syntax to filter in database query.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -24,7 +24,7 @@
return None
return Ticket.query \
- .filter(Ticket.used_by == user) \
+ .filter_by(used_by=user) \
.options(
db.joinedload('occupied_seat').joinedload('area'),
) \ |
481fe3e66b51e0bed3b62a6b46919b487ac67369 | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.3.dev0'
| Update dsub version to 0.4.3.dev0 | Update dsub version to 0.4.3.dev0
PiperOrigin-RevId: 337359189
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.2'
+DSUB_VERSION = '0.4.3.dev0' |
996611b4ec0f0e13769d40122f21b6a6362783a5 | app.tmpl/models.py | app.tmpl/models.py | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
os.path.join(app.root_path, app.name + '.db'))
db = SQLAlchemy(app)
#class MyModel(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# # Quickref:
# # types: Integer, String(L), Text, DateTime, ForeignKey('table.col')
# # keywords: primary_key, nullable, unique, default
# # rels: db.relationship('OtherModel', backref=db.backref('mymodels'))
#
#
# def __init__(self, ...):
# pass
#
#
# def __str__(self):
# return self.name
#
#
# def __repr__(self):
# return '<{} {!r}>'.format(self.__class__.__name__, self.id)
| # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
os.path.join(app.root_path, app.name + '.db'))
db = SQLAlchemy(app)
migrate = Migrate(app, db)
#class MyModel(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# # Quickref:
# # types: Integer, String(L), Text, DateTime, ForeignKey('table.col')
# # keywords: primary_key, nullable, unique, default
# # rels: db.relationship('OtherModel', backref=db.backref('mymodels'))
#
#
# def __init__(self, ...):
# pass
#
#
# def __str__(self):
# return self.name
#
#
# def __repr__(self):
# return '<{} {!r}>'.format(self.__class__.__name__, self.id)
| Use newer package import syntax for Flask | Use newer package import syntax for Flask
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template | ---
+++
@@ -5,7 +5,8 @@
import os, os.path
from datetime import datetime
-from flask.ext.sqlalchemy import SQLAlchemy
+from flask_sqlalchemy import SQLAlchemy
+from flask_migrate import Migrate
from {{PROJECTNAME}} import app
@@ -13,6 +14,7 @@
os.path.join(app.root_path, app.name + '.db'))
db = SQLAlchemy(app)
+migrate = Migrate(app, db)
#class MyModel(db.Model): |
9d7c55855b2226ff1aef36ed82d34d2f3626d376 | easyium/exceptions.py | easyium/exceptions.py | __author__ = 'karl.gong'
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
self.msg = msg
self.message = self.msg
self.context = context
def __str__(self):
exception_msg = ""
if self.msg is not None:
exception_msg = self.msg
if self.context is not None:
exception_msg += "\n" + str(self.context)
return exception_msg
class TimeoutException(EasyiumException):
pass
class ElementTimeoutException(TimeoutException):
pass
class WebDriverTimeoutException(TimeoutException):
pass
class NoSuchElementException(EasyiumException):
pass
class NotPersistException(EasyiumException):
pass
class LatePersistException(EasyiumException):
pass
class UnsupportedWebDriverTypeException(EasyiumException):
pass
class InvalidLocatorException(EasyiumException):
pass
class UnsupportedOperationException(EasyiumException):
pass
| import re
__author__ = 'karl.gong'
filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)")
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
# Remove Session info and Driver info of the message.
self.msg = filter_msg_regex.sub("", msg)
self.message = self.msg
self.context = context
def __str__(self):
exception_msg = ""
if self.msg is not None:
exception_msg = self.msg
if self.context is not None:
exception_msg += "\n" + str(self.context)
return exception_msg
class TimeoutException(EasyiumException):
pass
class ElementTimeoutException(TimeoutException):
pass
class WebDriverTimeoutException(TimeoutException):
pass
class NoSuchElementException(EasyiumException):
pass
class NotPersistException(EasyiumException):
pass
class LatePersistException(EasyiumException):
pass
class UnsupportedWebDriverTypeException(EasyiumException):
pass
class InvalidLocatorException(EasyiumException):
pass
class UnsupportedOperationException(EasyiumException):
pass
| Remove session info and driver info of webdriverexception. | Remove session info and driver info of webdriverexception.
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium | ---
+++
@@ -1,9 +1,14 @@
+import re
+
__author__ = 'karl.gong'
+
+filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)")
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
- self.msg = msg
+ # Remove Session info and Driver info of the message.
+ self.msg = filter_msg_regex.sub("", msg)
self.message = self.msg
self.context = context
|
efa20f9d88fab8b62a95d126500f220255ce6633 | src/yaml_server_test/YamlReader_test.py | src/yaml_server_test/YamlReader_test.py | import unittest
import logging
from yaml_server.YamlReader import YamlReader
from yaml_server.YamlServerException import YamlServerException
class Test(unittest.TestCase):
data1_data = {
'data1': 'test1',
'data2': [
{
'test3': 'data4',
'test5': 'data5'
},
{
'test6': 'data6'
}
]
}
def setUp(self):
unittest.TestCase.setUp(self)
self.logger = logging.getLogger()
self.loghandler = logging.StreamHandler()
self.loghandler.setFormatter(logging.Formatter('yaml_server[%(module)s %(funcName)s]: %(levelname)s: %(message)s'))
self.logger.addHandler(self.loghandler)
self.logger.setLevel(logging.DEBUG)
def test_should_correctly_merge_yaml_files(self):
self.assertEqual(YamlReader("testdata/data1").get(), self.data1_data)
def test_should_fail_on_invalid_yaml_dir(self):
self.assertRaises(YamlServerException, YamlReader,"/dev/null")
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| import unittest
import logging
from yaml_server.YamlReader import YamlReader
from yaml_server.YamlServerException import YamlServerException
class Test(unittest.TestCase):
data1_data = {
'data1': 'test1',
'data2': [
{
'test3': 'data4',
'test5': 'data5'
},
{
'test6': 'data6'
}
]
}
def setUp(self):
unittest.TestCase.setUp(self)
self.logger = logging.getLogger()
self.loghandler = logging.StreamHandler()
self.loghandler.setFormatter(logging.Formatter('yaml_server[%(filename)s:%(lineno)d]: %(levelname)s: %(message)s'))
self.logger.addHandler(self.loghandler)
self.logger.setLevel(logging.DEBUG)
def test_should_correctly_merge_yaml_files(self):
self.assertEqual(YamlReader("testdata/data1").get(), self.data1_data)
def test_should_fail_on_invalid_yaml_dir(self):
self.assertRaises(YamlServerException, YamlReader,"/dev/null")
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Adjust log prefix in tests for Python 2.4 | Adjust log prefix in tests for Python 2.4 | Python | apache-2.0 | ImmobilienScout24/yamlreader,pombredanne/yamlreader | ---
+++
@@ -23,7 +23,7 @@
unittest.TestCase.setUp(self)
self.logger = logging.getLogger()
self.loghandler = logging.StreamHandler()
- self.loghandler.setFormatter(logging.Formatter('yaml_server[%(module)s %(funcName)s]: %(levelname)s: %(message)s'))
+ self.loghandler.setFormatter(logging.Formatter('yaml_server[%(filename)s:%(lineno)d]: %(levelname)s: %(message)s'))
self.logger.addHandler(self.loghandler)
self.logger.setLevel(logging.DEBUG)
|
b2854df273d2fa84a3bb5f2e0f2574f4ea80fb04 | migrations/211-recategorize-canned-responses.py | migrations/211-recategorize-canned-responses.py | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wiki.config import CANNED_RESPONSES_CATEGORY
to_move = list(Document.objects.filter(slug__startswith='forum-response-',
locale=settings.WIKI_DEFAULT_LANGUAGE))
to_move.append(Document.objects.get(slug='common-forum-responses',
locale=settings.WIKI_DEFAULT_LANGUAGE))
print 'Recategorizing %d common response articles.' % len(to_move)
for doc in to_move:
doc.category = CANNED_RESPONSES_CATEGORY
doc.is_localizable = True
doc.save()
| """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wiki.config import CANNED_RESPONSES_CATEGORY
to_move = list(Document.objects.filter(slug__startswith='forum-response-',
locale=settings.WIKI_DEFAULT_LANGUAGE))
try:
to_move.append(Document.objects.get(slug='common-forum-responses',
locale=settings.WIKI_DEFAULT_LANGUAGE))
except Document.DoesNotExist:
pass
print 'Recategorizing %d common response articles.' % len(to_move)
for doc in to_move:
doc.category = CANNED_RESPONSES_CATEGORY
doc.is_localizable = True
doc.save()
| Fix migration 211 to handle lack of data. | Fix migration 211 to handle lack of data.
| Python | bsd-3-clause | Osmose/kitsune,feer56/Kitsune1,orvi2014/kitsune,Osmose/kitsune,iDTLabssl/kitsune,mythmon/kitsune,asdofindia/kitsune,chirilo/kitsune,rlr/kitsune,feer56/Kitsune2,silentbob73/kitsune,mozilla/kitsune,philipp-sumo/kitsune,asdofindia/kitsune,YOTOV-LIMITED/kitsune,anushbmx/kitsune,rlr/kitsune,dbbhattacharya/kitsune,safwanrahman/kitsune,silentbob73/kitsune,MziRintu/kitsune,NewPresident1/kitsune,MikkCZ/kitsune,mythmon/kitsune,H1ghT0p/kitsune,philipp-sumo/kitsune,NewPresident1/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune,philipp-sumo/kitsune,turtleloveshoes/kitsune,feer56/Kitsune2,chirilo/kitsune,anushbmx/kitsune,anushbmx/kitsune,orvi2014/kitsune,safwanrahman/kitsune,YOTOV-LIMITED/kitsune,chirilo/kitsune,asdofindia/kitsune,iDTLabssl/kitsune,YOTOV-LIMITED/kitsune,feer56/Kitsune2,safwanrahman/linuxdesh,MikkCZ/kitsune,feer56/Kitsune1,mozilla/kitsune,mozilla/kitsune,orvi2014/kitsune,brittanystoroz/kitsune,H1ghT0p/kitsune,NewPresident1/kitsune,safwanrahman/linuxdesh,MziRintu/kitsune,safwanrahman/kitsune,iDTLabssl/kitsune,MziRintu/kitsune,orvi2014/kitsune,safwanrahman/kitsune,safwanrahman/linuxdesh,chirilo/kitsune,dbbhattacharya/kitsune,silentbob73/kitsune,turtleloveshoes/kitsune,dbbhattacharya/kitsune,turtleloveshoes/kitsune,feer56/Kitsune1,brittanystoroz/kitsune,Osmose/kitsune,rlr/kitsune,MikkCZ/kitsune,MikkCZ/kitsune,Osmose/kitsune,mozilla/kitsune,NewPresident1/kitsune,asdofindia/kitsune,MziRintu/kitsune,mythmon/kitsune,dbbhattacharya/kitsune,rlr/kitsune,silentbob73/kitsune,brittanystoroz/kitsune,anushbmx/kitsune,YOTOV-LIMITED/kitsune,H1ghT0p/kitsune,H1ghT0p/kitsune,brittanystoroz/kitsune,mythmon/kitsune,feer56/Kitsune2 | ---
+++
@@ -12,8 +12,11 @@
to_move = list(Document.objects.filter(slug__startswith='forum-response-',
locale=settings.WIKI_DEFAULT_LANGUAGE))
-to_move.append(Document.objects.get(slug='common-forum-responses',
- locale=settings.WIKI_DEFAULT_LANGUAGE))
+try:
+ to_move.append(Document.objects.get(slug='common-forum-responses',
+ locale=settings.WIKI_DEFAULT_LANGUAGE))
+except Document.DoesNotExist:
+ pass
print 'Recategorizing %d common response articles.' % len(to_move)
|
633e73238a4a5380f81dd142024efab5ae691f92 | frigg/settings/rest_framework.py | frigg/settings/rest_framework.py | REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '50/day',
}
}
| REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5000/day',
}
}
| Raise throttle limit for anon users | Raise throttle limit for anon users
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq | ---
+++
@@ -3,6 +3,6 @@
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
- 'anon': '50/day',
+ 'anon': '5000/day',
}
} |
ff3e0eb9d38d2cbed1fab7b67a374915bf65b8f5 | engine/logger.py | engine/logger.py | #
# dp for Tornado
# YoungYong Park (youngyongpark@gmail.com)
# 2014.10.23
#
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
def exception(self, e=None):
pass | #
# dp for Tornado
# YoungYong Park (youngyongpark@gmail.com)
# 2014.10.23
#
import logging
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
def exception(self, msg, *args, **kwargs):
logging.exception(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
logging.error(msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
logging.info(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
logging.warning(msg, *args, **kwargs)
def debug(self, msg, *args, **kwargs):
logging.debug(msg, *args, **kwargs) | Add logging helper. (exception, error, warning, info, debug) | Add logging helper. (exception, error, warning, info, debug)
| Python | mit | why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado | ---
+++
@@ -4,9 +4,24 @@
# 2014.10.23
#
+
+import logging
+
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
- def exception(self, e=None):
- pass
+ def exception(self, msg, *args, **kwargs):
+ logging.exception(msg, *args, **kwargs)
+
+ def error(self, msg, *args, **kwargs):
+ logging.error(msg, *args, **kwargs)
+
+ def info(self, msg, *args, **kwargs):
+ logging.info(msg, *args, **kwargs)
+
+ def warning(self, msg, *args, **kwargs):
+ logging.warning(msg, *args, **kwargs)
+
+ def debug(self, msg, *args, **kwargs):
+ logging.debug(msg, *args, **kwargs) |
a673bc6b3b9daf27404e4d330819bebc25a73608 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| import os
import testinfra.utils.ansible_runner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_basic_login(host):
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
driver.get(url + "/gettingstarted")
element = wait.until(EC.title_is(('Graylog - Sign in')))
#login
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
element = wait.until(EC.title_is(('Graylog - Getting started')))
driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal':
mongodb_service_name = 'mongodb'
else:
mongodb_service_name = 'mongod'
assert host.service(mongodb_service_name).is_running is True
def test_is_graylog_installed(host):
assert host.package('graylog-server').is_installed
def test_service_graylog_running(host):
assert host.service("graylog-server").is_running is True
| Add Selenium test for basic logic. | Add Selenium test for basic logic.
| Python | apache-2.0 | Graylog2/graylog-ansible-role | ---
+++
@@ -1,8 +1,36 @@
import os
import testinfra.utils.ansible_runner
+from selenium import webdriver
+from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
+
+def test_basic_login(host):
+ driver = webdriver.Chrome()
+ wait = WebDriverWait(driver, 10)
+
+ url = 'http://' + host.interface('eth0').addresses[0] + ':9000'
+
+ driver.get(url + "/gettingstarted")
+
+ element = wait.until(EC.title_is(('Graylog - Sign in')))
+
+ #login
+ uid_field = driver.find_element_by_name("username")
+ uid_field.clear()
+ uid_field.send_keys("admin")
+ password_field = driver.find_element_by_name("password")
+ password_field.clear()
+ password_field.send_keys("admin")
+ password_field.send_keys(Keys.RETURN)
+
+ element = wait.until(EC.title_is(('Graylog - Getting started')))
+
+ driver.close()
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True |
8b78f3e84c688b0e45ecfa0dda827870eced4c4e | sdi/corestick.py | sdi/corestick.py | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ignore the
width fields in the file.
"""
cores = {}
with open(filename) as f:
units = f.readline().strip('\r\n').lower()
if units not in ['feet', 'meters', 'meter']:
raise NotImplementedError('Only units of FEET and METERS/METER are supported ')
conv_factor = 1.0
if units == 'feet':
conv_factor = 0.3048
f.readline()
for line in f.readlines():
fields = line.split()
core_id = fields[2]
data = {}
data['easting'] = float(fields[0])
data['northing'] = float(fields[1])
data['layer_interface_depths'] = [
float(fields[i]) * conv_factor
for i in range(5, len(fields), 4)
]
data['layer_colors'] = [i for i in range(6, len(fields), 4)]
cores[core_id] = data
return cores
| def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ignore the
width fields in the file.
"""
cores = {}
with open(filename) as f:
units = f.readline().strip('\r\n').lower()
if units not in ['feet', 'meters', 'meter']:
raise NotImplementedError('Only units of FEET and METERS/METER are supported ')
conv_factor = 1.0
if units == 'feet':
conv_factor = 0.3048
f.readline()
for line in f.readlines():
fields = line.split()
core_id = fields[2]
data = {}
data['easting'] = float(fields[0])
data['northing'] = float(fields[1])
data['layer_interface_depths'] = [
float(fields[i]) * conv_factor
for i in range(5, len(fields), 4)
]
data['layer_colors'] = [
int(fields[i]) for i in range(6, len(fields), 4)]
cores[core_id] = data
return cores
| Fix reading in for layer_colors. | Fix reading in for layer_colors.
| Python | bsd-3-clause | twdb/sdi | ---
+++
@@ -30,7 +30,8 @@
float(fields[i]) * conv_factor
for i in range(5, len(fields), 4)
]
- data['layer_colors'] = [i for i in range(6, len(fields), 4)]
+ data['layer_colors'] = [
+ int(fields[i]) for i in range(6, len(fields), 4)]
cores[core_id] = data
return cores |
c82efa3d0db2f3f9887f4639552e761802829be6 | pgcli/pgstyle.py | pgcli/pgstyle.py | from pygments.token import Token
from pygments.style import Style
import pygments.styles
def style_factory(name):
class PGStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar.Status: 'bg:#222222 #aaaaaa',
Token.Toolbar.Status.Off: 'bg:#222222 #888888',
Token.Toolbar.Status.On: 'bg:#222222 #ffffff',
}
style = pygments.styles.get_style_by_name(name)
styles.update(style.styles)
return PGStyle
| from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar.Status: 'bg:#222222 #aaaaaa',
Token.Toolbar.Status.Off: 'bg:#222222 #888888',
Token.Toolbar.Status.On: 'bg:#222222 #ffffff',
}
styles.update(style.styles)
return PGStyle
| Add safety check for non-existent style. | Add safety check for non-existent style.
| Python | bsd-3-clause | j-bennet/pgcli,suzukaze/pgcli,dbcli/pgcli,darikg/pgcli,johshoff/pgcli,thedrow/pgcli,thedrow/pgcli,janusnic/pgcli,darikg/pgcli,j-bennet/pgcli,yx91490/pgcli,koljonen/pgcli,yx91490/pgcli,lk1ngaa7/pgcli,d33tah/pgcli,lk1ngaa7/pgcli,bitemyapp/pgcli,bitemyapp/pgcli,joewalnes/pgcli,d33tah/pgcli,w4ngyi/pgcli,dbcli/vcli,koljonen/pgcli,nosun/pgcli,joewalnes/pgcli,n-someya/pgcli,suzukaze/pgcli,zhiyuanshi/pgcli,TamasNo1/pgcli,bitmonk/pgcli,janusnic/pgcli,johshoff/pgcli,nosun/pgcli,TamasNo1/pgcli,MattOates/pgcli,dbcli/pgcli,dbcli/vcli,MattOates/pgcli,zhiyuanshi/pgcli,w4ngyi/pgcli,bitmonk/pgcli,n-someya/pgcli | ---
+++
@@ -1,9 +1,15 @@
from pygments.token import Token
from pygments.style import Style
+from pygments.util import ClassNotFound
import pygments.styles
def style_factory(name):
+ try:
+ style = pygments.styles.get_style_by_name(name)
+ except ClassNotFound:
+ style = pygments.styles.get_style_by_name('native')
+
class PGStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
@@ -18,7 +24,6 @@
Token.Toolbar.Status.Off: 'bg:#222222 #888888',
Token.Toolbar.Status.On: 'bg:#222222 #ffffff',
}
- style = pygments.styles.get_style_by_name(name)
styles.update(style.styles)
return PGStyle |
200027f73a99f18eeeae4395be9622c65590916f | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))]
# Junkbot
class GVG_106:
events = [
Death(FRIENDLY + MECH).on(Buff(SELF, "GVG_106e"))
]
# Enhance-o Mechano
class GVG_107:
def action(self):
for target in self.controller.field:
tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD))
yield SetTag(target, {tag: True})
# Recombobulator
class GVG_108:
def action(self, target):
choice = randomCollectible(type=CardType.MINION, cost=target.cost)
return [Morph(TARGET, choice)]
# Clockwork Giant
class GVG_121:
def cost(self, value):
return value - len(self.controller.opponent.hand)
| from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))]
# Junkbot
class GVG_106:
events = [
Death(FRIENDLY + MECH).on(Buff(SELF, "GVG_106e"))
]
# Enhance-o Mechano
class GVG_107:
def action(self):
for target in self.controller.field.exclude(self):
tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD))
yield SetTag(target, {tag: True})
# Recombobulator
class GVG_108:
def action(self, target):
choice = randomCollectible(type=CardType.MINION, cost=target.cost)
return [Morph(TARGET, choice)]
# Clockwork Giant
class GVG_121:
def cost(self, value):
return value - len(self.controller.opponent.hand)
| Exclude Enhance-o Mechano from its own buff targets | Exclude Enhance-o Mechano from its own buff targets
| Python | agpl-3.0 | oftc-ftw/fireplace,smallnamespace/fireplace,butozerca/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,Meerkov/fireplace,NightKev/fireplace,butozerca/fireplace,amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fireplace | ---
+++
@@ -29,7 +29,7 @@
# Enhance-o Mechano
class GVG_107:
def action(self):
- for target in self.controller.field:
+ for target in self.controller.field.exclude(self):
tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD))
yield SetTag(target, {tag: True})
|
631a096eb8b369258c85b5c014460166787abf6c | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi')
for each in all_variables:
if each.unit:
if ' per ' in each.unit:
short_form = each.unit.split(' per ')[0]
if any(w in short_form for w in common_short_units):
for x in common_short_units:
if x in short_form:
each.short_unit = x
each.save()
break
else:
each.short_unit = short_form
each.save()
elif any(x in each.unit for x in common_short_units):
for y in common_short_units:
if y in each.unit:
each.short_unit = y
each.save()
break
elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares'
each.short_unit = each.unit
each.save()
| import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi')
for each in all_variables:
if each.unit and not each.short_unit:
if ' per ' in each.unit:
short_form = each.unit.split(' per ')[0]
if any(w in short_form for w in common_short_units):
for x in common_short_units:
if x in short_form:
each.short_unit = x
each.save()
break
else:
each.short_unit = short_form
each.save()
elif any(x in each.unit for x in common_short_units):
for y in common_short_units:
if y in each.unit:
each.short_unit = y
each.save()
break
elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares'
each.short_unit = each.unit
each.save()
| Make short unit extraction script idempotent | Make short unit extraction script idempotent
| Python | mit | OurWorldInData/owid-grapher,owid/owid-grapher,aaldaber/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,aaldaber/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,OurWorldInData/our-world-in-data-grapher | ---
+++
@@ -11,7 +11,7 @@
all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi')
for each in all_variables:
- if each.unit:
+ if each.unit and not each.short_unit:
if ' per ' in each.unit:
short_form = each.unit.split(' per ')[0]
if any(w in short_form for w in common_short_units): |
4335d5430fbcae6035f90495f1ce43d351e3927a | djangopypi/urls.py | djangopypi/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("",
# Simple PyPI
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
url(r'^(?P<dist_name>[\w\d_\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",
name="djangopypi-show_version"),
url(r'^(?P<dist_name>[\w\d_\-]+)/?', "djangopypi.views.show_links",
name="djangopypi-show_links"),
)
| # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("",
# Simple PyPI
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",
name="djangopypi-show_version"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/?', "djangopypi.views.show_links",
name="djangopypi-show_links"),
)
| Allow "." in project names. | Allow "." in project names.
| Python | bsd-3-clause | hsmade/djangopypi2,pitrho/djangopypi2,pitrho/djangopypi2,popen2/djangopypi2,mattcaldwell/djangopypi,hsmade/djangopypi2,disqus/djangopypi,EightMedia/djangopypi,EightMedia/djangopypi,ask/chishop,popen2/djangopypi2,disqus/djangopypi,benliles/djangopypi | ---
+++
@@ -6,11 +6,11 @@
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
- url(r'^(?P<dist_name>[\w\d_\-]+)/(?P<version>[\w\.\d\-_]+)/?',
+ url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",
name="djangopypi-show_version"),
- url(r'^(?P<dist_name>[\w\d_\-]+)/?', "djangopypi.views.show_links",
+ url(r'^(?P<dist_name>[\w\d_\.\-]+)/?', "djangopypi.views.show_links",
name="djangopypi-show_links"),
)
|
d8347132e246caf4874384000014353ce200dff4 | launcher/launcher/ui/__init__.py | launcher/launcher/ui/__init__.py | CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "synapse.isrd.isi.edu",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| Set prod server as config default. | Set prod server as config default.
| Python | bsd-3-clause | informatics-isi-edu/synspy,informatics-isi-edu/synspy,informatics-isi-edu/synspy | ---
+++
@@ -3,7 +3,7 @@
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
- "host": "",
+ "host": "synapse.isrd.isi.edu",
"catalog_id": 1
},
"viewer_mode": "2d", |
8b88ca952ff562eb692f25cba54263afcbbcfafd | auth/models.py | auth/models.py | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def set_password(self, password):
self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt(log_rounds=1))
def check_password(self, password):
return bcrypt.hashpw(password, self.password_hash) == self.password_hash
@classmethod
def authenticate(cls, email, password):
user = cls.all().filter('email =', email).get()
if user is None:
return None
if user.check_password(password):
return user
return None
| from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def __init__(self, *args, **kwds):
db.Model.__init__(self, *args, **kwds)
password = kwds.pop('password', None)
if password:
self.set_password(password)
def set_password(self, password):
self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt(log_rounds=1))
def check_password(self, password):
return bcrypt.hashpw(password, self.password_hash) == self.password_hash
@classmethod
def authenticate(cls, email, password):
user = cls.all().filter('email =', email).get()
if user is None:
return None
if user.check_password(password):
return user
return None
| Set password in user ini | Set password in user ini
| Python | mit | haldun/optimyser2,haldun/optimyser2,haldun/tornado-gae-auth | ---
+++
@@ -9,6 +9,12 @@
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
+
+ def __init__(self, *args, **kwds):
+ db.Model.__init__(self, *args, **kwds)
+ password = kwds.pop('password', None)
+ if password:
+ self.set_password(password)
def set_password(self, password):
self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt(log_rounds=1)) |
7a448c4df3feb717d0b1d8abbf9d32237751aab5 | nbgrader/tests/apps/test_nbgrader_extension.py | nbgrader/tests/apps/test_nbgrader_extension.py | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 3
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 2
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
| import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment'
| Fix tests for nbgrader extensions | Fix tests for nbgrader extensions
| Python | bsd-3-clause | jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader | ---
+++
@@ -6,10 +6,11 @@
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
- assert len(nbexts) == 3
+ assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
+ assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
@@ -18,6 +19,7 @@
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
- assert len(serverexts) == 2
+ assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
+ assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment' |
e385a20fdb877f0c6308883709814920cf0378d7 | behave/__main__.py | behave/__main__.py | #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
if __name__ == "__main__":
from .main import main
sys.exit(main())
| #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
from .main import main
if __name__ == "__main__":
sys.exit(main())
| Tweak for better backward compatibility w/ master repository. | Tweak for better backward compatibility w/ master repository.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave | ---
+++
@@ -8,7 +8,7 @@
from __future__ import absolute_import
import sys
+from .main import main
if __name__ == "__main__":
- from .main import main
sys.exit(main()) |
ababeb31c0673c44b0c0e6d0b30bf369d67b9e55 | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
def rpp_initialisation():
a = Rpp(max_duration=100)
| import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
pow_ride_1 = np.linspace(100, 200, 4000)
pow_ride_2 = np.linspace(50, 400, 4000)
def test_fitting_rpp():
""" Test the computation of the fitting """
my_rpp = Rpp(max_duration_rpp=10)
my_rpp.fit(pow_ride_1)
# We need to make an assert equal here with meaningful data
print my_rpp.rpp_
def test_partial_fitting_rpp():
""" Test the partial fitting with update of the rpp """
my_rpp = Rpp(max_duration_rpp=10)
my_rpp.fit(pow_ride_1)
my_rpp.partial_fit(pow_ride_2)
# We need to make an assert equal here with meaningful data
print my_rpp.rpp_
def test_partial_fitting_rpp_refit():
""" Test the partial fitting with update of the rpp """
my_rpp = Rpp(max_duration_rpp=10)
my_rpp.fit(pow_ride_1)
my_rpp.partial_fit(pow_ride_2)
my_rpp.partial_fit(pow_ride_1, refit=True)
# We need to make an assert equal here with meaningful data
print my_rpp.rpp_
| Bring some test which need to be finished | Bring some test which need to be finished
| Python | mit | glemaitre/power-profile,clemaitre58/power-profile,glemaitre/power-profile,clemaitre58/power-profile | ---
+++
@@ -8,5 +8,34 @@
from skcycling.power_profile import Rpp
-def rpp_initialisation():
- a = Rpp(max_duration=100)
+pow_ride_1 = np.linspace(100, 200, 4000)
+pow_ride_2 = np.linspace(50, 400, 4000)
+
+def test_fitting_rpp():
+ """ Test the computation of the fitting """
+ my_rpp = Rpp(max_duration_rpp=10)
+ my_rpp.fit(pow_ride_1)
+
+ # We need to make an assert equal here with meaningful data
+ print my_rpp.rpp_
+
+
+def test_partial_fitting_rpp():
+ """ Test the partial fitting with update of the rpp """
+ my_rpp = Rpp(max_duration_rpp=10)
+ my_rpp.fit(pow_ride_1)
+ my_rpp.partial_fit(pow_ride_2)
+
+ # We need to make an assert equal here with meaningful data
+ print my_rpp.rpp_
+
+
+def test_partial_fitting_rpp_refit():
+ """ Test the partial fitting with update of the rpp """
+ my_rpp = Rpp(max_duration_rpp=10)
+ my_rpp.fit(pow_ride_1)
+ my_rpp.partial_fit(pow_ride_2)
+ my_rpp.partial_fit(pow_ride_1, refit=True)
+
+ # We need to make an assert equal here with meaningful data
+ print my_rpp.rpp_ |
67b80161fd686ef0743470dd57e56b64fe9f9128 | rnn_padding.py | rnn_padding.py | import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=None):
"""Pad Python List of unpadded tensors. If length is
not specified padding till sentence of max length."""
if length is None:
length = max(s.size(0) for s in sequence_list)
padded_list = [pad_single_sequence(s, length) for s in sequence_list]
return torch.cat(padded_list, dim=1)
| import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=None):
"""Pad Python List of unpadded tensors. If length is
not specified padding till sentence of max length."""
if length is None:
length = max(s.size(0) for s in sequence_list)
padded_list = [pad_single_sequence(s, length) for s in
sorted(sequence_list, key=lambda tensor: tensor.size(0), reverse=True)]
return torch.cat(padded_list, dim=1)
| Return Vector is in decreasing order of origal length. | Return Vector is in decreasing order of origal length.
| Python | mit | reachtarunhere/pytorch-snippets | ---
+++
@@ -13,5 +13,6 @@
not specified padding till sentence of max length."""
if length is None:
length = max(s.size(0) for s in sequence_list)
- padded_list = [pad_single_sequence(s, length) for s in sequence_list]
+ padded_list = [pad_single_sequence(s, length) for s in
+ sorted(sequence_list, key=lambda tensor: tensor.size(0), reverse=True)]
return torch.cat(padded_list, dim=1) |
8f2b9eecc5c62be356225250783731c21a22abea | django_pickling.py | django_pickling.py | VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls] = [f.attname for f in cls._meta.fields]
return _cache[cls]
def model_unpickle(cls, vector, db, adding):
obj = cls.__new__(cls)
obj.__dict__.update(izip(attnames(cls), vector))
# Restore state. This is the fastest way to create object I know.
obj._state = ModelState.__new__(ModelState)
obj._state.__dict__ = {'db': db, 'adding': adding}
return obj
model_unpickle.__safe_for_unpickle__ = True
def Model__reduce__(self):
cls = self.__class__
data = self.__dict__.copy()
state = data.pop('_state')
try:
vector = tuple(data.pop(name) for name in attnames(cls))
return (model_unpickle, (cls, vector, state.db, state.adding), data)
except KeyError:
# data.pop() raises when some attnames are deferred
return original_Model__reduce__(self)
if Model.__reduce__ != Model__reduce__:
original_Model__reduce__ = Model.__reduce__
Model.__reduce__ = Model__reduce__
del Model.__setstate__ # Drop django version check
| VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls] = tuple(f.attname for f in cls._meta.fields)
return _cache[cls]
def model_unpickle(cls, vector, db, adding):
obj = cls.__new__(cls)
obj.__dict__.update(izip(attnames(cls), vector))
# Restore state. This is the fastest way to create object I know.
obj._state = ModelState.__new__(ModelState)
obj._state.__dict__ = {'db': db, 'adding': adding}
return obj
model_unpickle.__safe_for_unpickle__ = True
def Model__reduce__(self):
cls = self.__class__
data = self.__dict__.copy()
state = data.pop('_state')
try:
vector = tuple(data.pop(name) for name in attnames(cls))
return (model_unpickle, (cls, vector, state.db, state.adding), data)
except KeyError:
# data.pop() raises when some attnames are deferred
return original_Model__reduce__(self)
if Model.__reduce__ != Model__reduce__:
original_Model__reduce__ = Model.__reduce__
Model.__reduce__ = Model__reduce__
del Model.__setstate__ # Drop django version check
| Use tuples of attnames instead of lists | Use tuples of attnames instead of lists
| Python | bsd-3-clause | Suor/django-pickling | ---
+++
@@ -14,7 +14,7 @@
try:
return _cache[cls]
except KeyError:
- _cache[cls] = [f.attname for f in cls._meta.fields]
+ _cache[cls] = tuple(f.attname for f in cls._meta.fields)
return _cache[cls]
|
8acb681ff8963621452f0e018781c76d4935cb84 | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
)
| Add url for project_status_edit option | Add url for project_status_edit option
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -4,6 +4,7 @@
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
+ url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'), |
ef974d5b01940efa3886a4074eda964bfc07b133 | bookie/__init__.py | bookie/__init__.py | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.auth import UserMgr
from bookie.routes import build_routes
from pyramid.security import Allow
from pyramid.security import Everyone
from pyramid.security import ALL_PERMISSIONS
class RootFactory(object):
__acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)]
def __init__(self, request):
self.__dict__.update(request.matchdict)
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
initialize_sql(engine)
authn_policy = AuthTktAuthenticationPolicy(settings.get('auth.secret'),
callback=UserMgr.auth_groupfinder)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(settings=settings,
root_factory='bookie.RootFactory',
authentication_policy=authn_policy,
authorization_policy=authz_policy)
config.set_request_factory(RequestWithUserAttribute)
config = build_routes(config)
config.add_static_view('static', 'bookie:static')
config.scan('bookie.views')
return config.make_wsgi_app()
| from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.auth import UserMgr
from bookie.routes import build_routes
from pyramid.security import Allow
from pyramid.security import Everyone
from pyramid.security import ALL_PERMISSIONS
class RootFactory(object):
__acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)]
def __init__(self, request):
if request.matchdict:
self.__dict__.update(request.matchdict)
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
initialize_sql(engine)
authn_policy = AuthTktAuthenticationPolicy(settings.get('auth.secret'),
callback=UserMgr.auth_groupfinder)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(settings=settings,
root_factory='bookie.RootFactory',
authentication_policy=authn_policy,
authorization_policy=authz_policy)
config.set_request_factory(RequestWithUserAttribute)
config = build_routes(config)
config.add_static_view('static', 'bookie:static')
config.scan('bookie.views')
return config.make_wsgi_app()
| Fix the rootfactory for no matchdict so we can get a 404 back out | Fix the rootfactory for no matchdict so we can get a 404 back out
| Python | agpl-3.0 | pombredanne/Bookie,skmezanul/Bookie,teodesson/Bookie,GreenLunar/Bookie,wangjun/Bookie,bookieio/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,charany1/Bookie,bookieio/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,adamlincoln/Bookie,charany1/Bookie,charany1/Bookie,teodesson/Bookie,wangjun/Bookie,GreenLunar/Bookie,pombredanne/Bookie,teodesson/Bookie,wangjun/Bookie,teodesson/Bookie,bookieio/Bookie,skmezanul/Bookie,GreenLunar/Bookie,wangjun/Bookie,skmezanul/Bookie | ---
+++
@@ -17,7 +17,8 @@
__acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)]
def __init__(self, request):
- self.__dict__.update(request.matchdict)
+ if request.matchdict:
+ self.__dict__.update(request.matchdict)
def main(global_config, **settings): |
ffbe699a8435dd0abfb43a37c8528257cdaf386d | pymogilefs/request.py | pymogilefs/request.py | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8')
| try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8')
# Python 2.7 compatibility
def __str__(self):
return self.__bytes__().decode()
| Add __str__/__bytes__ Python 2.7 compatibility | Add __str__/__bytes__ Python 2.7 compatibility
| Python | mit | bwind/pymogilefs,bwind/pymogilefs | ---
+++
@@ -12,3 +12,7 @@
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8')
+
+ # Python 2.7 compatibility
+ def __str__(self):
+ return self.__bytes__().decode() |
8b3e40e70101433157709d9d774b199ce606196f | violations/tests/test_base.py | violations/tests/test_base.py | from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test register"""
@self.library.register('dummy')
def violation():
pass
self.assertEqual(self.library.get('dummy'), violation)
def test_not_found(self):
"""Test violation not found"""
with self.assertRaises(ViolationDoesNotExists):
self.library.get('dummy!!!')
def test_has(self):
"""Test has method"""
@self.library.register('dummy')
def violation():
pass
self.assertTrue(self.library.has('dummy'))
self.assertFalse(self.library.has('dummy!!!'))
| import sure
from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test register"""
@self.library.register('dummy')
def violation():
pass
self.library.get('dummy').should.be.equal(violation)
def test_not_found(self):
"""Test violation not found"""
self.library.get.when.called_with('dummy!!!')\
.should.throw(ViolationDoesNotExists)
def test_has(self):
"""Test has method"""
@self.library.register('dummy')
def violation():
pass
self.library.has('dummy').should.be.true
self.library.has('dummy!!!').should.be.false
| Use sure in violations bases tests | Use sure in violations bases tests
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -1,3 +1,4 @@
+import sure
from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
@@ -15,12 +16,12 @@
def violation():
pass
- self.assertEqual(self.library.get('dummy'), violation)
+ self.library.get('dummy').should.be.equal(violation)
def test_not_found(self):
"""Test violation not found"""
- with self.assertRaises(ViolationDoesNotExists):
- self.library.get('dummy!!!')
+ self.library.get.when.called_with('dummy!!!')\
+ .should.throw(ViolationDoesNotExists)
def test_has(self):
"""Test has method"""
@@ -28,5 +29,5 @@
def violation():
pass
- self.assertTrue(self.library.has('dummy'))
- self.assertFalse(self.library.has('dummy!!!'))
+ self.library.has('dummy').should.be.true
+ self.library.has('dummy!!!').should.be.false |
516bebe37212e72362b416bd1d9c87a83726fa5f | changes/api/cluster_nodes.py | changes/api/cluster_nodes.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', type=int, location='args')
def get(self, cluster_id):
cluster = Cluster.query.get(cluster_id)
if cluster is None:
return '', 404
queryset = Node.query.filter(
Node.clusters.contains(cluster),
)
args = self.parser.parse_args()
if args.since:
cutoff = datetime.utcnow() - timedelta(days=args.since)
queryset = queryset.join(
JobStep, JobStep.node_id == Node.id,
).filter(
JobStep.date_created > cutoff,
).group_by(Node)
return self.paginate(queryset)
| from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', type=int, location='args')
def get(self, cluster_id):
cluster = Cluster.query.get(cluster_id)
if cluster is None:
return '', 404
queryset = Node.query.filter(
Node.clusters.contains(cluster),
).order_by(Node.label.asc())
args = self.parser.parse_args()
if args.since:
cutoff = datetime.utcnow() - timedelta(days=args.since)
queryset = queryset.join(
JobStep, JobStep.node_id == Node.id,
).filter(
JobStep.date_created > cutoff,
).group_by(Node)
return self.paginate(queryset)
| Enforce ordering on cluster nodes endpoint | Enforce ordering on cluster nodes endpoint
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -18,7 +18,7 @@
queryset = Node.query.filter(
Node.clusters.contains(cluster),
- )
+ ).order_by(Node.label.asc())
args = self.parser.parse_args()
if args.since: |
fe8266beb5541f1ac5b08f365edb5f30b3e8eddd | snakeeyes/blueprints/contact/tasks.py | snakeeyes/blueprints/contact/tasks.py | from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail message
:type user_id: str
:return: None
"""
ctx = {'email': email, 'message': message}
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
recipients=[celery.conf.get('MAIL_USERNAME')],
reply_to=email,
template='contact/mail/index', ctx=ctx)
return None
| from flask import current_app
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail message
:type user_id: str
:return: None
"""
ctx = {'email': email, 'message': message}
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
recipients=[current_app.config['MAIL_USERNAME']],
reply_to=email,
template='contact/mail/index', ctx=ctx)
return None
| Fix contact form recipient email address | Fix contact form recipient email address
Since Celery is configured differently now we can't reach in and
grab config values outside of Celery.
| Python | mit | nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask | ---
+++
@@ -1,3 +1,5 @@
+from flask import current_app
+
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
@@ -19,7 +21,7 @@
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
- recipients=[celery.conf.get('MAIL_USERNAME')],
+ recipients=[current_app.config['MAIL_USERNAME']],
reply_to=email,
template='contact/mail/index', ctx=ctx)
|
4b451721c9e3530d83cf4ada1c1a7c994c217f15 | cloudbio/edition/__init__.py | cloudbio/edition/__init__.py | """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition
from cloudbio.edition.minimal import Minimal
from cloudbio.edition.bionode import BioNode
_edition_map = {None: Edition,
"minimal": Minimal,
"bionode": BioNode}
def _setup_edition(env):
"""Setup one of the BioLinux editions (which are derived from
the Edition base class)
"""
# fetch Edition from environment and load relevant class. Use
# an existing edition, if possible, and override behaviour through
# the Flavor mechanism.
edition_class = _edition_map[env.get("edition", None)]
env.edition = edition_class(env)
env.logger.debug("%s %s" % (env.edition.name, env.edition.version))
env.logger.info("This is a %s" % env.edition.short_name)
| """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition, Minimal, BioNode
_edition_map = {None: Edition,
"minimal": Minimal,
"bionode": BioNode}
def _setup_edition(env):
"""Setup one of the BioLinux editions (which are derived from
the Edition base class)
"""
# fetch Edition from environment and load relevant class. Use
# an existing edition, if possible, and override behaviour through
# the Flavor mechanism.
edition_class = _edition_map[env.get("edition", None)]
env.edition = edition_class(env)
env.logger.debug("%s %s" % (env.edition.name, env.edition.version))
env.logger.info("This is a %s" % env.edition.short_name)
| Correct imports for new directory structure | Correct imports for new directory structure
| Python | mit | elkingtonmcb/cloudbiolinux,averagehat/cloudbiolinux,rchekaluk/cloudbiolinux,rchekaluk/cloudbiolinux,heuermh/cloudbiolinux,lpantano/cloudbiolinux,chapmanb/cloudbiolinux,averagehat/cloudbiolinux,AICIDNN/cloudbiolinux,elkingtonmcb/cloudbiolinux,AICIDNN/cloudbiolinux,kdaily/cloudbiolinux,averagehat/cloudbiolinux,elkingtonmcb/cloudbiolinux,heuermh/cloudbiolinux,heuermh/cloudbiolinux,lpantano/cloudbiolinux,joemphilips/cloudbiolinux,pjotrp/cloudbiolinux,AICIDNN/cloudbiolinux,heuermh/cloudbiolinux,elkingtonmcb/cloudbiolinux,joemphilips/cloudbiolinux,averagehat/cloudbiolinux,AICIDNN/cloudbiolinux,rchekaluk/cloudbiolinux,pjotrp/cloudbiolinux,kdaily/cloudbiolinux,pjotrp/cloudbiolinux,pjotrp/cloudbiolinux,chapmanb/cloudbiolinux,kdaily/cloudbiolinux,rchekaluk/cloudbiolinux,kdaily/cloudbiolinux,chapmanb/cloudbiolinux,chapmanb/cloudbiolinux,joemphilips/cloudbiolinux,joemphilips/cloudbiolinux,lpantano/cloudbiolinux | ---
+++
@@ -6,9 +6,7 @@
Other editions can be found in this directory
"""
-from cloudbio.edition.base import Edition
-from cloudbio.edition.minimal import Minimal
-from cloudbio.edition.bionode import BioNode
+from cloudbio.edition.base import Edition, Minimal, BioNode
_edition_map = {None: Edition,
"minimal": Minimal, |
d3f181f3151e158c569cc53f4287d3c4d7ca426e | proppy/main.py | proppy/main.py | import sys
import pytoml as toml
from proppy.exceptions import InvalidCommand, InvalidConfiguration
from proppy.proposal import Proposal
from proppy.render import to_pdf
def main(filename):
if not filename.endswith('.toml'):
raise InvalidCommand("You must use a TOML file as input")
with open(filename, 'rb') as f:
print("Parsing %s" % filename)
config = toml.load(f)
theme = config.get('theme')
if not theme:
raise InvalidConfiguration("Missing theme in TOML file")
if not config.get('customer'):
raise InvalidConfiguration("Missing customer in TOML file")
if not config.get('project'):
raise InvalidConfiguration("Missing customer in TOML file")
proposal = Proposal(config)
if proposal.is_valid():
print("Valid proposal, saving it.")
to_pdf(theme, proposal)
print("Proposal rendered and saved.")
else:
# show errors and do nothing
proposal.print_errors()
def run_main():
if len(sys.argv) != 2:
raise InvalidCommand("Invalid number of arguments")
main(sys.argv[1])
if __name__ == '__main__':
run_main()
| import sys
import pytoml as toml
from proppy.exceptions import InvalidCommand, InvalidConfiguration
from proppy.proposal import Proposal
from proppy.render import to_pdf
def main(filename):
if not filename.endswith('.toml'):
raise InvalidCommand("You must use a TOML file as input")
with open(filename, 'rb') as f:
print("Parsing %s" % filename)
config = toml.load(f)
theme = config.get('theme')
if not theme:
raise InvalidConfiguration("Missing theme in TOML file")
if not config.get('customer'):
raise InvalidConfiguration("Missing customer in TOML file")
if not config.get('project'):
raise InvalidConfiguration("Missing project in TOML file")
proposal = Proposal(config)
if proposal.is_valid():
print("Valid proposal, saving it.")
to_pdf(theme, proposal)
print("Proposal rendered and saved.")
else:
# show errors and do nothing
proposal.print_errors()
def run_main():
if len(sys.argv) != 2:
raise InvalidCommand("Invalid number of arguments")
main(sys.argv[1])
if __name__ == '__main__':
run_main()
| Fix exception string for missing project | Fix exception string for missing project
| Python | mit | WeAreWizards/proppy,WeAreWizards/proppy | ---
+++
@@ -21,7 +21,7 @@
raise InvalidConfiguration("Missing customer in TOML file")
if not config.get('project'):
- raise InvalidConfiguration("Missing customer in TOML file")
+ raise InvalidConfiguration("Missing project in TOML file")
proposal = Proposal(config)
|
6e6f906b47c1750f14e02b65cd825fd246a84c63 | tests/__init__.py | tests/__init__.py | import locale
# The test fixtures can break if the locale is non-US.
locale.setlocale(locale.LC_ALL, 'en_US')
| import locale
# The test fixtures can break if the locale is non-US.
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
| Set the locale to en_US.UTF-8 | test: Set the locale to en_US.UTF-8
| Python | mit | onyxfish/journalism,onyxfish/agate,wireservice/agate | ---
+++
@@ -1,4 +1,4 @@
import locale
# The test fixtures can break if the locale is non-US.
-locale.setlocale(locale.LC_ALL, 'en_US')
+locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') |
002be05d8bb07e610613b1ba6f24c904691c9f03 | tests/conftest.py | tests/conftest.py | """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCredentials(
database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'],
access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'],
secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
) # type: VuforiaServerCredentials
return credentials
| """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCredentials(
database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'],
access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'],
secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
) # type: VuforiaServerCredentials
return credentials
@pytest.fixture()
def vuforia_inactive_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials for an inactive project from environment variables.
"""
credentials = VuforiaServerCredentials(
database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'],
access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'],
secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
) # type: VuforiaServerCredentials
return credentials
| Create credentials fixture for inactive project | Create credentials fixture for inactive project
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python | ---
+++
@@ -20,3 +20,16 @@
secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
) # type: VuforiaServerCredentials
return credentials
+
+
+@pytest.fixture()
+def vuforia_inactive_server_credentials() -> VuforiaServerCredentials:
+ """
+ Return VWS credentials for an inactive project from environment variables.
+ """
+ credentials = VuforiaServerCredentials(
+ database_name=os.environ['VUFORIA_TARGET_MANAGER_DATABASE_NAME'],
+ access_key=os.environ['VUFORIA_SERVER_ACCESS_KEY'],
+ secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
+ ) # type: VuforiaServerCredentials
+ return credentials |
ca0d9b40442f3ca9499f4b1630650c61700668ec | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
'You might be testing the wrong code '
'-- More: https://github.com/renanivo/pytest-testdox/issues/13',
UserWarning
)
| # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
'You might be testing the wrong code. '
'Uninstall pytest-testdox to be able to run all test cases '
'-- More: https://github.com/renanivo/pytest-testdox/issues/13',
UserWarning
)
| Add the action required to fix the issue to the warning | Add the action required to fix the issue to the warning
| Python | mit | renanivo/pytest-testdox | ---
+++
@@ -17,7 +17,8 @@
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
- 'You might be testing the wrong code '
+ 'You might be testing the wrong code. '
+ 'Uninstall pytest-testdox to be able to run all test cases '
'-- More: https://github.com/renanivo/pytest-testdox/issues/13',
UserWarning
) |
1d7e20e1dfb113839b4b213e49308c4b3f8f6605 | csunplugged/general/views.py | csunplugged/general/views.py | """Views for the general application."""
from django.views.generic import TemplateView
from django.http import HttpResponse
class GeneralIndexView(TemplateView):
"""View for the homepage that renders from a template."""
template_name = 'general/index.html'
class GeneralAboutView(TemplateView):
"""View for the about page that renders from a template."""
template_name = 'general/about.html'
class GeneralContactView(TemplateView):
"""View for the contact page that renders from a template"""
template_name = 'general/contact.html'
class GeneralPeopleView(TemplateView):
"""View for the people page that renders from a template."""
template_name = 'general/people.html'
class GeneralPrinciplesView(TemplateView):
"""View for the princples page that renders from a template."""
template_name = 'general/principles.html'
def health_check(request):
"""Return heath check response for Google App Engine.
Returns a 200 HTTP response for Google App Engine to detect the system
is running.
"""
return HttpResponse(status=200)
| """Views for the general application."""
from django.views.generic import TemplateView
from django.http import HttpResponse
class GeneralIndexView(TemplateView):
"""View for the homepage that renders from a template."""
template_name = 'general/index.html'
class GeneralAboutView(TemplateView):
"""View for the about page that renders from a template."""
template_name = 'general/about.html'
class GeneralContactView(TemplateView):
"""View for the contact page that renders from a template."""
template_name = 'general/contact.html'
class GeneralPeopleView(TemplateView):
"""View for the people page that renders from a template."""
template_name = 'general/people.html'
class GeneralPrinciplesView(TemplateView):
"""View for the princples page that renders from a template."""
template_name = 'general/principles.html'
def health_check(request):
"""Return heath check response for Google App Engine.
Returns a 200 HTTP response for Google App Engine to detect the system
is running.
"""
return HttpResponse(status=200)
| Reset file to pass style checks | Reset file to pass style checks
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -17,7 +17,7 @@
class GeneralContactView(TemplateView):
- """View for the contact page that renders from a template"""
+ """View for the contact page that renders from a template."""
template_name = 'general/contact.html'
|
687c0f3c1b8d1b5cd0cee6403a9664bb2b8f63d1 | cleverbot/utils.py | cleverbot/utils.py | def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
return property(getter, setter)
| def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
deleter = lambda self: delattr(self, _name)
return property(getter, setter, deleter)
| Add deleter to Conversation properties | Add deleter to Conversation properties
| Python | mit | orlnub123/cleverbot.py | ---
+++
@@ -8,4 +8,5 @@
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
- return property(getter, setter)
+ deleter = lambda self: delattr(self, _name)
+ return property(getter, setter, deleter) |
d2c50272ec4509e40562f441e534ba7457a493f3 | tests/test_api.py | tests/test_api.py | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.warns(UserWarning):
api.sort_file(tmp_file, atomic=True)
def test_check_file(tmpdir) -> None:
perfect = tmpdir.join(f"test_no_changes.py")
perfect.write_text("import a\nimport b\n", "utf8")
assert api.check_file(perfect, show_diff=True)
| """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.warns(UserWarning):
api.sort_file(tmp_file, atomic=True)
def test_check_file(tmpdir) -> None:
perfect = tmpdir.join(f"test_no_changes.py")
perfect.write_text("import a\nimport b\n", "utf8")
assert api.check_file(perfect, show_diff=True)
imperfect = tmpdir.join(f"test_needs_changes.py")
imperfect.write_text("import b\nimport a\n", "utf8")
assert not api.check_file(imperfect, show_diff=True)
| Add test for imperfect imports as well | Add test for imperfect imports as well
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -16,3 +16,7 @@
perfect = tmpdir.join(f"test_no_changes.py")
perfect.write_text("import a\nimport b\n", "utf8")
assert api.check_file(perfect, show_diff=True)
+
+ imperfect = tmpdir.join(f"test_needs_changes.py")
+ imperfect.write_text("import b\nimport a\n", "utf8")
+ assert not api.check_file(imperfect, show_diff=True) |
a8f125236308cbfc9bb2eb5b225a0ac92a3a95e4 | ANN.py | ANN.py | from random import random
class Neuron:
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def get_output(self):
return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
output = property(get_output)
class NeuronNetwork:
neurons = []
def __init__(self, inputs, outputs, rows, columns):
self.neurons = []
for row in xrange(rows + 2):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows + 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
else:
for column in xrange(columns):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
| from random import random
class Neuron:
output = None
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def calculate(self):
self.output = sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
class NeuronNetwork:
neurons = []
def __init__(self, inputs, outputs, rows, columns):
self.neurons = []
for row in xrange(rows + 2):
self.neurons.append([])
if row == 0:
for input_ in xrange(inputs):
self.neurons[row].append(Neuron(parents=[]))
elif row == rows + 1:
for output in xrange(outputs):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
else:
for column in xrange(columns):
self.neurons[row].append(Neuron(parents=self.neurons[row - 1]))
| Store output instead of calculating it each time | Store output instead of calculating it each time
| Python | mit | tysonzero/py-ann | ---
+++
@@ -2,14 +2,14 @@
class Neuron:
+ output = None
+
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
- def get_output(self):
- return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
-
- output = property(get_output)
+ def calculate(self):
+ self.output = sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
class NeuronNetwork: |
884483d27f7c0fac3975da17a7ef5c470ef9e3b4 | fcm_django/apps.py | fcm_django/apps.py | from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
| from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
default_auto_field = "django.db.models.BigAutoField"
| Use BigAutoField as the default ID | Use BigAutoField as the default ID | Python | mit | xtrinch/fcm-django | ---
+++
@@ -6,3 +6,4 @@
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
+ default_auto_field = "django.db.models.BigAutoField" |
a43e1c76ba3bef9ab3cbe1353c3b7289031a3b64 | pydub/playback.py | pydub/playback.py | import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def play(audio_segment):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
audio_segment.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
| import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def _play_with_ffplay(seg):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
seg.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
def _play_with_pyaudio(seg):
import pyaudio
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(seg.sample_width),
channels=seg.channels,
rate=seg.frame_rate,
output=True)
stream.write(seg._data)
stream.stop_stream()
stream.close()
p.terminate()
def play(audio_segment):
try:
import pyaudio
_play_with_pyaudio(audio_segment)
except ImportError:
_play_with_ffplay(audio_segment)
| Use Pyaudio when available, ffplay as fallback | Use Pyaudio when available, ffplay as fallback
| Python | mit | cbelth/pyMusic,miguelgrinberg/pydub,jiaaro/pydub,Geoion/pydub,joshrobo/pydub,sgml/pydub | ---
+++
@@ -4,7 +4,34 @@
PLAYER = get_player_name()
+
+
+def _play_with_ffplay(seg):
+ with NamedTemporaryFile("w+b", suffix=".wav") as f:
+ seg.export(f.name, "wav")
+ subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
+
+
+def _play_with_pyaudio(seg):
+ import pyaudio
+
+ p = pyaudio.PyAudio()
+ stream = p.open(format=p.get_format_from_width(seg.sample_width),
+ channels=seg.channels,
+ rate=seg.frame_rate,
+ output=True)
+
+ stream.write(seg._data)
+ stream.stop_stream()
+ stream.close()
+
+ p.terminate()
+
+
def play(audio_segment):
- with NamedTemporaryFile("w+b", suffix=".wav") as f:
- audio_segment.export(f.name, "wav")
- subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
+ try:
+ import pyaudio
+ _play_with_pyaudio(audio_segment)
+ except ImportError:
+ _play_with_ffplay(audio_segment)
+ |
414dd0b03b3e4eabc11f848f79d681f3a284380e | pygcvs/helpers.py | pygcvs/helpers.py | from .parser import GcvsParser
try:
import ephem
except ImportError:
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii/html/
"""
with open(filename, 'r') as fp:
parser = GcvsParser(fp)
for star in parser:
yield star
def dict_to_body(star_dict):
"""
Converts a dictionary of variable star data to a `Body` instance.
Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be installed.
"""
if ephem is None:
raise NotImplementedError("Please install PyEphem in order to use dict_to_body.")
body = ephem.FixedBody()
body.name = star_dict['name']
body._ra = ephem.hours(str(star_dict['ra']))
body._dec = ephem.degrees(str(star_dict['dec']))
body._epoch = ephem.J2000
return body
| from .parser import GcvsParser
try:
import ephem
except ImportError: # pragma: no cover
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii/html/
"""
with open(filename, 'r') as fp:
parser = GcvsParser(fp)
for star in parser:
yield star
def dict_to_body(star_dict):
"""
Converts a dictionary of variable star data to a `Body` instance.
Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be installed.
"""
if ephem is None: # pragma: no cover
raise NotImplementedError("Please install PyEphem in order to use dict_to_body.")
body = ephem.FixedBody()
body.name = star_dict['name']
body._ra = ephem.hours(str(star_dict['ra']))
body._dec = ephem.degrees(str(star_dict['dec']))
body._epoch = ephem.J2000
return body
| Exclude missing ephem from coverage | Exclude missing ephem from coverage
| Python | mit | zsiciarz/pygcvs | ---
+++
@@ -2,7 +2,7 @@
try:
import ephem
-except ImportError:
+except ImportError: # pragma: no cover
ephem = None
@@ -26,7 +26,7 @@
Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be installed.
"""
- if ephem is None:
+ if ephem is None: # pragma: no cover
raise NotImplementedError("Please install PyEphem in order to use dict_to_body.")
body = ephem.FixedBody()
body.name = star_dict['name'] |
cba707395196e78a54a1ded52066746680c5b225 | email_log/migrations/__init__.py | email_log/migrations/__init__.py | """
Django migrations for email_log app
This package does not contain South migrations. South migrations can be found
in the ``south_migrations`` package.
"""
SOUTH_ERROR_MESSAGE = """\n
For South support, customize the SOUTH_MIGRATION_MODULES setting like so:
SOUTH_MIGRATION_MODULES = {
'email_log': 'email_log.south_migrations',
}
"""
# Ensure the user is not using Django 1.6 or below with South
try:
from django.db import migrations # noqa
except ImportError:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE)
| Add friendly error message targeted at South users | Add friendly error message targeted at South users
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log | ---
+++
@@ -0,0 +1,21 @@
+"""
+Django migrations for email_log app
+
+This package does not contain South migrations. South migrations can be found
+in the ``south_migrations`` package.
+"""
+
+SOUTH_ERROR_MESSAGE = """\n
+For South support, customize the SOUTH_MIGRATION_MODULES setting like so:
+
+ SOUTH_MIGRATION_MODULES = {
+ 'email_log': 'email_log.south_migrations',
+ }
+"""
+
+# Ensure the user is not using Django 1.6 or below with South
+try:
+ from django.db import migrations # noqa
+except ImportError:
+ from django.core.exceptions import ImproperlyConfigured
+ raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE) | |
332fcb6566727a4736da42ccde449679136690a6 | dbaas/dbaas/settings_test.py | dbaas/dbaas/settings_test.py | from settings import * # noqa
# Comment this line for turn on debug on tests
LOGGING = {}
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--verbosity=0',
'--no-byte-compile',
'--debug-log=error_test.log',
'-s',
'--nologcapture'
]
if CI:
NOSE_ARGS += [
'--with-coverage',
'--cover-package=application',
'--with-xunit',
'--xunit-file=test-report.xml',
'--cover-xml',
'--cover-xml-file=coverage.xml'
]
| from settings import * # noqa
# Comment this line for turn on debug on tests
LOGGING = {}
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--verbosity=4',
'--no-byte-compile',
'--debug-log=error_test.log',
'-l',
'-s',
# '-x',
'--nologcapture',
#'--collect-only'
]
if CI:
NOSE_ARGS += [
'--with-coverage',
'--cover-package=application',
'--with-xunit',
'--xunit-file=test-report.xml',
'--cover-xml',
'--cover-xml-file=coverage.xml'
]
| Change parameters of tests to remove big output | Change parameters of tests to remove big output
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -5,11 +5,14 @@
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
- '--verbosity=0',
+ '--verbosity=4',
'--no-byte-compile',
'--debug-log=error_test.log',
+ '-l',
'-s',
- '--nologcapture'
+ # '-x',
+ '--nologcapture',
+ #'--collect-only'
]
if CI: |
9f37a35434389ff48afe52159f15d64e7f600ec2 | app/soc/models/grading_project_survey.py | app/soc/models/grading_project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the GradingProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <ajaksu@gmail.com>',
'"Lennard de Rijk" <ljvderijk@gmail.com>',
]
from soc.models.project_survey import ProjectSurvey
class GradingProjectSurvey(ProjectSurvey):
"""Survey for Mentors for each of their StudentProjects.
"""
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
self.taking_access = 'mentor'
| #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the GradingProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <ajaksu@gmail.com>',
'"Lennard de Rijk" <ljvderijk@gmail.com>',
]
from soc.models.project_survey import ProjectSurvey
class GradingProjectSurvey(ProjectSurvey):
"""Survey for Mentors for each of their StudentProjects.
"""
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
self.taking_access = 'org'
| Set default taking access for GradingProjectSurvey to org. | Set default taking access for GradingProjectSurvey to org.
This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
| Python | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -32,4 +32,4 @@
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
- self.taking_access = 'mentor'
+ self.taking_access = 'org' |
c9a9bf594f9d91a0a2f4c297e6200ebfa047bae6 | examples/manage.py | examples/manage.py | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bs3demo.settings')
execute_from_command_line(sys.argv)
| Use env variable for settings.py | Use env variable for settings.py
| Python | mit | rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,haricot/djangocms-bs4forcascade,haricot/djangocms-bs4forcascade,jrief/djangocms-cascade,jrief/djangocms-cascade,jrief/djangocms-cascade,rfleschenberg/djangocms-cascade,rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,jtiki/djangocms-cascade | ---
+++
@@ -7,4 +7,5 @@
if __name__ == "__main__":
from django.core.management import execute_from_command_line
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bs3demo.settings')
execute_from_command_line(sys.argv) |
1704ec592f1232364162ebc56e799d875f61ddd2 | app.py | app.py | import os
from flask import Flask, render_template
from pymongo import MongoClient
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index')
def index():
#online_users = mongo.db.users.find({'online': True})
return render_template('index.html', template_folder=tmpl_dir)#online_users=online_users) | import os
from flask import Flask, render_template
from pymongo import MongoClient
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
#client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index')
def index():
#online_users = mongo.db.users.find({'online': True})
return render_template('index.html', template_folder=tmpl_dir)#online_users=online_users)
| Comment out database connection until database is set up | Comment out database connection until database is set up
| Python | unknown | alanplotko/CoREdash,alanplotko/CoRE-Manager,alanplotko/CoREdash,alanplotko/CoRE-Manager | ---
+++
@@ -4,7 +4,7 @@
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
-client = MongoClient('localhost', 27017)
+#client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index') |
2a379bbef9549005b0c55f29a1bfb0f41811a4e0 | fabfile.py | fabfile.py | from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo systemctl stop dochub-gunicorn.service')
run("../backup_db.sh")
run("git pull")
run("pip install -r requirements.txt -q")
run("npm run build")
run("./manage.py collectstatic --noinput -v 0")
run("./manage.py migrate")
run('sudo systemctl start dochub-gunicorn.service')
run('sudo systemctl start dochub-gunicorn.socket')
def light_deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo systemctl stop dochub-gunicorn.service')
run("git pull")
run('sudo systemctl start dochub-gunicorn.service')
run('sudo systemctl start dochub-gunicorn.socket')
def restart_workers():
run('sudo systemctl stop dochub-celery')
run('sudo systemctl start dochub-celery')
def stats():
with cd(BASE_DIR), prefix(ACTIVATE):
run('./manage.py stats')
| from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo systemctl stop dochub-gunicorn.service')
run("../backup_db.sh")
run("git pull")
run("pip install -r requirements.txt -q")
run("npm install --no-progress")
run("npm run build")
run("./manage.py collectstatic --noinput -v 0")
run("./manage.py migrate")
run('sudo systemctl start dochub-gunicorn.service')
run('sudo systemctl start dochub-gunicorn.socket')
def light_deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo systemctl stop dochub-gunicorn.service')
run("git pull")
run('sudo systemctl start dochub-gunicorn.service')
run('sudo systemctl start dochub-gunicorn.socket')
def restart_workers():
run('sudo systemctl stop dochub-celery')
run('sudo systemctl start dochub-celery')
def stats():
with cd(BASE_DIR), prefix(ACTIVATE):
run('./manage.py stats')
| Add npm install to the fabric script | Add npm install to the fabric script
| Python | agpl-3.0 | UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub | ---
+++
@@ -13,6 +13,7 @@
run("../backup_db.sh")
run("git pull")
run("pip install -r requirements.txt -q")
+ run("npm install --no-progress")
run("npm run build")
run("./manage.py collectstatic --noinput -v 0")
run("./manage.py migrate") |
bbda0891e2fc4d2dfec157e9249e02d114c7c45a | corehq/tests/test_toggles.py | corehq/tests/test_toggles.py | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing'.format(toggle.slug)
assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug)
assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag)
assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug)
| from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing'.format(toggle.slug)
assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug)
assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag)
assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug)
def test_solutions_sub_tags():
"""
Check Solutions sub-tags begin with 'Solutions - '
"""
solutions_tags = [toggles.TAG_SOLUTIONS_OPEN, toggles.TAG_SOLUTIONS_CONDITIONAL, toggles.TAG_SOLUTIONS_LIMITED]
for tag in solutions_tags:
assert tag.name.startswith('Solutions - ')
| Add test to check Solutions sub-tags names | Add test to check Solutions sub-tags names
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -14,3 +14,12 @@
assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug)
assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag)
assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug)
+
+
+def test_solutions_sub_tags():
+ """
+ Check Solutions sub-tags begin with 'Solutions - '
+ """
+ solutions_tags = [toggles.TAG_SOLUTIONS_OPEN, toggles.TAG_SOLUTIONS_CONDITIONAL, toggles.TAG_SOLUTIONS_LIMITED]
+ for tag in solutions_tags:
+ assert tag.name.startswith('Solutions - ') |
d8310b3d0a4664f90d89b59fd6d5660f6cc0ab2b | conference/gmap.py | conference/gmap.py | # -*- coding: UTF-8 -*-
import urllib
import httplib
import simplejson
G = 'maps.google.com'
def geocode(address, key, country):
"""
Get the coordinates from Google Maps for a specified address
"""
# see http://code.google.com/intl/it/apis/maps/documentation/geocoding/#GeocodingRequests
params = {
'q': address.encode('utf-8') if isinstance(address, unicode) else address,
'key': key,
'sensor': 'false',
'output': 'json',
'oe': 'utf8',
}
if country:
params['gl'] = country
url = '/maps/geo?' + urllib.urlencode(params.items())
conn = httplib.HTTPConnection(G)
try:
conn.request('GET', url)
r = conn.getresponse()
if r.status == 200:
return simplejson.loads(r.read())
else:
return {'Status': {'code': r.status }}
finally:
conn.close()
| # -*- coding: UTF-8 -*-
import urllib
import httplib
import simplejson
G = 'maps.google.com'
# FIXME: use this function or this one, but the code is in double assopy.utils.geocode
def geocode(address, key, country): # pragma: no cover
"""
Get the coordinates from Google Maps for a specified address
"""
# see http://code.google.com/intl/it/apis/maps/documentation/geocoding/#GeocodingRequests
params = {
'q': address.encode('utf-8') if isinstance(address, unicode) else address,
'key': key,
'sensor': 'false',
'output': 'json',
'oe': 'utf8',
}
if country:
params['gl'] = country
url = '/maps/geo?' + urllib.urlencode(params.items())
conn = httplib.HTTPConnection(G)
try:
conn.request('GET', url)
r = conn.getresponse()
if r.status == 200:
return simplejson.loads(r.read())
else:
return {'Status': {'code': r.status }}
finally:
conn.close()
| Add a pragma and in the future we need to fix the function, because it's a duplicata | Add a pragma and in the future we need to fix the function, because it's a duplicata
| Python | bsd-2-clause | artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon,artcz/epcon,artcz/epcon,artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon | ---
+++
@@ -5,7 +5,8 @@
G = 'maps.google.com'
-def geocode(address, key, country):
+# FIXME: use this function or this one, but the code is in double assopy.utils.geocode
+def geocode(address, key, country): # pragma: no cover
"""
Get the coordinates from Google Maps for a specified address
""" |
c82eaa445ddbe39f4142de7f51f0d19437a1aef0 | validators/url.py | validators/url.py | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""
url
---
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`.
This validator is based on `WTForms URL validator`_.
.. _WTForms URL validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> import validators
>>> assert validators.url('http://foobar.dk')
>>> assert validators.url('http://localhost/foobar', require_tld=False)
>>> assert not validators.url('http://foobar.d')
.. versionadded:: 0.2
:param value: URL address string to validate
"""
if require_tld:
return pattern_with_tld.match(value)
return pattern_without_tld.match(value)
| import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`.
This validator is based on `WTForms URL validator`_.
.. _WTForms URL validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> import validators
>>> assert validators.url('http://foobar.dk')
>>> assert validators.url('http://localhost/foobar', require_tld=False)
>>> assert not validators.url('http://foobar.d')
.. versionadded:: 0.2
:param value: URL address string to validate
"""
if require_tld:
return pattern_with_tld.match(value)
return pattern_without_tld.match(value)
| Remove unnecessary heading from docstring | Remove unnecessary heading from docstring
| Python | mit | kvesteri/validators | ---
+++
@@ -14,9 +14,6 @@
@validator
def url(value, require_tld=True):
"""
- url
- ---
-
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`. |
1d4d317c826cd8528dfafd4ae47d006c1e8bb673 | reports/admin.py | reports/admin.py | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
list_filter = ['created_at', 'content']
search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from']
admin.site.register(Report, ReportAdmin)
| # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'signed_from', 'created_at')
list_filter = ['created_at']
search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from']
admin.site.register(Report, ReportAdmin)
| Change search and list fields | Change search and list fields
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -3,8 +3,8 @@
from .models import Report
class ReportAdmin(admin.ModelAdmin):
- list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
- list_filter = ['created_at', 'content']
+ list_display = ('addressed_to', 'reported_from', 'signed_from', 'created_at')
+ list_filter = ['created_at']
search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from']
admin.site.register(Report, ReportAdmin) |
4a98d2ce95d6a082588e4ccc8e04454c26260ca0 | helpers.py | helpers.py | def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
elif isinstance(passed_list, dict):
for i, item in enumerate(passed_list.values()):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output + end
def get_list_as_english(passed_list):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item) + ' '
elif len(passed_list) is 2:
output += str(item)
if i is not (len(passed_list) - 1):
output += " and "
else:
output += ""
else:
if i is not (len(passed_list) - 1):
output += str(item) + ", "
else:
output += "and " + str(item) + ", "
return output
| def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list) or isinstance(passed_list, tuple):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
elif isinstance(passed_list, dict):
for i, item in enumerate(passed_list.values()):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
return output + end
def get_list_as_english(passed_list):
output = ""
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item) + ' '
elif len(passed_list) is 2:
output += str(item)
if i is not (len(passed_list) - 1):
output += " and "
else:
output += ""
else:
if i is not (len(passed_list) - 1):
output += str(item) + ", "
else:
output += "and " + str(item) + ", "
return output
| Make get_readable_list process tuples, too | Make get_readable_list process tuples, too
| Python | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -1,6 +1,6 @@
def get_readable_list(passed_list, sep=', ', end=''):
output = ""
- if isinstance(passed_list, list):
+ if isinstance(passed_list, list) or isinstance(passed_list, tuple):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
@@ -10,6 +10,7 @@
output += str(item) + sep
else:
output += str(item)
+
elif isinstance(passed_list, dict):
for i, item in enumerate(passed_list.values()): |
9bc7d09e9abf79f6af7f7fd3cdddbfacd91ba9d3 | run.py | run.py | #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push dokku master")
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--deploy', action="store_true", required=False)
args = parser.parse_args()
if args.deploy:
deploy()
else:
run()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push dokku master")
def dependencies():
os.system("pip-compile --upgrade requirements.in")
os.system("pip-compile --upgrade requirements-dev.in")
os.system("pip-sync requirements-dev.txt")
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--deploy', action="store_true", required=False)
parser.add_argument('--deps', action="store_true", required=False)
args = parser.parse_args()
if args.deploy:
deploy()
elif args.deps:
dependencies()
else:
run()
if __name__ == '__main__':
main()
| Add command to update dependencies. | Add command to update dependencies.
| Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | ---
+++
@@ -14,15 +14,24 @@
def deploy():
os.system("git push dokku master")
+def dependencies():
+ os.system("pip-compile --upgrade requirements.in")
+ os.system("pip-compile --upgrade requirements-dev.in")
+ os.system("pip-sync requirements-dev.txt")
+
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--deploy', action="store_true", required=False)
+ parser.add_argument('--deps', action="store_true", required=False)
args = parser.parse_args()
if args.deploy:
deploy()
+ elif args.deps:
+ dependencies()
else:
run()
+
if __name__ == '__main__':
main() |
5b208baa581e16290aa8332df966ad1d61876107 | deployment/ansible/filter_plugins/custom_filters.py | deployment/ansible/filter_plugins/custom_filters.py | class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, *t):
"""Determnies if there are no elements in common between x and y
x | is_not_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
groups_to_test, all_group_names = t
return set(groups_to_test).isdisjoint(set(all_group_names))
def is_in(self, *t):
"""Determnies if all of the elements in x are a subset of y
x | is_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
groups_to_test, all_group_names = t
return set(groups_to_test).issubset(set(all_group_names))
def some_are_in(self, *t):
"""Determnies if any element in x intersects with y
x | some_are_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
groups_to_test, all_group_names = t
return len(set(groups_to_test) & set(all_group_names)) > 0
| class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, x, y):
"""Determines if there are no elements in common between x and y
x | is_not_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
return set(x).isdisjoint(set(y))
def is_in(self, x, y):
"""Determines if all of the elements in x are a subset of y
x | is_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
return set(x).issubset(set(y))
def some_are_in(self, x, y):
"""Determines if any element in x intersects with y
x | some_are_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
return len(set(x) & set(y)) > 0
| Add explicit method signature to custom filters | Add explicit method signature to custom filters
This changeset adds an explicit method signature to the Ansible custom filters.
| Python | agpl-3.0 | maurizi/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,maurizi/nyc-trees | ---
+++
@@ -8,38 +8,32 @@
'some_are_in': self.some_are_in
}
- def is_not_in(self, *t):
- """Determnies if there are no elements in common between x and y
+ def is_not_in(self, x, y):
+ """Determines if there are no elements in common between x and y
x | is_not_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
- groups_to_test, all_group_names = t
+ return set(x).isdisjoint(set(y))
- return set(groups_to_test).isdisjoint(set(all_group_names))
-
- def is_in(self, *t):
- """Determnies if all of the elements in x are a subset of y
+ def is_in(self, x, y):
+ """Determines if all of the elements in x are a subset of y
x | is_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
- groups_to_test, all_group_names = t
+ return set(x).issubset(set(y))
- return set(groups_to_test).issubset(set(all_group_names))
-
- def some_are_in(self, *t):
- """Determnies if any element in x intersects with y
+ def some_are_in(self, x, y):
+ """Determines if any element in x intersects with y
x | some_are_in(y)
Arguments
:param t: A tuple with two elements (x and y)
"""
- groups_to_test, all_group_names = t
-
- return len(set(groups_to_test) & set(all_group_names)) > 0
+ return len(set(x) & set(y)) > 0 |
b2e0b2047fa686fd716ba22dcec536b79f6fea41 | cookielaw/templatetags/cookielaw_tags.py | cookielaw/templatetags/cookielaw_tags.py | from classytags.helpers import InclusionTag
from django import template
from django.template.loader import render_to_string
register = template.Library()
class CookielawBanner(InclusionTag):
"""
Displays cookie law banner only if user has not dismissed it yet.
"""
template = 'cookielaw/banner.html'
def render_tag(self, context, **kwargs):
template = self.get_template(context, **kwargs)
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
data = self.get_context(context, **kwargs)
return render_to_string(template, data)
register.tag(CookielawBanner)
| # -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
return render_to_string('cookielaw/banner.html', context)
| Use Django simple_tag instead of classytags because there were no context in template rendering. | Use Django simple_tag instead of classytags because there were no context in template rendering. | Python | bsd-2-clause | juan-cb/django-cookie-law,juan-cb/django-cookie-law,juan-cb/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law | ---
+++
@@ -1,4 +1,5 @@
-from classytags.helpers import InclusionTag
+# -*- coding: utf-8 -*-
+
from django import template
from django.template.loader import render_to_string
@@ -6,18 +7,9 @@
register = template.Library()
-class CookielawBanner(InclusionTag):
- """
- Displays cookie law banner only if user has not dismissed it yet.
- """
+@register.simple_tag(takes_context=True)
+def cookielaw_banner(context):
+ if context['request'].COOKIES.get('cookielaw_accepted', False):
+ return ''
+ return render_to_string('cookielaw/banner.html', context)
- template = 'cookielaw/banner.html'
-
- def render_tag(self, context, **kwargs):
- template = self.get_template(context, **kwargs)
- if context['request'].COOKIES.get('cookielaw_accepted', False):
- return ''
- data = self.get_context(context, **kwargs)
- return render_to_string(template, data)
-
-register.tag(CookielawBanner) |
92e7164cf152700c4ae60013bfbb9536e425a64c | neo/rawio/tests/test_nixrawio.py | neo/rawio/tests/test_nixrawio.py | import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "neoraw.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "__main__":
unittest.main()
| import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "nixrawio-1.5.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "__main__":
unittest.main()
| Change filename for NIXRawIO tests | [nixio] Change filename for NIXRawIO tests
| Python | bsd-3-clause | NeuralEnsemble/python-neo,INM-6/python-neo,JuliaSprenger/python-neo,apdavison/python-neo,rgerkin/python-neo,samuelgarcia/python-neo | ---
+++
@@ -3,9 +3,10 @@
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
-testfname = "neoraw.nix"
+testfname = "nixrawio-1.5.nix"
-class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
+
+class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.