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 |
|---|---|---|---|---|---|---|---|---|---|---|
4a32fe3b3735df9ec56a4ca1769268740ef5d8f4 | tests/test_to_html.py | tests/test_to_html.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expected, **kwargs):
self.assertEqual(self.func(source, **kwargs), expected)
def test_empty(self):
self.check("", "")
def test_ascii(self):
self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n")
def test_non_ascii(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>. И другие штуки.</p>\n"))
def test_breaks(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"),
breaks=True)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = (
"Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expected, **kwargs):
self.assertEqual(self.func(source, **kwargs), expected)
def test_empty(self):
self.check("", "")
def test_ascii(self):
self.check("Hello, Noob!", "<p>Hello, Noob!</p>\n")
def test_non_ascii(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>. И другие штуки.</p>\n"
"<p>Test of <em>HTML</em>.</p>\n"))
def test_breaks(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
"<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"
"<p>Test of <em>HTML</em>.</p>\n"),
breaks=True)
| Add HTML fragment to test sample | Add HTML fragment to test sample
| Python | bsd-3-clause | PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark | ---
+++
@@ -6,7 +6,9 @@
class ToHTMLTest(unittest.TestCase):
- SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
+ SAMPLE = (
+ "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
+ "<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
@@ -27,12 +29,14 @@
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
- "<p>Вставляем <code>код</code>. И другие штуки.</p>\n"))
+ "<p>Вставляем <code>код</code>. И другие штуки.</p>\n"
+ "<p>Test of <em>HTML</em>.</p>\n"))
def test_breaks(self):
self.check(
self.SAMPLE,
(
"<p>Проверяем <em>CommonMark</em>.</p>\n"
- "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"),
+ "<p>Вставляем <code>код</code>.\nИ другие штуки.</p>\n"
+ "<p>Test of <em>HTML</em>.</p>\n"),
breaks=True) |
d0a02a8190d040eea3065a1141dbd41679c5eee3 | tools/casper_tests.py | tools/casper_tests.py | #!/usr/bin/env python
import multiprocessing
import subprocess
import glob
import os
if __name__ == "__main__":
os.environ["MLTSP_TEST_DB"] = "1"
from mltsp.Flask import flask_app
flask_app.db_init(force=True)
from mltsp.Flask.flask_app import app
p = multiprocessing.Process(target=app.run)
p.start()
tests = sorted(glob.glob('mltsp/tests/frontend/*.js'))
subprocess.call(['external/casperjs/bin/casperjs', '--verbose',
'--log-level=debug', 'test'] + tests)
p.terminate()
| #!/usr/bin/env python
import multiprocessing
import subprocess
import glob
import os
import sys
if __name__ == "__main__":
os.environ["MLTSP_TEST_DB"] = "1"
from mltsp.Flask import flask_app
flask_app.db_init(force=True)
from mltsp.Flask.flask_app import app
p = multiprocessing.Process(target=app.run)
p.start()
tests = sorted(glob.glob('mltsp/tests/frontend/*.js'))
status = subprocess.call(['external/casperjs/bin/casperjs', '--verbose',
'--log-level=debug', 'test'] + tests)
p.terminate()
sys.exit(status)
| Exit frontend tests with Casper status | Exit frontend tests with Casper status
| Python | bsd-3-clause | mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,acrellin/mltsp,bnaul/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp | ---
+++
@@ -4,6 +4,7 @@
import subprocess
import glob
import os
+import sys
if __name__ == "__main__":
@@ -16,10 +17,10 @@
p.start()
tests = sorted(glob.glob('mltsp/tests/frontend/*.js'))
- subprocess.call(['external/casperjs/bin/casperjs', '--verbose',
- '--log-level=debug', 'test'] + tests)
+ status = subprocess.call(['external/casperjs/bin/casperjs', '--verbose',
+ '--log-level=debug', 'test'] + tests)
p.terminate()
+ sys.exit(status)
- |
405c5cc9f88f3ea69f101ae36f3b3bf05b54a9eb | luckystrike/config.py | luckystrike/config.py | import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
else:
with open('config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
users = configuration['users']
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
action='store_true',
help='increase debug level'
)
parser.add_argument(
'-s', '--setup_config',
action='store_true',
help='generate config.json'
)
args = parser.parse_args()
# connect to Campfire
campfire = pinder.Campfire(configuration['domain'], configuration['api_key'])
# Initialize the Cred authentication system used by the IRC server.
irc_realm = service.InMemoryWordsRealm('LuckyStrike')
| import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
else:
with open('config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
users = configuration['users']
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
action='count',
help='add debug logging, add multiple times to increase level'
)
parser.add_argument(
'-s', '--setup_config',
action='store_true',
help='generate config.json'
)
args = parser.parse_args()
# connect to Campfire
campfire = pinder.Campfire(configuration['domain'], configuration['api_key'])
# Initialize the Cred authentication system used by the IRC server.
irc_realm = service.InMemoryWordsRealm('LuckyStrike')
| Add ability to increase debug level through multiple instances of flag | Add ability to increase debug level through multiple instances of flag
| Python | mit | mmichie/luckystrike | ---
+++
@@ -21,8 +21,8 @@
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
- action='store_true',
- help='increase debug level'
+ action='count',
+ help='add debug logging, add multiple times to increase level'
)
parser.add_argument(
'-s', '--setup_config', |
c53e9266877f84d6a9f0d334a799a2e2d456471d | config/local_settings_staging.py | config/local_settings_staging.py | DEBUG = False
ENVIRONMENT = "staging"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
| DEBUG = False
ENVIRONMENT = "staging"
ALLOWED_HOSTS = ('dev.lutris.net',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
| Add ALLOWED_HOSTS on staging server settings | Add ALLOWED_HOSTS on staging server settings
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,lutris/website,lutris/website | ---
+++
@@ -1,6 +1,6 @@
DEBUG = False
ENVIRONMENT = "staging"
-
+ALLOWED_HOSTS = ('dev.lutris.net',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', |
005e7175f5fcd7e74637790e66e5cf46825195f6 | tests/cupy_tests/cuda_tests/test_nccl.py | tests/cupy_tests/cuda_tests/test_nccl.py | import unittest
from cupy import cuda
from cupy.testing import attr
@unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed')
class TestNCCL(unittest.TestCase):
@attr.gpu
def test_single_proc_ring(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
assert 0 == comm.rank_id()
comm.destroy()
@attr.gpu
@unittest.skipUnless(cuda.nccl_enabled and
cuda.nccl.get_version() >= 2400, 'Using old NCCL')
def test_abort(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.abort()
@attr.gpu
@unittest.skipUnless(cuda.nccl_enabled and
cuda.nccl.get_version() >= 2400, 'Using old NCCL')
def test_check_async_error(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.check_async_error()
comm.destroy()
| import unittest
from cupy import cuda
from cupy.testing import attr
@unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed')
class TestNCCL(unittest.TestCase):
@attr.gpu
def test_single_proc_ring(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
assert 0 == comm.rank_id()
comm.destroy()
@attr.gpu
@unittest.skipUnless(cuda.nccl_enabled and
cuda.nccl.get_version() >= 2400, 'Using old NCCL')
def test_abort(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.abort()
@attr.gpu
@unittest.skipUnless(cuda.nccl_enabled and
cuda.nccl.get_version() >= 2400, 'Using old NCCL')
def test_check_async_error(self):
id = cuda.nccl.get_unique_id()
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.check_async_error()
comm.destroy()
@attr.gpu
def test_init_all(self):
comm = cuda.nccl.NcclCommunicator.initAll(1)
assert 0 == comm.rank_id()
comm.destroy()
| Add a test for initAll() | Add a test for initAll()
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -30,3 +30,9 @@
comm = cuda.nccl.NcclCommunicator(1, id, 0)
comm.check_async_error()
comm.destroy()
+
+ @attr.gpu
+ def test_init_all(self):
+ comm = cuda.nccl.NcclCommunicator.initAll(1)
+ assert 0 == comm.rank_id()
+ comm.destroy() |
620d59b82e8a5c98fd4568217c74b485f802ac94 | tests/integration/test_authentication.py | tests/integration/test_authentication.py | from pyutrack import Connection
from pyutrack import Credentials
from pyutrack.errors import LoginError
from tests.integration import IntegrationTest
class AuthenticationTests(IntegrationTest):
def test_successful_authentication(self):
connection = Connection(
credentials=Credentials(username='root', password='root'),
base_url='http://localhost:9876'
)
self.assertTrue(connection.login())
def test_invalid_password(self):
connection = Connection(
credentials=Credentials(username='root', password='rooted'),
base_url='http://localhost:9876'
)
self.assertRaises(connection.login, LoginError)
| from pyutrack import Connection
from pyutrack import Credentials
from pyutrack.errors import LoginError
from tests.integration import IntegrationTest
class AuthenticationTests(IntegrationTest):
def test_successful_authentication(self):
connection = Connection(
credentials=Credentials(username='root', password='root'),
base_url='http://localhost:9876'
)
self.assertTrue(connection.login())
def test_invalid_password(self):
connection = Connection(
credentials=Credentials(username='root', password='rooted'),
base_url='http://localhost:9876'
)
self.assertRaises(LoginError, connection.login)
| Fix order of assertion arguments | Fix order of assertion arguments
| Python | mit | alisaifee/pyutrack,alisaifee/pyutrack | ---
+++
@@ -17,4 +17,4 @@
credentials=Credentials(username='root', password='rooted'),
base_url='http://localhost:9876'
)
- self.assertRaises(connection.login, LoginError)
+ self.assertRaises(LoginError, connection.login) |
5adbcbbce53985862f0cfcceadb4a3c0da2abe3d | tests/query_test/test_decimal_queries.py | tests/query_test/test_decimal_queries.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
| #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
| Update decimal tests to only run on text/none. | Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
| Python | apache-2.0 | michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala | ---
+++
@@ -25,7 +25,8 @@
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
- v.get_value('table_format').file_format == 'text')
+ v.get_value('table_format').file_format == 'text' and
+ v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector) |
245a6b190c1ad3c5e380c5957d6b98593fdb4006 | logserver/__main__.py | logserver/__main__.py | from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--table", default="logs",
help="Name of table to store logs in")
parser.add_argument("-f", "--filename", default="logs.sqlite",
help="SQLite filename")
args = parser.parse_args()
handlers = [
logging.StreamHandler(),
SQLiteHandler(args.filename, args.table)
]
print("Listening for logs to handle on port", args.port)
server = run_server(handlers, port=args.port)
| from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--table", default="logs",
help="Name of table to store logs in")
parser.add_argument("-f", "--filename", default="logs.sqlite",
help="SQLite filename")
args = parser.parse_args()
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter(
"[%(levelname)1.1s %(name)s %(asctime)s] %(msg)s"))
handlers = [
stream_handler,
SQLiteHandler(args.filename, args.table)
]
print("Listening for logs to handle on port", args.port)
server = run_server(handlers, port=args.port)
| Format messages in stream handler | Format messages in stream handler
| Python | mit | mivade/logserver | ---
+++
@@ -13,8 +13,12 @@
help="SQLite filename")
args = parser.parse_args()
+stream_handler = logging.StreamHandler()
+stream_handler.setFormatter(logging.Formatter(
+ "[%(levelname)1.1s %(name)s %(asctime)s] %(msg)s"))
+
handlers = [
- logging.StreamHandler(),
+ stream_handler,
SQLiteHandler(args.filename, args.table)
]
|
0ac5a45c27b574c73d2660e96543220e274e1c64 | magpy/server/_ejdb.py | magpy/server/_ejdb.py | """EJDB driver for Magpy.
Currently does not do much except support certain command line scripts.
"""
import os
import pyejdb
class Database(object):
"""Simple database connection for use in serverside scripts etc."""
def __init__(self,
database_name=None,
config_file=None):
self.config_file = config_file
if not database_name:
database_name = os.path.expanduser('~/magpy.tct')
self._database_name = database_name
self.database = pyejdb.EJDB(database_name,
pyejdb.DEFAULT_OPEN_MODE |
pyejdb.JBOTRUNC)
def get_collection(self, collection):
"""Get a collection by name."""
return Collection(collection, self)
def drop_collections(self, collections):
"""Drop a named tuple or list of collections."""
for collection in collections:
self.database.dropCollection(collection)
class Collection(object):
"""A mongodb style collection object."""
def __init__(self, name, database):
self.database = database
self.name = name
def find(self):
"""Find instances from a collection."""
return self.database.database.find(self.name)
def find_one(self):
"""Find a single instance from a collection."""
raise NotImplementedError
def save(self, instance):
"""Save an instance."""
self.database.database.save(self.name, instance)
| """EJDB driver for Magpy.
Currently does not do much except support certain command line scripts.
"""
import os
import pyejdb
class Database(object):
"""Simple database connection for use in serverside scripts etc."""
def __init__(self,
database_name=None,
config_file=None):
self.config_file = config_file
if not database_name:
database_name = os.path.expanduser('~/magpy.tct')
self._database_name = database_name
self.database = pyejdb.EJDB(database_name,
pyejdb.DEFAULT_OPEN_MODE |
pyejdb.JBOTRUNC)
def get_collection(self, collection):
"""Get a collection by name."""
return Collection(collection, self)
def drop_collections(self, collections):
"""Drop a named tuple or list of collections."""
for collection in collections:
self.database.dropCollection(collection)
class Collection(object):
"""A mongodb style collection object."""
def __init__(self, name, database):
self.database = database
self.name = name
def find(self):
"""Find instances from a collection."""
return self.database.database.find(self.name)
def find_one(self):
"""Find a single instance from a collection."""
raise NotImplementedError
def save(self, instance):
"""Save an instance."""
instance['id'] = instance.pop('_id')
self.database.database.save(self.name, instance)
| Deal with the weirdnesses of ejdb. | Deal with the weirdnesses of ejdb.
| Python | bsd-3-clause | zeth/magpy,catsmith/magpy,zeth/magpy,catsmith/magpy | ---
+++
@@ -44,4 +44,5 @@
def save(self, instance):
"""Save an instance."""
+ instance['id'] = instance.pop('_id')
self.database.database.save(self.name, instance) |
2ef97402219107fc632196bb0a7e3d6de38e5888 | latest_tweets/management/commands/latest_tweets_update.py | latest_tweets/management/commands/latest_tweets_update.py | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
# Need to escape HTML entities
htmlparser = html_parser.HTMLParser()
unescape = htmlparser.unescape
for i in messages:
tweet_id = i['id']
tweet_username = i['user']['screen_name']
tweet_text = unescape(i['text'])
tweet_created = datetime.strptime(
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
obj, created = Tweet.objects.get_or_create(tweet_id=tweet_id, defaults={
'user': tweet_username,
'text': tweet_text,
'created': tweet_created,
})
class Command(BaseCommand):
def handle(self, *args, **options):
for i in args:
update_user(i)
| from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
# Need to escape HTML entities
htmlparser = html_parser.HTMLParser()
unescape = htmlparser.unescape
for i in messages:
tweet_id = i['id']
tweet_username = i['user']['screen_name']
tweet_text = unescape(i['text'])
tweet_created = datetime.strptime(
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
obj, created = Tweet.objects.update_or_create(tweet_id=tweet_id, defaults={
'user': tweet_username,
'text': tweet_text,
'created': tweet_created,
})
class Command(BaseCommand):
def handle(self, *args, **options):
for i in args:
update_user(i)
| Switch to update_or_create - Django 1.7+ | Switch to update_or_create - Django 1.7+
Can't use this on older versions of Django
| Python | bsd-3-clause | blancltd/django-latest-tweets | ---
+++
@@ -28,7 +28,7 @@
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
- obj, created = Tweet.objects.get_or_create(tweet_id=tweet_id, defaults={
+ obj, created = Tweet.objects.update_or_create(tweet_id=tweet_id, defaults={
'user': tweet_username,
'text': tweet_text,
'created': tweet_created, |
8a0f17eea757f2001ec9d9579a413ab852549d39 | tavenner.py | tavenner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
def main():
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid='
errors = 0
i = 1
while True:
req = Request(url_base + str(i))
try:
f = urlopen(req)
sys.stdout.write('.')
sys.stdout.flush()
errors = 0
local_file = open(str(i) + '.html', 'w')
local_file.write(f.read())
local_file.close()
except HTTPError as e:
sys.stdout.write(' ')
sys.stdout.flush()
errors += 1
i += 1
if errors >= 100:
break
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
import zipfile
import sys
import hashlib
output_dir = 'output'
def main():
# Make our output directory, if it doesn't exist.
if not os.path.exists(output_dir):
os.makedirs(output_dir)
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid='
errors = 0
i = 1
while True:
req = Request(url_base + str(i))
try:
f = urlopen(req)
sys.stdout.write('.')
sys.stdout.flush()
errors = 0
local_file = open(str(i) + '.html', 'w')
local_file.write(f.read())
local_file.close()
except HTTPError as e:
sys.stdout.write(' ')
sys.stdout.flush()
errors += 1
i += 1
if errors >= 100:
break
if __name__ == "__main__":
main()
| Store output in a subdirectory | Store output in a subdirectory
| Python | mit | openva/tavenner | ---
+++
@@ -7,7 +7,13 @@
import sys
import hashlib
+output_dir = 'output'
+
def main():
+
+ # Make our output directory, if it doesn't exist.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
from urllib2 import Request, urlopen, HTTPError
url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid=' |
d2e03bf76f585dc1025b5a94be0327284f8d5fa2 | Left_pare.py | Left_pare.py | # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
view = viewSvc.currentView
view = view.queryInterface(components.interfaces.koIScintillaView)
sm = view.scimoz
# Make `start` the beginning position of the first selected line,
# and `end` the ending position of the last selected line.
if sm.anchor < sm.currentPos:
start = sm.positionFromLine(sm.lineFromPosition(sm.anchor))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.currentPos))
else:
start = sm.positionFromLine(sm.lineFromPosition(sm.currentPos))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.anchor))
lines = tuple(sm.getTextRange(start, end).splitlines())
# Cut one character from the left
lines = tuple(l[1:] for l in lines)
# Select part of document
sm.setSel(start, end)
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
# Keep selection to allow to continue to apply this macro if use wants
sm.setSel(start, start+len(text))
| # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
view = viewSvc.currentView
view = view.queryInterface(components.interfaces.koIScintillaView)
sm = view.scimoz
# Make `start` the beginning position of the first selected line,
# and `end` the ending position of the last selected line.
if sm.anchor < sm.currentPos:
start = sm.positionFromLine(sm.lineFromPosition(sm.anchor))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.currentPos))
else:
start = sm.positionFromLine(sm.lineFromPosition(sm.currentPos))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.anchor))
lines = tuple(sm.getTextRange(start, end).splitlines())
# Cut one character from the left
lines = tuple(l[1:] for l in lines)
# Select part of document
sm.setSel(start, end)
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
# Keep selection to let user continue to apply this macro
sm.setSel(start, start+len(text.encode('utf-8')))
| Correct selecting text by length when text is Unicode. | Correct selecting text by length when text is Unicode.
| Python | mpl-2.0 | Komodo/macros,Komodo/macros | ---
+++
@@ -28,5 +28,5 @@
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
-# Keep selection to allow to continue to apply this macro if use wants
-sm.setSel(start, start+len(text))
+# Keep selection to let user continue to apply this macro
+sm.setSel(start, start+len(text.encode('utf-8'))) |
0a884d3c38cb1449a6fa5c650ed06cde647de4a8 | settings/sqlite.py | settings/sqlite.py | from .base import *
import os.path
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(SITE_ROOT, 'dev.db'),
}
}
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
| from .base import *
import os.path
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(SITE_ROOT, 'dev.db'),
}
}
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
try:
from local_settings import *
except:
pass
| Allow local settings override as well. | Allow local settings override as well.
| Python | mit | singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,kenwang76/readthedocs.org,hach-que/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,asampat3090/readthedocs.org,safwanrahman/readthedocs.org,istresearch/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,kdkeyser/readthedocs.org,GovReady/readthedocs.org,techtonik/readthedocs.org,agjohnson/readthedocs.org,davidfischer/readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,nikolas/readthedocs.org,cgourlay/readthedocs.org,wanghaven/readthedocs.org,royalwang/readthedocs.org,sils1297/readthedocs.org,nyergler/pythonslides,agjohnson/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,soulshake/readthedocs.org,SteveViss/readthedocs.org,kenwang76/readthedocs.org,wijerasa/readthedocs.org,istresearch/readthedocs.org,KamranMackey/readthedocs.org,nyergler/pythonslides,laplaceliu/readthedocs.org,SteveViss/readthedocs.org,attakei/readthedocs-oauth,emawind84/readthedocs.org,jerel/readthedocs.org,takluyver/readthedocs.org,Tazer/readthedocs.org,titiushko/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,nikolas/readthedocs.org,kenwang76/readthedocs.org,dirn/readthedocs.org,emawind84/readthedocs.org,royalwang/readthedocs.org,takluyver/readthedocs.org,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,jerel/readthedocs.org,espdev/readthedocs.org,laplaceliu/readthedocs.org,michaelmcandrew/readthedocs.org,d0ugal/readthedocs.org,techtonik/readthedocs.org,rtfd/readthedocs.org,titiushko/readthedocs.org,istresearch/readthedocs.org,Carreau/readthedocs.org,agjohnson/readthedocs.org,mrshoki/readthedocs.org,sils1297/readthedocs.org,atsuyim/readthedocs.org,ojii/readthedocs.org,clarkperkins/readthedocs.org,sils1297/readthedocs.org,laplaceliu/readthedocs.org,ojii/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,hach-que/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,titiushko/readthedocs.org,hach-que/readthedocs.org,johncosta/private-readthedocs.org,sils1297/readthedocs.org,mrshoki/readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,techtonik/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,fujita-shintaro/readthedocs.org,SteveViss/readthedocs.org,wanghaven/readthedocs.org,stevepiercy/readthedocs.org,kdkeyser/readthedocs.org,wanghaven/readthedocs.org,ojii/readthedocs.org,CedarLogic/readthedocs.org,soulshake/readthedocs.org,kdkeyser/readthedocs.org,SteveViss/readthedocs.org,LukasBoersma/readthedocs.org,d0ugal/readthedocs.org,michaelmcandrew/readthedocs.org,gjtorikian/readthedocs.org,hach-que/readthedocs.org,wijerasa/readthedocs.org,nikolas/readthedocs.org,Carreau/readthedocs.org,raven47git/readthedocs.org,jerel/readthedocs.org,michaelmcandrew/readthedocs.org,mrshoki/readthedocs.org,nyergler/pythonslides,nikolas/readthedocs.org,clarkperkins/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org,LukasBoersma/readthedocs.org,davidfischer/readthedocs.org,mrshoki/readthedocs.org,tddv/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,kdkeyser/readthedocs.org,safwanrahman/readthedocs.org,sid-kap/readthedocs.org,kenshinthebattosai/readthedocs.org,emawind84/readthedocs.org,pombredanne/readthedocs.org,VishvajitP/readthedocs.org,KamranMackey/readthedocs.org,Carreau/readthedocs.org,safwanrahman/readthedocs.org,soulshake/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,KamranMackey/readthedocs.org,takluyver/readthedocs.org,gjtorikian/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,stevepiercy/readthedocs.org,LukasBoersma/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,johncosta/private-readthedocs.org,safwanrahman/readthedocs.org,dirn/readthedocs.org,sunnyzwh/readthedocs.org,GovReady/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,alex/readthedocs.org,sunnyzwh/readthedocs.org,istresearch/readthedocs.org,takluyver/readthedocs.org,royalwang/readthedocs.org,asampat3090/readthedocs.org,soulshake/readthedocs.org,VishvajitP/readthedocs.org,espdev/readthedocs.org,GovReady/readthedocs.org,clarkperkins/readthedocs.org,agjohnson/readthedocs.org,michaelmcandrew/readthedocs.org,mhils/readthedocs.org,alex/readthedocs.org,cgourlay/readthedocs.org,alex/readthedocs.org,jerel/readthedocs.org,davidfischer/readthedocs.org,sunnyzwh/readthedocs.org,alex/readthedocs.org,clarkperkins/readthedocs.org,Carreau/readthedocs.org,kenshinthebattosai/readthedocs.org,Tazer/readthedocs.org,d0ugal/readthedocs.org,fujita-shintaro/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org,kenwang76/readthedocs.org,attakei/readthedocs-oauth,asampat3090/readthedocs.org,mhils/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,LukasBoersma/readthedocs.org,stevepiercy/readthedocs.org,attakei/readthedocs-oauth,gjtorikian/readthedocs.org,nyergler/pythonslides,wanghaven/readthedocs.org,attakei/readthedocs-oauth,wijerasa/readthedocs.org,kenshinthebattosai/readthedocs.org,espdev/readthedocs.org | ---
+++
@@ -13,3 +13,8 @@
SESSION_COOKIE_DOMAIN = None
HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
+try:
+ from local_settings import *
+except:
+ pass
+ |
14d170eece4e8bb105f5316fb0c6e672a3253b08 | py3flowtools/flowtools_wrapper.py | py3flowtools/flowtools_wrapper.py | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
def FlowToolsLog(file_path):
with io.open(file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(file_path)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
| # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
class FlowToolsLog(object):
def __init__(self, file_path):
self._file_path = file_path
def __iter__(self):
self._parser = self._reader()
return self
def __next__(self):
return next(self._parser)
def next(self):
"""
next method included for compatibility with Python 2
"""
return self.__next__()
def _reader(self):
with io.open(self._file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(
self._file_path
)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
| Convert FlowToolsLog to a class | Convert FlowToolsLog to a class
| Python | mit | bbayles/py3flowtools | ---
+++
@@ -21,21 +21,40 @@
]
-def FlowToolsLog(file_path):
- with io.open(file_path, mode='rb') as flow_fd, \
- io.open(os.devnull, mode='wb') as DEVNULL:
- with subprocess.Popen(
- FLOW_EXPORT_ARGS,
- stdin=flow_fd,
- stdout=subprocess.PIPE,
- stderr=DEVNULL
- ) as proc:
- iterator = iter(proc.stdout.readline, b'')
- try:
- next(iterator)
- except StopIteration:
- msg = 'Could not extract data from {}'.format(file_path)
- raise IOError(msg)
- for line in iterator:
- parsed_line = FlowLine(line)
- yield parsed_line
+class FlowToolsLog(object):
+ def __init__(self, file_path):
+ self._file_path = file_path
+
+ def __iter__(self):
+ self._parser = self._reader()
+ return self
+
+ def __next__(self):
+ return next(self._parser)
+
+ def next(self):
+ """
+ next method included for compatibility with Python 2
+ """
+ return self.__next__()
+
+ def _reader(self):
+ with io.open(self._file_path, mode='rb') as flow_fd, \
+ io.open(os.devnull, mode='wb') as DEVNULL:
+ with subprocess.Popen(
+ FLOW_EXPORT_ARGS,
+ stdin=flow_fd,
+ stdout=subprocess.PIPE,
+ stderr=DEVNULL
+ ) as proc:
+ iterator = iter(proc.stdout.readline, b'')
+ try:
+ next(iterator)
+ except StopIteration:
+ msg = 'Could not extract data from {}'.format(
+ self._file_path
+ )
+ raise IOError(msg)
+ for line in iterator:
+ parsed_line = FlowLine(line)
+ yield parsed_line |
5b6bd6cacc7032bc6a830707374b1448861e5d08 | plugin.py | plugin.py | import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.get('ignored_packages', [])
if 'PHP' not in ignored_packages:
ignored_packages.append('PHP')
settings.set('ignored_packages', ignored_packages)
sublime.save_settings('Preferences.sublime-settings')
| import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.get('ignored_packages', [])
if 'PHP' not in ignored_packages:
ignored_packages.append('PHP')
ignored_packages.sort()
settings.set('ignored_packages', ignored_packages)
sublime.save_settings('Preferences.sublime-settings')
| Sort ignored packages when adding native PHP package | Sort ignored packages when adding native PHP package
| Python | bsd-3-clause | gerardroche/sublime-php-grammar,gerardroche/sublime-php-grammar | ---
+++
@@ -11,5 +11,6 @@
if 'PHP' not in ignored_packages:
ignored_packages.append('PHP')
+ ignored_packages.sort()
settings.set('ignored_packages', ignored_packages)
sublime.save_settings('Preferences.sublime-settings') |
76e766998984da126de4cb6121c07690fbdeeba1 | pystil/data/graph/line.py | pystil/data/graph/line.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria == 'unique' else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria in ('unique', 'new') else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
| Fix the new/unique visits (at least!) | Fix the new/unique visits (at least!)
| Python | bsd-3-clause | Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil | ---
+++
@@ -14,7 +14,7 @@
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
- if criteria == 'unique' else count(1).label("count"))
+ if criteria in ('unique', 'new') else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
|
268467c5eb12e92a031d22e3e0515e9d6fc264b7 | ofgem_certificates.py | ofgem_certificates.py | #!/usr/bin/env python
# coding=utf-8
#
# Copyright 2013 david reid <zathrasorama@gmail.com>
#
# 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.
#
__author__ = 'david reid'
__version__ = '0.1'
import argparse
from Ofgem.certificate import OfgemCertificateData
def do_search(month, year):
ocd = OfgemCertificateData(month = month, year = year)
if ocd.get_data():
for c in ocd.certificates:
print c.as_string()
else:
print "No certificates returned."
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Get details of a station by accreditation number')
# parser.add_argument('accreditation', action='store', help='Accreditation number to search for')
args = parser.parse_args()
do_search(9, 2012)
| #!/usr/bin/env python
# coding=utf-8
#
# Copyright 2013 david reid <zathrasorama@gmail.com>
#
# 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.
#
__author__ = 'david reid'
__version__ = '0.1'
import argparse
from Ofgem.certificate import OfgemCertificateData
def do_search(month, year):
ocd = OfgemCertificateData(month = month, year = year)
if ocd.get_data():
for c in ocd.certificates:
print c.as_string()
else:
print "No certificates returned."
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Get Ofgem certificates for a given month & year')
parser.add_argument('month', type=int, action='store', help='Month')
parser.add_argument('year', type=int, action='store', help='Year')
args = parser.parse_args()
do_search(args.month, args.year)
| Update the certificate script to accept month & year | Update the certificate script to accept month & year
| Python | unlicense | zathras777/pywind,zathras777/pywind | ---
+++
@@ -32,9 +32,10 @@
print "No certificates returned."
if __name__ == '__main__':
- parser = argparse.ArgumentParser(description='Get details of a station by accreditation number')
-# parser.add_argument('accreditation', action='store', help='Accreditation number to search for')
+ parser = argparse.ArgumentParser(description='Get Ofgem certificates for a given month & year')
+ parser.add_argument('month', type=int, action='store', help='Month')
+ parser.add_argument('year', type=int, action='store', help='Year')
args = parser.parse_args()
- do_search(9, 2012)
+ do_search(args.month, args.year) |
695b3f628b56cd1dbe050f07692559ff3685290c | templatefinder/__init__.py | templatefinder/__init__.py | from __future__ import absolute_import
from .utils import *
VERSION = (0, 5,)
| from __future__ import absolute_import
# this is required for setup.py to work
try:
from .utils import *
except ImportError:
pass
VERSION = (0, 5, 1,)
| Fix setup.py for installs without Django | Fix setup.py for installs without Django
| Python | bsd-2-clause | TyMaszWeb/django-template-finder | ---
+++
@@ -1,6 +1,10 @@
from __future__ import absolute_import
-from .utils import *
+# this is required for setup.py to work
+try:
+ from .utils import *
+except ImportError:
+ pass
-VERSION = (0, 5,)
+VERSION = (0, 5, 1,) |
8d604d20562c8e90a938986976715e165aa98a53 | tests/test_rmd_to_ipynb.py | tests/test_rmd_to_ipynb.py | import nbrmd
import pytest
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
Test that writing the notebook with ipynb, and read again, yields identify
:param file:
:return:
"""
with open(nb_file) as fp:
rmd = fp.read()
nb = nbrmd.reads(rmd)
rmd2 = nbrmd.writes(nb)
assert rmd == rmd2
| import nbrmd
import pytest
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
Test that writing the notebook with ipynb, and read again, yields identity
:param file:
:return:
"""
with open(nb_file) as fp:
rmd = fp.read()
nb = nbrmd.reads(rmd)
rmd2 = nbrmd.writes(nb)
assert rmd == rmd2
| Fix typo identified by @tgy | Fix typo identified by @tgy
| Python | mit | mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext | ---
+++
@@ -4,7 +4,7 @@
@pytest.mark.parametrize('nb_file', ['ioslides.Rmd', 'chunk_options.Rmd'])
def test_identity_write_read(nb_file):
"""
- Test that writing the notebook with ipynb, and read again, yields identify
+ Test that writing the notebook with ipynb, and read again, yields identity
:param file:
:return:
""" |
a764e58549284b8af1b3978676b8ee121fd918e3 | thecure/levels/__init__.py | thecure/levels/__init__.py | from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Cliff]
#return [Overworld, Cliff]
| from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Overworld, Cliff]
| Set the overworld as the default level again. | Set the overworld as the default level again.
| Python | mit | chipx86/the-cure | ---
+++
@@ -4,5 +4,4 @@
def get_levels():
- return [Cliff]
- #return [Overworld, Cliff]
+ return [Overworld, Cliff] |
e8cfb78df42021097e54009c5b724c1d176822bc | sale_analytic_cost/__openerp__.py | sale_analytic_cost/__openerp__.py | # -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Sale Analytic Cost',
"version": "8.0.1.0.0",
"license": 'AGPL-3',
"author": 'AvanzOSC,'
'Serv. Tecnol. Avanzados - Pedro M. Baeza',
'website': "http://www.odoomrp.com",
"contributors": [
"Ainara Galdona <ainaragaldona@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <anajuaristi@avanzosc.es>",
],
'category': 'Sales',
'depends': ['sale',
'account',
'mrp_production_project_estimated_cost'],
'data': [],
'installable': True,
}
| # -*- coding: utf-8 -*-
# (c) 2015 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Sale Analytic Cost',
"version": "8.0.1.0.0",
"license": 'AGPL-3',
"author": 'AvanzOSC,'
'Serv. Tecnol. Avanzados - Pedro M. Baeza',
'website': "http://www.odoomrp.com",
"contributors": [
"Ainara Galdona <ainaragaldona@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <anajuaristi@avanzosc.es>",
],
'category': 'Sales',
'depends': ['sale',
'account',
'mrp_production_estimated_cost'],
'data': [],
'installable': True,
}
| Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost". | [FIX] sale_analytic_cost: Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost".
| Python | agpl-3.0 | Daniel-CA/odoo-addons,alfredoavanzosc/odoo-addons,mikelarre/hr-addons,Daniel-CA/odoo-addons,esthermm/odoo-addons,agaldona/odoo-addons,alfredoavanzosc/odoo-addons,esthermm/odoo-addons,agaldona/odoo-addons,agaldona/odoo-addons,esthermm/odoo-addons,Daniel-CA/odoo-addons | ---
+++
@@ -17,7 +17,7 @@
'category': 'Sales',
'depends': ['sale',
'account',
- 'mrp_production_project_estimated_cost'],
+ 'mrp_production_estimated_cost'],
'data': [],
'installable': True,
} |
9b239f3484f3ec3e03ad1fda2a76d35852f662e6 | _releng/deploy.py | _releng/deploy.py | #!/usr/bin/env python3
import os
import subprocess
PUBLIC_URL = "https://frida.re"
BUCKET_URI = "s3://frida.re"
MAX_PURGES_PER_REQUEST = 30
def main():
repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
urls = []
listing = subprocess.check_output([
"s3cmd",
"ls",
"-r",
BUCKET_URI
]).decode('utf-8')
lines = listing.rstrip().split("\n")
for line in lines:
path = line[line.index(BUCKET_URI) + len(BUCKET_URI):]
urls.append(PUBLIC_URL + path)
subprocess.check_call([
"s3cmd",
"sync",
"--delete-removed",
"--acl-public",
os.path.join(repo_path, "_site") + os.sep,
BUCKET_URI + "/"
])
for batch in chop(urls, MAX_PURGES_PER_REQUEST):
subprocess.check_call(["cfcli", "purge"] + batch)
def chop(items, n):
for i in range(0, len(items), n):
yield items[i:i + n]
main()
| #!/usr/bin/env python3
import os
import subprocess
PUBLIC_URL = "https://frida.re"
BUCKET_URI = "s3://frida.re"
MAX_PURGES_PER_REQUEST = 30
def main():
repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
urls = []
listing = subprocess.check_output([
"s3cmd",
"ls",
"-r",
BUCKET_URI
]).decode('utf-8')
lines = listing.rstrip().split("\n")
for line in lines:
path = line[line.index(BUCKET_URI) + len(BUCKET_URI):]
urls += compute_urls_for_path(path)
subprocess.check_call([
"s3cmd",
"sync",
"--delete-removed",
"--acl-public",
os.path.join(repo_path, "_site") + os.sep,
BUCKET_URI + "/"
])
for batch in chop(urls, MAX_PURGES_PER_REQUEST):
subprocess.check_call(["cfcli", "purge"] + batch)
def compute_urls_for_path(path):
result = [PUBLIC_URL + path]
if path.endswith("/index.html"):
slash_index = path.rindex("/")
result += [
PUBLIC_URL + path[:slash_index],
PUBLIC_URL + path[:slash_index + 1]
]
return result
def chop(items, n):
for i in range(0, len(items), n):
yield items[i:i + n]
main()
| Make cache purging logic a bit more thorough | Make cache purging logic a bit more thorough
| Python | mit | frida/frida-website,frida/frida-website,frida/frida-website | ---
+++
@@ -21,7 +21,7 @@
lines = listing.rstrip().split("\n")
for line in lines:
path = line[line.index(BUCKET_URI) + len(BUCKET_URI):]
- urls.append(PUBLIC_URL + path)
+ urls += compute_urls_for_path(path)
subprocess.check_call([
"s3cmd",
@@ -36,6 +36,19 @@
subprocess.check_call(["cfcli", "purge"] + batch)
+def compute_urls_for_path(path):
+ result = [PUBLIC_URL + path]
+
+ if path.endswith("/index.html"):
+ slash_index = path.rindex("/")
+ result += [
+ PUBLIC_URL + path[:slash_index],
+ PUBLIC_URL + path[:slash_index + 1]
+ ]
+
+ return result
+
+
def chop(items, n):
for i in range(0, len(items), n):
yield items[i:i + n] |
fa42219c1e6763f3adfc1f6ede4080f769e476a6 | tests/test_mongo.py | tests/test_mongo.py | #!/usr/bin/env python
# coding=utf8
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name])
conn.drop_database(self.db_name)
| #!/usr/bin/env python
# coding=utf8
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
| Add database table name to MongoStore tests. | Add database table name to MongoStore tests.
| Python | mit | fmarczin/simplekv,karteek/simplekv,mbr/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv | ---
+++
@@ -18,5 +18,5 @@
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
- yield MongoStore(conn[db_name])
+ yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name) |
af6c31d09aef686ba896b2a2c74fbb88cc7f1be0 | tests/test_utils.py | tests/test_utils.py | #!/usr/bin/python2.5
#
# Copyright 2008 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
| #!/usr/bin/python2.5
#
# Copyright 2008 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
| Add a start and end method to MockRequest | Add a start and end method to MockRequest
| Python | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -19,12 +19,42 @@
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
+ '"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
+
+
+from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
+
+ Before using the object, start should be called, when done (and
+ before calling start on a new request), end should be called.
"""
+
def __init__(self, path=None):
- self.REQUEST = self.GET = self.POST = {}
+ """Creates a new empty request object.
+
+ self.REQUEST, self.GET and self.POST are set to an empty
+ dictionary, and path to the value specified.
+ """
+
+ self.REQUEST = {}
+ self.GET = {}
+ self.POST = {}
self.path = path
+
+ def start(self):
+ """Readies the core for a new request.
+ """
+
+ core = callback.getCore()
+ core.startNewRequest(self)
+
+ def end(self):
+ """Finishes up the current request.
+ """
+
+ core = callback.getCore()
+ core.endRequest(self, False) |
bff9e9c8c72be580bca4d82abf2d7931379f8ebf | scripts/get_services_to_deploy.py | scripts/get_services_to_deploy.py | #!/usr/bin/env python
import requests
import json
import sys
import argparse
parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed')
parser.add_argument('--url', help='URL where Monorail is located')
parser.add_argument('--pr', help='List of pull requests we will ask for')
args = parser.parse_args()
curl_uri = '/deploy-info?pr='
if (args.url):
if args.url.startswith('http'):
request_url = args.url+curl_uri
else:
request_url = 'http://'+args.url+curl_uri
else:
print 'We need an URL'
exit(1)
if (args.pr):
pull_requests = args.pr.split()
pull_requests = ",".join(pull_requests)
else:
print 'A list of PRs is needed'
exit(1)
try:
r = requests.get(request_url+pull_requests)
except:
print 'Something went wrong querying Monorail'
exit(2)
json_list = r.json()
services=json_list['services']
deploynotes=json_list['deployNotes']
if deploynotes == 'True':
print 'There are deployNotes so we cannot continue'
exit(3)
if len(services) == 0:
print 'There are not services defined so we cannot continue'
exit(4)
exit (0)
| #!/usr/bin/env python
import requests
import json
import sys
import argparse
parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed')
parser.add_argument('--url', help='URL where Monorail is located')
parser.add_argument('--pr', help='List of pull requests we will ask for')
args = parser.parse_args()
curl_uri = '/deploy-info?pr='
if (args.url):
if args.url.startswith('http'):
request_url = args.url+curl_uri
else:
request_url = 'http://'+args.url+curl_uri
else:
print 'We need an URL'
exit(1)
if (args.pr):
pull_requests = args.pr.split()
pull_requests = ",".join(pull_requests)
else:
print 'A list of PRs is needed'
exit(1)
try:
r = requests.get(request_url+pull_requests)
except:
print 'Something went wrong querying Monorail'
exit(2)
json_list = r.json()
services=json_list['services']
deploynotes=json_list['deployNotes']
print 'deploynotes:'
print deploynotes
print '\nservices:'
print services
if deploynotes == 'True':
print 'There are deployNotes so we cannot continue'
exit(3)
if len(services) == 0:
print 'There are not services defined so we cannot continue'
exit(4)
exit (0)
| Print variables for initial testing | Print variables for initial testing
| Python | mit | AudienseCo/monorail,AudienseCo/monorail | ---
+++
@@ -38,6 +38,11 @@
services=json_list['services']
deploynotes=json_list['deployNotes']
+print 'deploynotes:'
+print deploynotes
+print '\nservices:'
+print services
+
if deploynotes == 'True':
print 'There are deployNotes so we cannot continue'
exit(3) |
e3545cf444aea043fa892caeaff5a66ce893a0bb | misc/move-objects.py | misc/move-objects.py | from sys import argv
from axiom.store import Store
from entropy.store import ImmutableObject
from entropy.util import getAppStore
def moveObjects(appStore, start, limit=1000):
obj = None
for obj in appStore.query(
ImmutableObject,
ImmutableObject.storeID >= start,
limit=limit):
oldPath = obj.content
bucket = obj.contentDigest[:4]
newPath = appStore.newFilePath(
'objects', 'immutable', bucket,
'%s:%s' % (obj.hash, obj.contentDigest))
if not newPath.parent().exists():
newPath.parent().makedirs()
oldPath.moveTo(newPath)
obj.content = newPath
if obj is None:
print 'No objects selected'
else:
print 'Last object seen: %s' % (obj.storeID,)
siteStore = Store(argv[1])
appStore = getAppStore(siteStore)
appStore.transact(moveObjects, appStore, int(argv[2]))
| from sys import argv
from axiom.store import Store
from entropy.store import ImmutableObject
from entropy.util import getAppStore
def moveObjects(appStore, start, limit):
obj = None
for obj in appStore.query(
ImmutableObject,
ImmutableObject.storeID >= start,
limit=limit):
oldPath = obj.content
bucket = obj.contentDigest[:4]
newPath = appStore.newFilePath(
'objects', 'immutable', bucket,
'%s:%s' % (obj.hash, obj.contentDigest))
if not newPath.parent().exists():
newPath.parent().makedirs()
oldPath.moveTo(newPath)
obj.content = newPath
if obj is None:
print 'No objects selected'
else:
print 'Last object seen: %s' % (obj.storeID,)
siteStore = Store(argv[1])
appStore = getAppStore(siteStore)
limit = int(argv[3])
appStore.transact(moveObjects, appStore, int(argv[2]), int(argv[3]))
| Make limit a command-line parameter too. | Make limit a command-line parameter too.
| Python | mit | fusionapp/entropy | ---
+++
@@ -5,7 +5,7 @@
from entropy.util import getAppStore
-def moveObjects(appStore, start, limit=1000):
+def moveObjects(appStore, start, limit):
obj = None
for obj in appStore.query(
ImmutableObject,
@@ -28,4 +28,5 @@
siteStore = Store(argv[1])
appStore = getAppStore(siteStore)
-appStore.transact(moveObjects, appStore, int(argv[2]))
+limit = int(argv[3])
+appStore.transact(moveObjects, appStore, int(argv[2]), int(argv[3])) |
b1382e380016c9034826b090540275ce2bbe3a95 | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Request",
"ControlAssessment",
"Issue",
"DocumentationResponse",
"InterviewResponse",
"PopulationSampleResponse",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [
"DocumentationResponse",
"InterviewResponse",
"Response",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document"
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Relationship"
]
}
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Request",
"Comment",
"ControlAssessment",
"Issue",
"DocumentationResponse",
"InterviewResponse",
"PopulationSampleResponse",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [
"DocumentationResponse",
"InterviewResponse",
"Response",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document"
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Relationship"
]
}
| Allow Program Readers to view comments | Allow Program Readers to view comments
| Python | apache-2.0 | jmakov/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core | ---
+++
@@ -11,6 +11,7 @@
permissions = {
"read": [
"Request",
+ "Comment",
"ControlAssessment",
"Issue",
"DocumentationResponse", |
8773f652a1cf78299e3dd5ba9296ca2a50143caa | aiopg/__init__.py | aiopg/__init__.py | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.2'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
| import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.4.0a0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool)
| Revert master version to 0.4.0a0 | Revert master version to 0.4.0a0
| Python | bsd-2-clause | eirnym/aiopg,graingert/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,nerandell/aiopg | ---
+++
@@ -10,7 +10,7 @@
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
-__version__ = '0.3.2'
+__version__ = '0.4.0a0'
version = __version__ + ' , Python ' + sys.version
|
d0e7d3578fe79432ad2b2cc62be2203d4ff36014 | examples/charts/file/cat_heatmap.py | examples/charts/file/cat_heatmap.py | from bokeh.charts import HeatMap, output_file, show
from bokeh.sampledata.unemployment1948 import data
# pandas magic
df = data[data.columns[:-2]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()
output_file("cat_heatmap.html")
hm = HeatMap(df3, title="categorical heatmap", width=800)
show(hm) | from bokeh.charts import HeatMap, output_file, show
from bokeh.palettes import YlOrRd9 as palette
from bokeh.sampledata.unemployment1948 import data
# pandas magic
df = data[data.columns[:-1]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()
output_file("cat_heatmap.html")
palette = palette[::-1] # Reverse the color order so dark red is highest unemployment
hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette)
show(hm)
| Use all the months of the year and tweak palette. | Use all the months of the year and tweak palette.
- Picked a continuous palette and reversed as better for the data.
| Python | bsd-3-clause | abele/bokeh,laurent-george/bokeh,azjps/bokeh,josherick/bokeh,rs2/bokeh,timsnyder/bokeh,draperjames/bokeh,matbra/bokeh,ptitjano/bokeh,DuCorey/bokeh,awanke/bokeh,akloster/bokeh,xguse/bokeh,stonebig/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,stonebig/bokeh,CrazyGuo/bokeh,ericmjl/bokeh,rhiever/bokeh,caseyclements/bokeh,roxyboy/bokeh,maxalbert/bokeh,ericdill/bokeh,KasperPRasmussen/bokeh,maxalbert/bokeh,stuart-knock/bokeh,draperjames/bokeh,carlvlewis/bokeh,akloster/bokeh,srinathv/bokeh,timsnyder/bokeh,khkaminska/bokeh,gpfreitas/bokeh,bokeh/bokeh,dennisobrien/bokeh,rothnic/bokeh,Karel-van-de-Plassche/bokeh,deeplook/bokeh,PythonCharmers/bokeh,matbra/bokeh,ericmjl/bokeh,ahmadia/bokeh,justacec/bokeh,aiguofer/bokeh,muku42/bokeh,ChristosChristofidis/bokeh,matbra/bokeh,rothnic/bokeh,mindriot101/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,timothydmorton/bokeh,ChristosChristofidis/bokeh,philippjfr/bokeh,josherick/bokeh,rhiever/bokeh,roxyboy/bokeh,alan-unravel/bokeh,jakirkham/bokeh,timsnyder/bokeh,philippjfr/bokeh,ahmadia/bokeh,aavanian/bokeh,carlvlewis/bokeh,maxalbert/bokeh,muku42/bokeh,laurent-george/bokeh,justacec/bokeh,evidation-health/bokeh,laurent-george/bokeh,bsipocz/bokeh,DuCorey/bokeh,rs2/bokeh,saifrahmed/bokeh,quasiben/bokeh,justacec/bokeh,ptitjano/bokeh,saifrahmed/bokeh,jakirkham/bokeh,jplourenco/bokeh,ChinaQuants/bokeh,percyfal/bokeh,stonebig/bokeh,ericmjl/bokeh,daodaoliang/bokeh,eteq/bokeh,abele/bokeh,htygithub/bokeh,aiguofer/bokeh,khkaminska/bokeh,ahmadia/bokeh,stuart-knock/bokeh,htygithub/bokeh,paultcochrane/bokeh,jakirkham/bokeh,muku42/bokeh,srinathv/bokeh,alan-unravel/bokeh,philippjfr/bokeh,htygithub/bokeh,eteq/bokeh,bokeh/bokeh,ChinaQuants/bokeh,KasperPRasmussen/bokeh,daodaoliang/bokeh,eteq/bokeh,schoolie/bokeh,satishgoda/bokeh,aavanian/bokeh,carlvlewis/bokeh,PythonCharmers/bokeh,phobson/bokeh,josherick/bokeh,schoolie/bokeh,aiguofer/bokeh,daodaoliang/bokeh,jplourenco/bokeh,roxyboy/bokeh,Karel-van-de-Plassche/bokeh,jplourenco/bokeh,tacaswell/bokeh,azjps/bokeh,quasiben/bokeh,dennisobrien/bokeh,saifrahmed/bokeh,mindriot101/bokeh,azjps/bokeh,xguse/bokeh,bsipocz/bokeh,caseyclements/bokeh,clairetang6/bokeh,paultcochrane/bokeh,saifrahmed/bokeh,stuart-knock/bokeh,gpfreitas/bokeh,dennisobrien/bokeh,alan-unravel/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,xguse/bokeh,jplourenco/bokeh,PythonCharmers/bokeh,PythonCharmers/bokeh,schoolie/bokeh,philippjfr/bokeh,gpfreitas/bokeh,xguse/bokeh,timsnyder/bokeh,deeplook/bokeh,khkaminska/bokeh,evidation-health/bokeh,paultcochrane/bokeh,aiguofer/bokeh,aavanian/bokeh,DuCorey/bokeh,msarahan/bokeh,stonebig/bokeh,ChristosChristofidis/bokeh,abele/bokeh,rhiever/bokeh,draperjames/bokeh,bsipocz/bokeh,ericdill/bokeh,rhiever/bokeh,awanke/bokeh,azjps/bokeh,muku42/bokeh,srinathv/bokeh,timsnyder/bokeh,satishgoda/bokeh,satishgoda/bokeh,eteq/bokeh,msarahan/bokeh,daodaoliang/bokeh,rothnic/bokeh,awanke/bokeh,maxalbert/bokeh,evidation-health/bokeh,ericmjl/bokeh,jakirkham/bokeh,ericdill/bokeh,ChinaQuants/bokeh,satishgoda/bokeh,Karel-van-de-Plassche/bokeh,paultcochrane/bokeh,CrazyGuo/bokeh,deeplook/bokeh,akloster/bokeh,caseyclements/bokeh,draperjames/bokeh,aavanian/bokeh,deeplook/bokeh,ChinaQuants/bokeh,CrazyGuo/bokeh,rs2/bokeh,bokeh/bokeh,clairetang6/bokeh,dennisobrien/bokeh,timothydmorton/bokeh,rs2/bokeh,ahmadia/bokeh,dennisobrien/bokeh,matbra/bokeh,justacec/bokeh,mindriot101/bokeh,timothydmorton/bokeh,akloster/bokeh,clairetang6/bokeh,awanke/bokeh,tacaswell/bokeh,schoolie/bokeh,evidation-health/bokeh,ptitjano/bokeh,schoolie/bokeh,htygithub/bokeh,alan-unravel/bokeh,ptitjano/bokeh,bokeh/bokeh,stuart-knock/bokeh,srinathv/bokeh,rs2/bokeh,ChristosChristofidis/bokeh,carlvlewis/bokeh,mindriot101/bokeh,msarahan/bokeh,gpfreitas/bokeh,KasperPRasmussen/bokeh,roxyboy/bokeh,percyfal/bokeh,aavanian/bokeh,CrazyGuo/bokeh,percyfal/bokeh,caseyclements/bokeh,azjps/bokeh,msarahan/bokeh,ericdill/bokeh,ptitjano/bokeh,percyfal/bokeh,aiguofer/bokeh,clairetang6/bokeh,bokeh/bokeh,josherick/bokeh,bsipocz/bokeh,phobson/bokeh,abele/bokeh,timothydmorton/bokeh,percyfal/bokeh,DuCorey/bokeh,quasiben/bokeh,tacaswell/bokeh,khkaminska/bokeh,phobson/bokeh,tacaswell/bokeh,rothnic/bokeh,draperjames/bokeh,philippjfr/bokeh,ericmjl/bokeh,laurent-george/bokeh | ---
+++
@@ -1,14 +1,16 @@
from bokeh.charts import HeatMap, output_file, show
+from bokeh.palettes import YlOrRd9 as palette
from bokeh.sampledata.unemployment1948 import data
# pandas magic
-df = data[data.columns[:-2]]
+df = data[data.columns[:-1]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()
output_file("cat_heatmap.html")
-hm = HeatMap(df3, title="categorical heatmap", width=800)
+palette = palette[::-1] # Reverse the color order so dark red is highest unemployment
+hm = HeatMap(df3, title="categorical heatmap", width=800, palette=palette)
show(hm) |
a7c5c9d27d29e14ebb2d314890b40eab318501ac | dialogos/admin.py | dialogos/admin.py | from django.contrib import admin
from dialogos.models import Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ['author', 'content_type', 'public']
list_filter = ['public', 'content_type']
admin.site.register(Comment, CommentAdmin)
| from django.contrib import admin
from dialogos.models import Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ["author", "content_type", "public"]
list_filter = ["public", "content_type"]
admin.site.register(Comment, CommentAdmin)
| Update style to match Pinax conventions | Update style to match Pinax conventions | Python | mit | pinax/pinax-comments,rizumu/dialogos,GeoNode/geonode-dialogos,eldarion/dialogos,georgedorn/dialogos,pinax/pinax-comments | ---
+++
@@ -1,8 +1,11 @@
from django.contrib import admin
+
from dialogos.models import Comment
+
class CommentAdmin(admin.ModelAdmin):
- list_display = ['author', 'content_type', 'public']
- list_filter = ['public', 'content_type']
+ list_display = ["author", "content_type", "public"]
+ list_filter = ["public", "content_type"]
+
admin.site.register(Comment, CommentAdmin) |
c09465f6f5d70789ca01470015985cbbdb465db9 | problem_2/solution.py | problem_2/solution.py | from timeit import timeit
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
c = a + b
return s
print "sum_even_fibonacci_numbers_1: {0}".format(timeit("sum_even_fibonacci_numbers_1()", "from __main__ import sum_even_fibonacci_numbers_1;"))
print "sum_even_fibonacci_numbers_2: {0}".format(timeit("sum_even_fibonacci_numbers_2()", "from __main__ import sum_even_fibonacci_numbers_2;"))
| import time
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
f2, f1 = f1, f1 + f2
if f2 % 2 == 0:
s += f2
return s
def sum_even_fibonacci_numbers_2():
s, a, b = 0, 1, 1
c = a + b
while c < 4000000:
s += c
a = b + c
b = a + c
c = a + b
return s
t1 = time.time()
sum_even_fibonacci_numbers_1()
t2 = time.time()
print "=> sum_even_fibonacci_numbers_1(): %fs" % (t2 - t1)
t1 = time.time()
sum_even_fibonacci_numbers_2()
t2 = time.time()
print "=> sum_even_fibonacci_numbers_2(): %fs" % (t2 - t1)
| Add better timing for python implementation of problem 2 | Add better timing for python implementation of problem 2
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler | ---
+++
@@ -1,4 +1,4 @@
-from timeit import timeit
+import time
def sum_even_fibonacci_numbers_1():
f1, f2, s, = 0, 1, 0,
while f2 < 4000000:
@@ -15,5 +15,11 @@
b = a + c
c = a + b
return s
-print "sum_even_fibonacci_numbers_1: {0}".format(timeit("sum_even_fibonacci_numbers_1()", "from __main__ import sum_even_fibonacci_numbers_1;"))
-print "sum_even_fibonacci_numbers_2: {0}".format(timeit("sum_even_fibonacci_numbers_2()", "from __main__ import sum_even_fibonacci_numbers_2;"))
+t1 = time.time()
+sum_even_fibonacci_numbers_1()
+t2 = time.time()
+print "=> sum_even_fibonacci_numbers_1(): %fs" % (t2 - t1)
+t1 = time.time()
+sum_even_fibonacci_numbers_2()
+t2 = time.time()
+print "=> sum_even_fibonacci_numbers_2(): %fs" % (t2 - t1) |
a612a245937781e86391e5c3ec8a740f36b405ce | problems/19/Solver.py | problems/19/Solver.py | class Solver:
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
elves = list(range(1, start_number + 1))
current_elf_index = 0
while len(elves) > 1:
jump_distance = len(elves) // 2
target_elf = jump_distance + current_elf_index
if target_elf >= len(elves):
del elves[target_elf - len(elves)]
current_elf_index -= 1
else:
del elves[target_elf]
current_elf_index += 1
current_elf_index %= len(elves)
return elves[current_elf_index]
| class Solver:
def __init__(self):
self.next_elves = {}
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
self.next_elves = {index: index + 1 for index in range(start_number)}
self.next_elves[start_number - 1] = 0
current_elf_index = 0
elves_remaining = start_number
while elves_remaining > 1:
target_elf = current_elf_index
jump_distance = elves_remaining // 2
for i in range(jump_distance):
previous_elf = target_elf
target_elf = self.next_elves[target_elf]
# remove target elf
self.delete_target_elf(previous_elf, target_elf)
current_elf_index = self.next_elves[current_elf_index]
elves_remaining -= 1
return current_elf_index + 1
def delete_target_elf(self, previous_elf, target_elf):
next_elf = self.next_elves[target_elf]
self.next_elves[previous_elf] = next_elf
target_elf %= len(self.next_elves)
| Refactor to use linked list | Refactor to use linked list
| Python | mit | tmct/adventOfCode2016 | ---
+++
@@ -1,4 +1,7 @@
class Solver:
+ def __init__(self):
+ self.next_elves = {}
+
def solve(self, start_number):
recipient = 1
remaining = start_number
@@ -13,17 +16,25 @@
return recipient
def solve_b(self, start_number):
- elves = list(range(1, start_number + 1))
+ self.next_elves = {index: index + 1 for index in range(start_number)}
+ self.next_elves[start_number - 1] = 0
current_elf_index = 0
- while len(elves) > 1:
- jump_distance = len(elves) // 2
- target_elf = jump_distance + current_elf_index
- if target_elf >= len(elves):
- del elves[target_elf - len(elves)]
- current_elf_index -= 1
- else:
- del elves[target_elf]
- current_elf_index += 1
- current_elf_index %= len(elves)
+ elves_remaining = start_number
+ while elves_remaining > 1:
+ target_elf = current_elf_index
+ jump_distance = elves_remaining // 2
+ for i in range(jump_distance):
+ previous_elf = target_elf
+ target_elf = self.next_elves[target_elf]
- return elves[current_elf_index]
+ # remove target elf
+ self.delete_target_elf(previous_elf, target_elf)
+
+ current_elf_index = self.next_elves[current_elf_index]
+ elves_remaining -= 1
+ return current_elf_index + 1
+
+ def delete_target_elf(self, previous_elf, target_elf):
+ next_elf = self.next_elves[target_elf]
+ self.next_elves[previous_elf] = next_elf
+ target_elf %= len(self.next_elves) |
44191360586beeec04a4abc8a4aa262bc5ec052d | odinweb/exceptions.py | odinweb/exceptions.py | # -*- coding: utf-8 -*-
"""
Exceptions
~~~~~~~~~~
"""
from .constants import HTTPStatus
from .resources import Error
class ImmediateHttpResponse(Exception):
"""
A response that should be returned immediately.
"""
def __init__(self, resource, status=HTTPStatus.OK, headers=None):
self.resource = resource
self.status = status
self.headers = headers
class HttpError(ImmediateHttpResponse):
"""
An error response that should be returned immediately.
"""
def __init__(self, status, code, message, developer_message=None, meta=None, headers=None):
super(HttpError, self).__init__(
Error(status, code, message, developer_message, meta),
status, headers
)
class PermissionDenied(HttpError):
"""
Permission to access the specified resource is denied.
"""
def __init__(self, message=None, developer_method=None, headers=None):
super(PermissionDenied, self).__init__(
HTTPStatus.FORBIDDEN, 40300, message or HTTPStatus.FORBIDDEN.description,
developer_method, None, headers
)
| # -*- coding: utf-8 -*-
"""
Exceptions
~~~~~~~~~~
"""
from .constants import HTTPStatus
from .resources import Error
__all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied')
class ImmediateHttpResponse(Exception):
"""
A response that should be returned immediately.
"""
def __init__(self, resource, status=HTTPStatus.OK, headers=None):
self.resource = resource
self.status = status
self.headers = headers
class HttpError(ImmediateHttpResponse):
"""
An error response that should be returned immediately.
"""
def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None):
super(HttpError, self).__init__(
Error.from_status(status, code_index, message, developer_message, meta), status, headers
)
class PermissionDenied(HttpError):
"""
Permission to access the specified resource is denied.
"""
def __init__(self, message=None, developer_method=None, headers=None):
super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers)
| Refactor HttpError to use Error.from_status helper | Refactor HttpError to use Error.from_status helper
| Python | bsd-3-clause | python-odin/odinweb,python-odin/odinweb | ---
+++
@@ -6,6 +6,8 @@
"""
from .constants import HTTPStatus
from .resources import Error
+
+__all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied')
class ImmediateHttpResponse(Exception):
@@ -22,10 +24,9 @@
"""
An error response that should be returned immediately.
"""
- def __init__(self, status, code, message, developer_message=None, meta=None, headers=None):
+ def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None):
super(HttpError, self).__init__(
- Error(status, code, message, developer_message, meta),
- status, headers
+ Error.from_status(status, code_index, message, developer_message, meta), status, headers
)
@@ -34,7 +35,4 @@
Permission to access the specified resource is denied.
"""
def __init__(self, message=None, developer_method=None, headers=None):
- super(PermissionDenied, self).__init__(
- HTTPStatus.FORBIDDEN, 40300, message or HTTPStatus.FORBIDDEN.description,
- developer_method, None, headers
- )
+ super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers) |
7ae151e277d2cb03037d40e1598b190ba4736433 | dthm4kaiako/events/views.py | dthm4kaiako/events/views.py | """Views for events application."""
from django.views import generic
from django.utils.timezone import now
from events.models import (
Event,
Location,
)
class HomeView(generic.TemplateView):
"""View for event homepage."""
template_name = 'events/home.html'
def get_context_data(self, **kwargs):
"""Provide the context data for the event homepage view.
Returns:
Dictionary of context data.
"""
context = super().get_context_data(**kwargs)
future_events = Event.objects.filter(end__gte=now()).order_by('start')
context['events'] = future_events[:10]
context['locations'] = Location.objects.filter(events__in=future_events).distinct()
return context
| """Views for events application."""
from django.views import generic
from django.utils.timezone import now
from events.models import (
Event,
Location,
)
class HomeView(generic.TemplateView):
"""View for event homepage."""
template_name = 'events/home.html'
def get_context_data(self, **kwargs):
"""Provide the context data for the event homepage view.
Returns:
Dictionary of context data.
"""
context = super().get_context_data(**kwargs)
future_events = Event.objects.filter(end__gte=now()).order_by('start').prefetch_related(
'organisers',
'locations',
'sponsors',
).select_related(
'series',
)
context['events'] = future_events[:10]
context['locations'] = Location.objects.filter(events__in=future_events).distinct()
return context
| Reduce SQL queries for events homepage | Reduce SQL queries for events homepage
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -20,7 +20,13 @@
Dictionary of context data.
"""
context = super().get_context_data(**kwargs)
- future_events = Event.objects.filter(end__gte=now()).order_by('start')
+ future_events = Event.objects.filter(end__gte=now()).order_by('start').prefetch_related(
+ 'organisers',
+ 'locations',
+ 'sponsors',
+ ).select_related(
+ 'series',
+ )
context['events'] = future_events[:10]
context['locations'] = Location.objects.filter(events__in=future_events).distinct()
return context |
33f47fc9aff361d0cea9557e6470d505a352e5f0 | forms.py | forms.py | from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
class TeamForm(Form):
number = IntegerField("Number", [validators.Required(),
validators.NumberRange(min=1, max=99999)])
name = TextField("Name", [validators.Required(),
validators.Length(min=1, max=50)])
affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)])
city = TextField("City", [validators.Length(min=1, max=50)])
state = TextField("State", [validators.Length(min=2, max=2)])
# TODO add validation
class ScoreForm(Form):
team_id = SelectField(u'Team', coerce=int)
round_number = SelectField(u'Round', choices=[(1, '1'), (2, '2'), (3, '3')], coerce=int)
tree_branch_is_closer = BooleanField(u'Is tree branch closer to mat than power lines', default=False)
tree_branch_is_intact = BooleanField(u'Is tree branch model intact', default=False)
cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'),
('1', 'Yellow only'),
('2', 'Light blue')])
| from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
from models import RobotScore
class TeamForm(Form):
number = IntegerField("Number", [validators.Required(),
validators.NumberRange(min=1, max=99999)])
name = TextField("Name", [validators.Required(),
validators.Length(min=1, max=50)])
affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)])
city = TextField("City", [validators.Length(min=1, max=50)])
state = TextField("State", [validators.Length(min=2, max=2)])
# TODO add validation
class ScoreForm(Form):
team_id = SelectField(u'Team', coerce=int)
round_number = SelectField(u'Round', choices=[(1, '1'), (2, '2'), (3, '3')], coerce=int)
tree_branch_is_closer = BooleanField(u'Is tree branch closer to mat than power lines', default=False)
tree_branch_is_intact = BooleanField(u'Is tree branch model intact', default=False)
cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'),
('1', 'Yellow only'),
('2', 'Light blue')])
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.score = None
def validate(self):
rv = Form.validate(self)
if not rv:
return False
score = RobotScore.query.filter_by(round_number=self.round_number.data).first()
if score is not None:
self.round_number.errors.append("Score already exists for this round")
return False
self.score = score
return True
| Validate that score doesn't already exist for a round when submitting the form | Validate that score doesn't already exist for a round when submitting the form
| Python | mit | rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy | ---
+++
@@ -1,6 +1,7 @@
from flask.ext.wtf import Form
from wtforms import SelectField, BooleanField, IntegerField, TextField, \
validators
+from models import RobotScore
class TeamForm(Form):
@@ -22,3 +23,20 @@
cargo_plane_location = SelectField(u'Cargo plane location', choices=[('0', 'None'),
('1', 'Yellow only'),
('2', 'Light blue')])
+
+ def __init__(self, *args, **kwargs):
+ Form.__init__(self, *args, **kwargs)
+ self.score = None
+
+ def validate(self):
+ rv = Form.validate(self)
+ if not rv:
+ return False
+
+ score = RobotScore.query.filter_by(round_number=self.round_number.data).first()
+ if score is not None:
+ self.round_number.errors.append("Score already exists for this round")
+ return False
+
+ self.score = score
+ return True |
08a7389e5be0d3f7a9e6c4e12b13f82da50480b1 | reference/gittaggers.py | reference/gittaggers.py | from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct', '..']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
| from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
| Fix Python packaging to use correct git log for package time/version stamps (2nd try) | Fix Python packaging to use correct git log for package time/version stamps (2nd try)
| Python | apache-2.0 | chapmanb/cwltool,brainstorm/common-workflow-language,curoverse/common-workflow-language,chapmanb/cwltool,hmenager/common-workflow-language,common-workflow-language/cwltool,foreveremain/common-workflow-language,StarvingMarvin/common-workflow-language,jeremiahsavage/cwltool,foreveremain/common-workflow-language,satra/common-workflow-language,common-workflow-language/common-workflow-language,curoverse/common-workflow-language,SciDAP/cwltool,mr-c/common-workflow-language,foreveremain/common-workflow-language,chapmanb/cwltool,mr-c/common-workflow-language,SciDAP/cwltool,dleehr/common-workflow-language,common-workflow-language/common-workflow-language,dleehr/common-workflow-language,chapmanb/cwltool,stain/common-workflow-language,slnovak/common-workflow-language,common-workflow-language/common-workflow-language,slnovak/common-workflow-language,dleehr/cwltool,stain/common-workflow-language,satra/common-workflow-language,guillermo-carrasco/common-workflow-language,hmenager/common-workflow-language,SciDAP/cwltool,dleehr/cwltool,StarvingMarvin/common-workflow-language,dleehr/common-workflow-language,dleehr/common-workflow-language,guillermo-carrasco/common-workflow-language,stain/common-workflow-language,jeremiahsavage/cwltool,slnovak/common-workflow-language,hmenager/common-workflow-language,jeremiahsavage/cwltool,stain/common-workflow-language,guillermo-carrasco/common-workflow-language,jeremiahsavage/cwltool,SciDAP/cwltool,hmenager/common-workflow-language,ohsu-computational-biology/common-workflow-language,brainstorm/common-workflow-language,common-workflow-language/common-workflow-language,common-workflow-language/cwltool,StarvingMarvin/common-workflow-language,ohsu-computational-biology/common-workflow-language,StarvingMarvin/common-workflow-language,brainstorm/common-workflow-language,dleehr/cwltool,satra/common-workflow-language,common-workflow-language/cwltool,mr-c/common-workflow-language,dleehr/cwltool,ohsu-computational-biology/common-workflow-language | ---
+++
@@ -11,7 +11,7 @@
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
- '--format=format:%ct', '..']).strip()
+ '--format=format:%ct']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self): |
834349fc6cc2f6d281f03f339dab116b897615fc | knowledge_repo/postprocessors/format_checks.py | knowledge_repo/postprocessors/format_checks.py | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
| from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, _ in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
for field, typ, _ in \
HEADER_REQUIRED_FIELD_TYPES + HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
header_field = headers[field]
assert isinstance(header_field, typ), \
f"Value for field `{field}` is of type " + \
f"{type(header_field)}, and needs to be of type {typ}."
| Refactor to avoid duplicate code | Refactor to avoid duplicate code
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | ---
+++
@@ -8,14 +8,13 @@
def process(self, kp):
headers = kp.headers
- for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
+ for field, typ, _ in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
- assert isinstance(headers[field], typ), \
- f"Value for field `{field}` is of type " + \
- f"{type(headers[field])}, and needs to be of type {typ}."
- for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
+ for field, typ, _ in \
+ HEADER_REQUIRED_FIELD_TYPES + HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
- assert isinstance(headers[field], typ), \
+ header_field = headers[field]
+ assert isinstance(header_field, typ), \
f"Value for field `{field}` is of type " + \
- f"{type(headers[field])}, and needs to be of type {typ}."
+ f"{type(header_field)}, and needs to be of type {typ}." |
5d2110059731069a6a29a31d2b9f02bb2743e90b | scripts/cleanup-images.py | scripts/cleanup-images.py | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.read('/srv/rbuilder/rbuilder.conf')
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fetchall()]
for baseDir, dirs, files in os.walk('/srv/rbuilder/finished-images'):
if len(baseDir.split(os.path.sep)) == 6:
os.chown(baseDir, isogenUid, apacheGid)
os.chmod(baseDir, os.stat(baseDir)[0] & 0777 | 0020)
for file in files:
path = os.path.join(baseDir, file)
if file not in imageFiles:
os.unlink(path)
else:
os.chown(path, isogenUid, apacheGid)
| #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.read(config.RBUILDER_CONFIG)
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fetchall()]
for baseDir, dirs, files in os.walk(cfg.imagesPath):
if len(baseDir.split(os.path.sep)) == 6:
os.chown(baseDir, isogenUid, apacheGid)
os.chmod(baseDir, os.stat(baseDir)[0] & 0777 | 0020)
for file in files:
path = os.path.join(baseDir, file)
if file not in imageFiles:
os.unlink(path)
else:
os.chown(path, isogenUid, apacheGid)
| Kill off another hardcoded path | Kill off another hardcoded path
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -14,13 +14,13 @@
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
-cfg.read('/srv/rbuilder/rbuilder.conf')
+cfg.read(config.RBUILDER_CONFIG)
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fetchall()]
-for baseDir, dirs, files in os.walk('/srv/rbuilder/finished-images'):
+for baseDir, dirs, files in os.walk(cfg.imagesPath):
if len(baseDir.split(os.path.sep)) == 6:
os.chown(baseDir, isogenUid, apacheGid)
os.chmod(baseDir, os.stat(baseDir)[0] & 0777 | 0020) |
eabc02aed1cd5a109554f48bfb82f185e392c404 | remo/base/middleware.py | remo/base/middleware.py | from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
class RegisterMiddleware(object):
"""Middleware to enforce users to complete registration.
When a user logins and has the registration_complete field in his
userprofile set to False the middleware will automatically
redirect him to edit profile with the appropriate message
displayed. The only allowed destinations are the edit profile and
the signout page.
"""
def process_request(self, request):
if (request.user.is_authenticated() and not
request.user.userprofile.registration_complete and not
request.user.groups.filter(name='Mozillians').exists()):
allow_urls = [
reverse('oidc_authentication_init'),
reverse('oidc_authentication_callback'),
reverse('profiles_edit',
kwargs={'display_name':
request.user.userprofile.display_name})]
if (not request.path.startswith(settings.STATIC_URL) and
not filter(lambda x: request.path == x, allow_urls)):
messages.warning(request, 'Please complete your '
'profile before proceeding.')
return redirect('profiles_edit',
request.user.userprofile.display_name)
| from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
class RegisterMiddleware(object):
"""Middleware to enforce users to complete registration.
When a user logins and has the registration_complete field in his
userprofile set to False the middleware will automatically
redirect him to edit profile with the appropriate message
displayed. The only allowed destinations are the edit profile and
the signout page.
"""
def process_request(self, request):
if (request.user.is_authenticated() and not
request.user.userprofile.registration_complete and not
request.user.groups.filter(name='Mozillians').exists()):
allow_urls = [
reverse('oidc_authentication_init'),
reverse('oidc_authentication_callback'),
reverse('oidc_logout'),
reverse('profiles_edit',
kwargs={'display_name':
request.user.userprofile.display_name})]
if (not request.path.startswith(settings.STATIC_URL) and
not filter(lambda x: request.path == x, allow_urls)):
messages.warning(request, 'Please complete your '
'profile before proceeding.')
return redirect('profiles_edit',
request.user.userprofile.display_name)
| Add 'oidc_logout' in allowed urls. | Add 'oidc_logout' in allowed urls.
| Python | bsd-3-clause | flamingspaz/remo,akatsoulas/remo,mozilla/remo,Mte90/remo,flamingspaz/remo,akatsoulas/remo,Mte90/remo,Mte90/remo,flamingspaz/remo,mozilla/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,mozilla/remo,flamingspaz/remo,Mte90/remo,mozilla/remo | ---
+++
@@ -22,6 +22,7 @@
allow_urls = [
reverse('oidc_authentication_init'),
reverse('oidc_authentication_callback'),
+ reverse('oidc_logout'),
reverse('profiles_edit',
kwargs={'display_name':
request.user.userprofile.display_name})] |
d1afc8b673595accb854639b311bbdd49be56022 | server/LikeLines/debug.py | server/LikeLines/debug.py | """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all")
def clear_all():
mongo = current_app.mongo
mongo.db.userSessions.remove()
mongo.db.interactionSessions.remove()
return redirect(url_for('destroy_session'))
@debug_pages.route("/dump")
def dump_session():
mongo = current_app.mongo
return jsonify({
'userSessions': list(mongo.db.userSessions.find()),
'interactionSessions': list(mongo.db.interactionSessions.find()),
})
| """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for, request
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
if request.method == 'GET':
return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>'
else:
mongo = current_app.mongo
mongo.db.userSessions.remove()
mongo.db.interactionSessions.remove()
return redirect(url_for('destroy_session'))
@debug_pages.route("/dump")
def dump_session():
mongo = current_app.mongo
return jsonify({
'userSessions': list(mongo.db.userSessions.find()),
'interactionSessions': list(mongo.db.interactionSessions.find()),
})
| Make it harder to accidentally empty the database | Make it harder to accidentally empty the database
| Python | mit | ShinNoNoir/likelines-player,ShinNoNoir/likelines-player,ShinNoNoir/likelines-player | ---
+++
@@ -1,17 +1,20 @@
"""
Debug Blueprints.
"""
-from flask import Blueprint, current_app, redirect, jsonify, url_for
+from flask import Blueprint, current_app, redirect, jsonify, url_for, request
debug_pages = Blueprint('debug', __name__)
-@debug_pages.route("/clear_all")
+@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
- mongo = current_app.mongo
- mongo.db.userSessions.remove()
- mongo.db.interactionSessions.remove()
- return redirect(url_for('destroy_session'))
+ if request.method == 'GET':
+ return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>'
+ else:
+ mongo = current_app.mongo
+ mongo.db.userSessions.remove()
+ mongo.db.interactionSessions.remove()
+ return redirect(url_for('destroy_session'))
@debug_pages.route("/dump") |
5ab34396d4f494f884ddf98fb993bcf1b928216e | api/citations/urls.py | api/citations/urls.py | from django.conf.urls import url
from api.citations import views
urlpatterns = [
url(r'^$', views.CitationList.as_view(), name=views.CitationList.view_name),
url(r'^(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
]
| from django.conf.urls import url
from api.citations import views
urlpatterns = [
url(r'^styles/$', views.CitationList.as_view(), name=views.CitationList.view_name),
url(r'^styles/(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
]
| Add styles prefix to match api v1 | Add styles prefix to match api v1
| Python | apache-2.0 | mattclark/osf.io,chennan47/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,mfraezz/osf.io,caneruguz/osf.io,crcresearch/osf.io,sloria/osf.io,adlius/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,icereval/osf.io,saradbowman/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,acshi/osf.io,pattisdr/osf.io,caneruguz/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,hmoco/osf.io,pattisdr/osf.io,Nesiehr/osf.io,sloria/osf.io,mluo613/osf.io,mattclark/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,crcresearch/osf.io,cslzchen/osf.io,erinspace/osf.io,adlius/osf.io,cwisecarver/osf.io,mfraezz/osf.io,Nesiehr/osf.io,rdhyee/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,acshi/osf.io,laurenrevere/osf.io,binoculars/osf.io,aaxelb/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,brianjgeiger/osf.io,hmoco/osf.io,acshi/osf.io,baylee-d/osf.io,felliott/osf.io,aaxelb/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,hmoco/osf.io,mluo613/osf.io,rdhyee/osf.io,mattclark/osf.io,TomBaxter/osf.io,leb2dg/osf.io,mluo613/osf.io,chrisseto/osf.io,chrisseto/osf.io,erinspace/osf.io,icereval/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,mfraezz/osf.io,pattisdr/osf.io,icereval/osf.io,leb2dg/osf.io,felliott/osf.io,leb2dg/osf.io,aaxelb/osf.io,sloria/osf.io,hmoco/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,binoculars/osf.io,cwisecarver/osf.io,felliott/osf.io,caneruguz/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,felliott/osf.io,cwisecarver/osf.io,caneruguz/osf.io,acshi/osf.io,saradbowman/osf.io,cslzchen/osf.io,Nesiehr/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,erinspace/osf.io,adlius/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,acshi/osf.io,Johnetordoff/osf.io,binoculars/osf.io,adlius/osf.io,chennan47/osf.io,laurenrevere/osf.io | ---
+++
@@ -3,6 +3,6 @@
from api.citations import views
urlpatterns = [
- url(r'^$', views.CitationList.as_view(), name=views.CitationList.view_name),
- url(r'^(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
+ url(r'^styles/$', views.CitationList.as_view(), name=views.CitationList.view_name),
+ url(r'^styles/(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name),
] |
3059f6448e0fc2dd49ad38306f8efedc734b3aab | api/projects/tasks.py | api/projects/tasks.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER, max_retries=None)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True, max_retries=None)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER)
| Fix retry for experiment group | Fix retry for experiment group
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -11,7 +11,7 @@
logger = logging.getLogger('polyaxon.tasks.projects')
-@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
+@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True, max_retries=None)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
@@ -28,4 +28,4 @@
if pending_experiments:
# Schedule another task
- self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER, max_retries=None)
+ self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER) |
10655be79d9ab65f86939d0bd085197e0e35b39d | CodeFights/knapsackLight.py | CodeFights/knapsackLight.py | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():
tests = [
[]
]
for t in tests:
res = knapsackLight(t[0], t[1], t[2])
ans = t[3]
if ans == res:
print("PASSED: knapsackLight({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print(("FAILED: knapsackLight({}, {}, {}) returned {},"
"answer: {}").format(t[0], t[1], t[2], res, ans))
if __name__ == '__main__':
main()
| #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():
tests = [
[10, 5, 6, 4, 8, 10],
[]
]
for t in tests:
res = knapsackLight(t[0], t[1], t[2], t[3], t[4])
ans = t[5]
if ans == res:
print("PASSED: knapsackLight({}, {}, {}, {}, {}) returned {}"
.format(t[0], t[1], t[2], t[3], t[4], res))
else:
print(("FAILED: knapsackLight({}, {}, {}, {}, {}) returned {},"
"answer: {}")
.format(t[0], t[1], t[2], t[3], t[4], res, ans))
if __name__ == '__main__':
main()
| Format Code Fights knapsack light problem | Format Code Fights knapsack light problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -12,18 +12,20 @@
def main():
tests = [
+ [10, 5, 6, 4, 8, 10],
[]
]
for t in tests:
- res = knapsackLight(t[0], t[1], t[2])
- ans = t[3]
+ res = knapsackLight(t[0], t[1], t[2], t[3], t[4])
+ ans = t[5]
if ans == res:
- print("PASSED: knapsackLight({}, {}, {}) returned {}"
- .format(t[0], t[1], t[2], res))
+ print("PASSED: knapsackLight({}, {}, {}, {}, {}) returned {}"
+ .format(t[0], t[1], t[2], t[3], t[4], res))
else:
- print(("FAILED: knapsackLight({}, {}, {}) returned {},"
- "answer: {}").format(t[0], t[1], t[2], res, ans))
+ print(("FAILED: knapsackLight({}, {}, {}, {}, {}) returned {},"
+ "answer: {}")
+ .format(t[0], t[1], t[2], t[3], t[4], res, ans))
if __name__ == '__main__': |
82796dfb24c3e65b669d4336948e76e2a64cf73f | LR/lr/model/node_service.py | LR/lr/model/node_service.py | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)
SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']
class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
ADMINISTRATIVE='administrative'
def __init__(self, data=None):
super(NodeServiceModel,self).__init__(data)
| #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)
SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']
class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
DISTRIBUTE = 'distribute'
ADMINISTRATIVE='administrative'
def __init__(self, data=None):
super(NodeServiceModel,self).__init__(data)
| Add 'distribute' to the node services | Add 'distribute' to the node services
| Python | apache-2.0 | jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry | ---
+++
@@ -25,6 +25,7 @@
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
+ DISTRIBUTE = 'distribute'
ADMINISTRATIVE='administrative'
def __init__(self, data=None): |
dcd97762b65df37b5f7c4724892ab76bb631762f | src/havenctl/havenctl/launcher.py | src/havenctl/havenctl/launcher.py | import sys
import getopt
from ctl import HavenCtl
def print_version():
import pkg_resources # part of setuptools
version = pkg_resources.require("havenctl")[0].version
print(version)
def print_usage():
print """
Usage: havenctl [-a <remote_address> | --address=<remote_address>]
[-p <remote_port> | --port=<remote_port>] [-hv] cmd
"""
def execute_from_command_line():
try:
opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \
["address=", "port=", "version", "help"])
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
print_usage()
sys.exit()
elif o in ("-v", "--version"):
print_version()
sys.exit()
elif o in ("-a", "--address"):
address = a
elif o in ("-p", "--port"):
port = a
else:
usage()
assert False, "unhandled option"
sys.exit(2)
handle_user_args(address, port, " ".join(args))
def handle_user_args(address, port, cmd):
repl = HavenCtl()
if(address):
repl.onecmd("connect " + str(address) + " " + str(port))
if(cmd):
repl.onecmd(cmd)
else:
repl.cmdloop()
| import sys
import getopt
from ctl import HavenCtl
def print_version():
import pkg_resources # part of setuptools
version = pkg_resources.require("havenctl")[0].version
print(version)
def print_usage():
print """
Usage: havenctl [-a <remote_address> | --address=<remote_address>]
[-p <remote_port> | --port=<remote_port>] [-hv] cmd
"""
def execute_from_command_line():
address = None
port = 7854
try:
opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \
["address=", "port=", "version", "help"])
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
print_usage()
sys.exit()
elif o in ("-v", "--version"):
print_version()
sys.exit()
elif o in ("-a", "--address"):
address = a
elif o in ("-p", "--port"):
port = a
else:
usage()
assert False, "unhandled option"
sys.exit(2)
remaining = " ".join(args)
handle_user_args(address, port, remaining)
def handle_user_args(address, port, cmd):
repl = HavenCtl()
if(address):
repl.onecmd("connect " + str(address) + " " + str(port))
if(cmd):
repl.onecmd(cmd)
else:
repl.cmdloop()
| Make plain repl work again. | Make plain repl work again.
| Python | apache-2.0 | fintler/tomatodb,fintler/tomatodb,fintler/tomatodb | ---
+++
@@ -15,6 +15,9 @@
"""
def execute_from_command_line():
+ address = None
+ port = 7854
+
try:
opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \
["address=", "port=", "version", "help"])
@@ -40,7 +43,8 @@
assert False, "unhandled option"
sys.exit(2)
- handle_user_args(address, port, " ".join(args))
+ remaining = " ".join(args)
+ handle_user_args(address, port, remaining)
def handle_user_args(address, port, cmd):
repl = HavenCtl() |
7ce0478dafebb7f6c52150a3563ae4cc59d68d6e | mass_mailing_switzerland/models/mailchimp_merge_fields.py | mass_mailing_switzerland/models/mailchimp_merge_fields.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import fields, models
class MailchimpMergeFields(models.Model):
_inherit = "mailchimp.merge.fields"
# Allows to use fields from mail.mass_mailing.contact records in merge fields
field_id = fields.Many2one(domain=[
('model_id.model', 'in', ['res.partner', 'mail.mass_mailing.contact']),
('ttype', 'not in', ['one2many', 'many2one', 'many2many'])]
)
def get_value(self, mailing_contact):
contact_fields = self.filtered(
lambda f: f.field_id.model == "mail.mass_mailing.contact")
partner_fields = self - contact_fields
res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact)
for custom_field in contact_fields:
if custom_field.field_id and hasattr(
self, custom_field.field_id.name):
value = getattr(self, custom_field.field_id.name)
else:
value = ''
res.update({custom_field.tag: value or ''})
return res
| ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import fields, models
class MailchimpMergeFields(models.Model):
_inherit = "mailchimp.merge.fields"
# Allows to use fields from mail.mass_mailing.contact records in merge fields
field_id = fields.Many2one(domain=[
('model_id.model', 'in', ['res.partner', 'mail.mass_mailing.contact']),
('ttype', 'not in', ['one2many', 'many2one', 'many2many'])]
)
def get_value(self, mailing_contact):
contact_fields = self.filtered(
lambda f: f.field_id.model == "mail.mass_mailing.contact")
partner_fields = self - contact_fields
res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact)
for custom_field in contact_fields:
if custom_field.field_id and hasattr(
mailing_contact, custom_field.field_id.name):
value = getattr(mailing_contact, custom_field.field_id.name)
else:
value = ''
res.update({custom_field.tag: value or ''})
return res
| FIX mailing_contact merge fields value | FIX mailing_contact merge fields value
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland | ---
+++
@@ -26,8 +26,8 @@
res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact)
for custom_field in contact_fields:
if custom_field.field_id and hasattr(
- self, custom_field.field_id.name):
- value = getattr(self, custom_field.field_id.name)
+ mailing_contact, custom_field.field_id.name):
+ value = getattr(mailing_contact, custom_field.field_id.name)
else:
value = ''
res.update({custom_field.tag: value or ''}) |
2ad16c44adb20e9ba023e873149d67068504c34c | saleor/cart/__init__.py | saleor/cart/__init__.py | from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class DigitalGroup(ItemList):
'''
Group for digital products.
'''
pass
class CartPartitioner(ClassifyingPartitioner):
'''
Dividing cart into groups.
'''
def classify(self, item):
if isinstance(item.product, DigitalShip):
return 'digital'
return 'shippable'
def get_partition(self, classifier, items):
if classifier == 'digital':
return DigitalGroup(items)
return ShippedGroup(items)
class Cart(cart.Cart):
'''
Contains cart items. Serialized instance of cart is saved into django
session.
'''
timestamp = None
billing_address = None
def __unicode__(self):
return pgettext(
'Shopping cart',
'Your cart (%(cart_count)s)') % {'cart_count': self.count()}
| from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class DigitalGroup(ItemList):
'''
Group for digital products.
'''
pass
class CartPartitioner(ClassifyingPartitioner):
'''
Dividing cart into groups.
'''
def classify(self, item):
if isinstance(item.product, DigitalShip):
return 'digital'
return 'shippable'
def get_partition(self, classifier, items):
if classifier == 'digital':
return DigitalGroup(items)
return ShippedGroup(items)
class Cart(cart.Cart):
'''
Contains cart items. Serialized instance of cart is saved into django
session.
'''
timestamp = None
billing_address = None
def __unicode__(self):
return pgettext(
'Shopping cart',
'Your cart (%(cart_count)s)') % {'cart_count': self.count()}
def clear(self):
self._state = []
| Add ability to clear cart | Add ability to clear cart
| Python | bsd-3-clause | avorio/saleor,laosunhust/saleor,hongquan/saleor,maferelo/saleor,avorio/saleor,car3oon/saleor,tfroehlich82/saleor,UITools/saleor,car3oon/saleor,Drekscott/Motlaesaleor,maferelo/saleor,hongquan/saleor,josesanch/saleor,taedori81/saleor,KenMutemi/saleor,tfroehlich82/saleor,spartonia/saleor,mociepka/saleor,itbabu/saleor,UITools/saleor,laosunhust/saleor,rchav/vinerack,KenMutemi/saleor,Drekscott/Motlaesaleor,arth-co/saleor,taedori81/saleor,laosunhust/saleor,laosunhust/saleor,taedori81/saleor,tfroehlich82/saleor,hongquan/saleor,taedori81/saleor,arth-co/saleor,mociepka/saleor,HyperManTT/ECommerceSaleor,arth-co/saleor,rchav/vinerack,spartonia/saleor,UITools/saleor,KenMutemi/saleor,mociepka/saleor,josesanch/saleor,jreigel/saleor,rodrigozn/CW-Shop,dashmug/saleor,UITools/saleor,Drekscott/Motlaesaleor,jreigel/saleor,avorio/saleor,rodrigozn/CW-Shop,rodrigozn/CW-Shop,arth-co/saleor,paweltin/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,josesanch/saleor,paweltin/saleor,jreigel/saleor,paweltin/saleor,HyperManTT/ECommerceSaleor,spartonia/saleor,spartonia/saleor,itbabu/saleor,paweltin/saleor,dashmug/saleor,dashmug/saleor,avorio/saleor,rchav/vinerack,Drekscott/Motlaesaleor,maferelo/saleor,UITools/saleor,itbabu/saleor | ---
+++
@@ -48,3 +48,6 @@
return pgettext(
'Shopping cart',
'Your cart (%(cart_count)s)') % {'cart_count': self.count()}
+
+ def clear(self):
+ self._state = [] |
5f9cf67c473ef7d304da067b70b56d77f71ca4fa | web/impact/impact/middleware/method_override_middleware.py | web/impact/impact/middleware/method_override_middleware.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
# METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override'
class MethodOverrideMiddleware(object):
def process_request(self, request):
if request.method != 'POST':
return
if METHOD_OVERRIDE_HEADER not in request.META:
return
request.method = request.META[METHOD_OVERRIDE_HEADER]
| # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
class MethodOverrideMiddleware(object):
def process_request(self, request):
if request.method != 'POST':
return
if METHOD_OVERRIDE_HEADER not in request.META:
return
print(request.META)
request.method = request.META[METHOD_OVERRIDE_HEADER]
print(request.META)
| Revert Changes To Middleware To Prevent Build Hangup | [AC-4959] Revert Changes To Middleware To Prevent Build Hangup
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -1,8 +1,7 @@
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
-# METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
-METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override'
+METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
class MethodOverrideMiddleware(object):
def process_request(self, request):
@@ -10,4 +9,6 @@
return
if METHOD_OVERRIDE_HEADER not in request.META:
return
+ print(request.META)
request.method = request.META[METHOD_OVERRIDE_HEADER]
+ print(request.META) |
42a0dd7f808b87035f8067c5d0ad4bb688632135 | ecmd-core/pyapi/init/__init__.py | ecmd-core/pyapi/init/__init__.py | # import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
| # import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.append(os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.append(os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
| Append version specific path to os.path rather than prepend | pyapi: Append version specific path to os.path rather than prepend
Other code might depend on os.path[0] being the path of the executed
script, and there is no need for our new path to be at the front.
| Python | apache-2.0 | open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD | ---
+++
@@ -3,9 +3,9 @@
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
- sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
+ sys_path.append(os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
- sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
+ sys_path.append(os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info |
b03c8ebe8cc426e21b45f4de0d8d6e7176a4a647 | api/admin.py | api/admin.py | from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| Allow searching by email, username and names in user profiles | Allow searching by email, username and names in user profiles
This is needed as user profiles need to be edited for setting main
contact flag and ambassador roles.
| Python | mit | codeeu/coding-events,michelesr/coding-events,michelesr/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events | ---
+++
@@ -5,7 +5,7 @@
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
-
+ search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)} |
eb313bcced5a71f80cff8b3314d3346a151297a9 | flickr_api/__init__.py | flickr_api/__init__.py | """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", either the 'id' string
or the object itself can be used as argument. Similar consideration
holds for lists of id's.
For instance if "photo_id" is expected you can give call the function
with named argument "photo = PhotoObject" or with the id string
"photo_id = id_string".
Author : Alexis Mignon (c)
email : alexis.mignon_at_gmail.com
Date : 05/08/2011
"""
from objects import *
import objects
from auth import set_auth_handler
import upload as Upload
from upload import upload,replace
from method_call import set_keys,enable_cache,disable_cache
#~ def set_auth_handler(auth_handler):
#~ if isinstance(auth_handler,str):
#~ ah = AuthHandler.load(auth_handler)
#~ set_auth_handler(ah)
#~ else :
#~ objects.AUTH_HANDLER = auth_handler
#~ Upload.AUTH_HANDLER = auth_handler
#~ api.AUTH_HANDLER = auth_handler
| """
Object Oriented implementation of Flickr API.
Important notes:
- For consistency, the nameing of methods might differ from the name
in the official API. Please check the method "docstring" to know
what is the implemented method.
- For methods which expect an object "id", either the 'id' string
or the object itself can be used as argument. Similar consideration
holds for lists of id's.
For instance if "photo_id" is expected you can give call the function
with named argument "photo = PhotoObject" or with the id string
"photo_id = id_string".
Author : Alexis Mignon (c)
email : alexis.mignon_at_gmail.com
Date : 05/08/2011
"""
try:
from objects import *
import objects
import upload as Upload
from upload import upload,replace
except Exception, e:
print "Could not all modules"
print type(e), e
from auth import set_auth_handler
from method_call import set_keys,enable_cache,disable_cache
#~ def set_auth_handler(auth_handler):
#~ if isinstance(auth_handler,str):
#~ ah = AuthHandler.load(auth_handler)
#~ set_auth_handler(ah)
#~ else :
#~ objects.AUTH_HANDLER = auth_handler
#~ Upload.AUTH_HANDLER = auth_handler
#~ api.AUTH_HANDLER = auth_handler
| Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date | Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date
| Python | bsd-3-clause | alexis-mignon/python-flickr-api,alexis-mignon/python-flickr-api,bryndin/tornado-flickr-api | ---
+++
@@ -20,13 +20,16 @@
Date : 05/08/2011
"""
-
-from objects import *
-import objects
+try:
+ from objects import *
+ import objects
+ import upload as Upload
+ from upload import upload,replace
+except Exception, e:
+ print "Could not all modules"
+ print type(e), e
+
from auth import set_auth_handler
-
-import upload as Upload
-from upload import upload,replace
from method_call import set_keys,enable_cache,disable_cache
#~ def set_auth_handler(auth_handler): |
c1c2503933243fe51bb14f7d63222f958178d7e7 | tfx/components/transform/executor_v2_test.py | tfx/components/transform/executor_v2_test.py | # Lint as: python3
# Copyright 2020 Google LLC. 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.
"""Tests for tfx.components.transform.executor.
With the native TF2 code path being exercised.
"""
import os
import tensorflow as tf
import tensorflow_transform as tft
from tfx.components.transform import executor_test
class ExecutorV2Test(executor_test.ExecutorTest):
# Should not rely on inherited _SOURCE_DATA_DIR for integration tests to work
# when TFX is installed as a non-editable package.
_SOURCE_DATA_DIR = os.path.join(
os.path.dirname(os.path.dirname(__file__)), 'testdata')
def _use_force_tf_compat_v1(self):
return False
if __name__ == '__main__':
# TODO(b/168641322): remove once TFT post-0.25.0 released and depended on.
if tft.__version__ > '0.25.0' and tf.version.VERSION >= '2.4':
tf.test.main()
| # Lint as: python3
# Copyright 2020 Google LLC. 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.
"""Tests for tfx.components.transform.executor.
With the native TF2 code path being exercised.
"""
import os
import tensorflow as tf
from tfx.components.transform import executor_test
class ExecutorV2Test(executor_test.ExecutorTest):
# Should not rely on inherited _SOURCE_DATA_DIR for integration tests to work
# when TFX is installed as a non-editable package.
_SOURCE_DATA_DIR = os.path.join(
os.path.dirname(os.path.dirname(__file__)), 'testdata')
def _use_force_tf_compat_v1(self):
return False
if __name__ == '__main__':
tf.test.main()
| Remove version check now that TFX 0.25 is released. | Remove version check now that TFX 0.25 is released.
PiperOrigin-RevId: 343533114
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -19,7 +19,6 @@
import os
import tensorflow as tf
-import tensorflow_transform as tft
from tfx.components.transform import executor_test
@@ -35,6 +34,4 @@
if __name__ == '__main__':
- # TODO(b/168641322): remove once TFT post-0.25.0 released and depended on.
- if tft.__version__ > '0.25.0' and tf.version.VERSION >= '2.4':
- tf.test.main()
+ tf.test.main() |
eab299ce4bd3fa4734b8a3adbc805c3f5863bfc5 | fastpt/v2/util.py | fastpt/v2/util.py | import sys
from threading import local
def debug():
def pm(etype, value, tb): # pragma no cover
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb
sys.stderr.write('Entering post-mortem IPDB shell\n')
p = Pdb(color_scheme='Linux')
p.reset()
p.setup(None, tb)
p.print_stack_trace()
sys.stderr.write('%s: %s\n' % ( etype, value))
p.cmdloop()
p.forget()
# p.interaction(None, tb)
except ImportError:
sys.stderr.write('Entering post-mortem PDB shell\n')
traceback.print_exception(etype, value, tb)
pdb.post_mortem(tb)
sys.excepthook = pm
def expose(func):
func.exposed = True
return func
class Undefined(object): pass
UNDEFINED=Undefined()
class flattener(object):
def __init__(self, iterator):
self.iterator = iterator
@classmethod
def decorate(cls, func):
def inner(*args, **kwargs):
return cls(func(*args, **kwargs))
return inner
def __iter__(self):
for x in self.iterator:
if isinstance(x, flattener):
for xx in x:
yield xx
else:
yield x
class TLProxy(object):
def __init__(self, factory):
self._factory = factory
self._local = local()
def _get(self):
try:
result = self._local.value
except AttributeError:
result = self._local.value = self.factory()
return result
def __getattr__(self, name):
return getattr(self._get(), name)
| import sys
from threading import local
def debug():# pragma no cover
def pm(etype, value, tb):
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb
sys.stderr.write('Entering post-mortem IPDB shell\n')
p = Pdb(color_scheme='Linux')
p.reset()
p.setup(None, tb)
p.print_stack_trace()
sys.stderr.write('%s: %s\n' % ( etype, value))
p.cmdloop()
p.forget()
# p.interaction(None, tb)
except ImportError:
sys.stderr.write('Entering post-mortem PDB shell\n')
traceback.print_exception(etype, value, tb)
pdb.post_mortem(tb)
sys.excepthook = pm
def expose(func):
func.exposed = True
return func
class Undefined(object): pass
UNDEFINED=Undefined()
class flattener(object):
def __init__(self, iterator):
self.iterator = iterator
@classmethod
def decorate(cls, func):
def inner(*args, **kwargs):
return cls(func(*args, **kwargs))
return inner
def __iter__(self):
for x in self.iterator:
if isinstance(x, flattener):
for xx in x:
yield xx
else:
yield x
| Remove more obsolete code in v2 | Remove more obsolete code in v2
| Python | mit | moreati/kajiki,ollyc/kajiki,ollyc/kajiki,moreati/kajiki,moreati/kajiki,ollyc/kajiki | ---
+++
@@ -1,8 +1,8 @@
import sys
from threading import local
-def debug():
- def pm(etype, value, tb): # pragma no cover
+def debug():# pragma no cover
+ def pm(etype, value, tb):
import pdb, traceback
try:
from IPython.ipapi import make_session; make_session()
@@ -48,18 +48,3 @@
else:
yield x
-class TLProxy(object):
-
- def __init__(self, factory):
- self._factory = factory
- self._local = local()
-
- def _get(self):
- try:
- result = self._local.value
- except AttributeError:
- result = self._local.value = self.factory()
- return result
-
- def __getattr__(self, name):
- return getattr(self._get(), name) |
1eb6f65e40fccb3cea4b35374e7ddc25dd574dfa | examples/test/test_scratchnet.py | examples/test/test_scratchnet.py | #!/usr/bin/env python
"""
Test for scratchnet.py
"""
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
"""
Test for scratchnet.py
"""
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
| Increase scratchnet timeout to see if it's just slow. | Increase scratchnet timeout to see if it's just slow.
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | ---
+++
@@ -14,7 +14,7 @@
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
- index = p.expect( self.opts )
+ index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel( self ): |
47c5bb272040f47bc20cde647f76b9a8e673698c | Bindings/Python/tests/test_component_interface.py | Bindings/Python/tests/test_component_interface.py | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printComponentsMatching(self):
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
self.assertEquals(num_matches, 126)
def test_attachGeometry_memory_management(self):
model = osim.Model()
model.getGround().attachGeometry(osim.Sphere(1.5))
| import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printComponentsMatching(self):
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
self.assertEquals(num_matches, 144)
def test_attachGeometry_memory_management(self):
model = osim.Model()
model.getGround().attachGeometry(osim.Sphere(1.5))
| Add the ModelComponentSets to the number of subcomponents. | Add the ModelComponentSets to the number of subcomponents.
| Python | apache-2.0 | opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core | ---
+++
@@ -14,7 +14,7 @@
model = osim.Model(os.path.join(test_dir,
"gait10dof18musc_subject01.osim"))
num_matches = model.printComponentsMatching("_r")
- self.assertEquals(num_matches, 126)
+ self.assertEquals(num_matches, 144)
def test_attachGeometry_memory_management(self):
model = osim.Model()
model.getGround().attachGeometry(osim.Sphere(1.5)) |
c6e16cf939e74640fc8aec3475bf917214ee8ee6 | copyrightme.py | copyrightme.py | import sublime, sublime_plugin
class CopyrightmeCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
region = self.view.visible_region()
if text not in self.view.substr(region):
self.view.split_by_newlines(region)
self.view.insert(edit, 0, text + '\n\n')
| import sublime, sublime_plugin
class CopyrightmeCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
region = self.view.visible_region()
if text not in self.view.substr(region):
self.view.insert(edit, 0, text + '\n\n')
| Remove line splitting in view | Remove line splitting in view | Python | mit | tatarin0/CopyrightMe,tatarin0/CopyrightMe | ---
+++
@@ -5,6 +5,5 @@
region = self.view.visible_region()
if text not in self.view.substr(region):
- self.view.split_by_newlines(region)
self.view.insert(edit, 0, text + '\n\n')
|
1a242dc184adf4a3917b6c82742a667399c16ae9 | respite/middleware.py | respite/middleware.py | from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
or request.POST.has_key('_method'):
request.method = (
request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
request.POST.get('_method')
).upper()
class HttpPutMiddleware:
"""
Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET
and HTTP POST; populate a QueryDict instance with the request body in request.PUT.
"""
def process_request(self, request):
if request.method == 'PUT':
request.PUT = QueryDict(request.raw_post_data)
class HttpPatchMiddleware:
"""
Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET
and HTTP POST; populate a QueryDict instance with the request body in request.PATCH.
"""
def process_request(self, request):
if request.method == 'PATCH':
request.PATCH = QueryDict(request.raw_post_data)
| import re
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
or request.POST.has_key('_method'):
request.method = (
request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
request.POST.get('_method')
).upper()
if '_method' in request.POST:
request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data)
class HttpPutMiddleware:
"""
Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET
and HTTP POST; populate a QueryDict instance with the request body in request.PUT.
"""
def process_request(self, request):
if request.method == 'PUT':
request.PUT = QueryDict(request.raw_post_data)
class HttpPatchMiddleware:
"""
Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET
and HTTP POST; populate a QueryDict instance with the request body in request.PATCH.
"""
def process_request(self, request):
if request.method == 'PATCH':
request.PATCH = QueryDict(request.raw_post_data)
| Discard the '_method' parameter on HTTP POST | Discard the '_method' parameter on HTTP POST
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite | ---
+++
@@ -1,3 +1,5 @@
+import re
+
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
@@ -13,6 +15,9 @@
request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
request.POST.get('_method')
).upper()
+
+ if '_method' in request.POST:
+ request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data)
class HttpPutMiddleware:
""" |
04e243aafbd08008556d83d73fbbf22e5398aab4 | telostats/stations/models.py | telostats/stations/models.py | from django.db import models
from django.utils import timezone
class Station(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
name = models.CharField(u'name', max_length=100)
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
class Status(models.Model):
station = models.ForeignKey(Station)
timestamp = models.DateTimeField(default=timezone.now)
actual_timestamp = models.DateTimeField(default=timezone.now)
bikes = models.IntegerField(u'available bikes')
docks = models.IntegerField(u'available docks')
| from django.db import models
from django.utils import timezone
class Station(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
name = models.CharField(u'name', max_length=100)
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
def __unicode__(self):
return self.name
class Status(models.Model):
station = models.ForeignKey(Station)
timestamp = models.DateTimeField(default=timezone.now)
actual_timestamp = models.DateTimeField(default=timezone.now)
bikes = models.IntegerField(u'available bikes')
docks = models.IntegerField(u'available docks')
def __unicode__(self):
return u'{}: {}/{} ({})'.format(
self.station,
self.bikes, self.docks,
self.timestamp)
| Add unicode methods to Station/Status | Add unicode methods to Station/Status
| Python | bsd-3-clause | idan/telostats,idan/telostats,idan/telostats | ---
+++
@@ -8,6 +8,9 @@
longitude = models.FloatField(u'longitude')
latitude = models.FloatField(u'latitude')
+ def __unicode__(self):
+ return self.name
+
class Status(models.Model):
station = models.ForeignKey(Station)
@@ -15,3 +18,9 @@
actual_timestamp = models.DateTimeField(default=timezone.now)
bikes = models.IntegerField(u'available bikes')
docks = models.IntegerField(u'available docks')
+
+ def __unicode__(self):
+ return u'{}: {}/{} ({})'.format(
+ self.station,
+ self.bikes, self.docks,
+ self.timestamp) |
bd0310663a4f646873119e6b01afe585d0ef40bb | lib/interpreters/ScssInterpreter.py | lib/interpreters/ScssInterpreter.py | import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
"ignore": [ "node_modules", ".git" ]
}
def parseModuleKey(self, value):
if "/" in value:
if value.startswith("./"):
value = value[2:]
if path.basename(value).startswith("_"):
value = path.join(path.dirname(value), path.basename(value)[1:])
return super().parseModuleKey(value)
def onSearchResultChosen(self, interpreted, option_key, value, mode=SIMode.REPLACE_MODE):
if option_key == "extra_files":
interpreted.handler_name = "file"
super().onSearchResultChosen(interpreted, option_key, value, mode)
def stringifyStatements(self, statements, handler_name=None, insert_type=Interpreted.IT_REPLACE):
if handler_name == "file":
return "url({0})".format(statements["module"])
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpreted):
return {
"file": interpreted.statements["module"]
}
| import re
from os import path
from ..interpreter import *
from ..SIMode import SIMode
from ..utils import endswith
class ScssInterpreter(Interpreter):
def run(self):
self.settings = {
"extensions": [".scss"],
"remove_extensions": [".scss"],
"extra_extensions": [".jpg", ".png", ".gif", ".svg"],
"ignore": [ "node_modules", ".git" ]
}
def parseModuleKey(self, value):
if "/" in value:
if value.startswith("./"):
value = value[2:]
if path.basename(value).startswith("_"):
value = path.join(path.dirname(value), path.basename(value)[1:])
return super().parseModuleKey(value)
def onSearchResultChosen(self, interpreted, option_key, value, mode=SIMode.REPLACE_MODE):
if option_key == "extra_files":
interpreted.handler_name = "file"
super().onSearchResultChosen(interpreted, option_key, value, mode)
def stringifyStatements(self, statements, handler_name=None, insert_type=Interpreted.IT_REPLACE):
if handler_name == "file":
return "url({0})".format(statements["module"])
if self.getSetting("single-quotes"):
return "@import \'{0}\';".format(statements["module"])
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpreted):
return {
"file": interpreted.statements["module"]
}
| Add single-quotes setting to scss | Add single-quotes setting to scss
| Python | mit | vinpac/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/simple-import-js,vini175pa/simple-import-js | ---
+++
@@ -33,6 +33,9 @@
if handler_name == "file":
return "url({0})".format(statements["module"])
+ if self.getSetting("single-quotes"):
+ return "@import \'{0}\';".format(statements["module"])
+
return "@import \"{0}\";".format(statements["module"])
def getQueryObject(self, interpreted): |
9219a70106ce3008e5d4a394bb0d8507d474405b | pylib/mapit/areas/management/commands/utils.py | pylib/mapit/areas/management/commands/utils.py | import sys
def save_polygons(lookup):
for shape in lookup.values():
m, poly = shape
if not poly:
continue
sys.stdout.write(".")
sys.stdout.flush()
#g = OGRGeometry(OGRGeomType('MultiPolygon'))
m.polygons.all().delete()
for p in poly:
print p.geom_name
if p.geom_name == 'POLYGON':
shapes = [ p ]
else:
shapes = p
for g in shapes:
m.polygons.create(polygon=g.wkt)
#m.polygon = g.wkt
#m.save()
poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice
print ""
| import sys
def save_polygons(lookup):
for shape in lookup.values():
m, poly = shape
if not poly:
continue
sys.stdout.write(".")
sys.stdout.flush()
#g = OGRGeometry(OGRGeomType('MultiPolygon'))
m.polygons.all().delete()
for p in poly:
print p.geom_name
if p.geom_name == 'POLYGON':
shapes = [ p ]
else:
shapes = p
for g in shapes:
# XXX Using g.wkt directly when importing Norway KML works fine
# with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with
# Django 1.2, Postgres 8.4, PostGIS 1.5.1, saying that the
# dimensions constraint fails - because it is trying to import
# a shape as 3D as the WKT contains " 0" at the end of every
# co-ordinate. Removing the altitudes from the KML, and/or
# using altitudeMode makes no difference to the WKT here, so
# the only easy solution appears to be removing the altitude
# directly from the WKT before using it.
must_be_two_d = g.wkt.replace(' 0,', ',')
m.polygons.create(polygon=must_be_two_d)
#m.polygon = g.wkt
#m.save()
poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice
print ""
| Work around KML -> Django import bug. | Work around KML -> Django import bug.
| Python | agpl-3.0 | chris48s/mapit,chris48s/mapit,opencorato/mapit,chris48s/mapit,opencorato/mapit,New-Bamboo/mapit,Code4SA/mapit,opencorato/mapit,Sinar/mapit,Sinar/mapit,Code4SA/mapit,Code4SA/mapit,New-Bamboo/mapit | ---
+++
@@ -16,7 +16,17 @@
else:
shapes = p
for g in shapes:
- m.polygons.create(polygon=g.wkt)
+ # XXX Using g.wkt directly when importing Norway KML works fine
+ # with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with
+ # Django 1.2, Postgres 8.4, PostGIS 1.5.1, saying that the
+ # dimensions constraint fails - because it is trying to import
+ # a shape as 3D as the WKT contains " 0" at the end of every
+ # co-ordinate. Removing the altitudes from the KML, and/or
+ # using altitudeMode makes no difference to the WKT here, so
+ # the only easy solution appears to be removing the altitude
+ # directly from the WKT before using it.
+ must_be_two_d = g.wkt.replace(' 0,', ',')
+ m.polygons.create(polygon=must_be_two_d)
#m.polygon = g.wkt
#m.save()
poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice |
f3ae9106bf738fc3e86609fbf4d7ed26d4c76354 | bookmarks/database.py | bookmarks/database.py | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
DATABASE_URL = 'postgresql://{}:{}@{}/{}'.format(
app.config['DATABASE_USERNAME'],
app.config['DATABASE_PASSWORD'],
app.config['DATABASE_HOST'],
app.config['DATABASE_NAME']
)
engine = create_engine(DATABASE_URL, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
import bookmarks.models
Base.metadata.create_all(bind=engine)
| from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
engine = create_engine(app.config['DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
import bookmarks.models
Base.metadata.create_all(bind=engine)
| Use a DATABASE_URI config for db reference | Use a DATABASE_URI config for db reference
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks | ---
+++
@@ -3,14 +3,7 @@
from sqlalchemy.ext.declarative import declarative_base
from bookmarks import app
-DATABASE_URL = 'postgresql://{}:{}@{}/{}'.format(
- app.config['DATABASE_USERNAME'],
- app.config['DATABASE_PASSWORD'],
- app.config['DATABASE_HOST'],
- app.config['DATABASE_NAME']
-)
-
-engine = create_engine(DATABASE_URL, convert_unicode=True)
+engine = create_engine(app.config['DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False, |
62622d78c5cd45fbbe04497de856ff5424051678 | tensorflow/models/rnn/__init__.py | tensorflow/models/rnn/__init__.py | # Copyright 2015 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.
# ==============================================================================
"""Libraries to build Recurrent Neural Networks.
This file helps simplify the import process:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.models.rnn import rnn
from tensorflow.models.rnn import rnn_cell
...
"""
from tensorflow.models.rnn import rnn
from tensorflow.models.rnn import rnn_cell
from tensorflow.models.rnn import seq2seq
| # Copyright 2015 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.
# ==============================================================================
"""Libraries to build Recurrent Neural Networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.models.rnn import rnn
from tensorflow.models.rnn import rnn_cell
from tensorflow.models.rnn import seq2seq
| Fix doc string weirdness introduced by script | Fix doc string weirdness introduced by script
The doc string is still pretty confusing, but this is what it was before I
messed it up with my script.
Change: 114470999
| Python | apache-2.0 | sandeepdsouza93/TensorFlow-15712,alsrgv/tensorflow,annarev/tensorflow,EvenStrangest/tensorflow,chemelnucfin/tensorflow,SnakeJenny/TensorFlow,Carmezim/tensorflow,admcrae/tensorflow,cxxgtxy/tensorflow,anilmuthineni/tensorflow,benoitsteiner/tensorflow-xsmm,ppwwyyxx/tensorflow,calebfoss/tensorflow,MostafaGazar/tensorflow,haeusser/tensorflow,eerwitt/tensorflow,Carmezim/tensorflow,av8ramit/tensorflow,codrut3/tensorflow,nightjean/Deep-Learning,adit-chandra/tensorflow,guschmue/tensorflow,benoitsteiner/tensorflow,ran5515/DeepDecision,seanli9jan/tensorflow,nanditav/15712-TensorFlow,xzturn/tensorflow,Mistobaan/tensorflow,vrv/tensorflow,naturali/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,rabipanda/tensorflow,yongtang/tensorflow,laosiaudi/tensorflow,Xeralux/tensorflow,lukeiwanski/tensorflow-opencl,moonboots/tensorflow,codrut3/tensorflow,elingg/tensorflow,benoitsteiner/tensorflow-opencl,allenlavoie/tensorflow,gautam1858/tensorflow,haeusser/tensorflow,martinbede/second-sight,sjperkins/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,Kongsea/tensorflow,HaebinShin/tensorflow,Mazecreator/tensorflow,TakayukiSakai/tensorflow,EvenStrangest/tensorflow,annarev/tensorflow,rdipietro/tensorflow,theflofly/tensorflow,SnakeJenny/TensorFlow,eadgarchen/tensorflow,dongjoon-hyun/tensorflow,dyoung418/tensorflow,tiagofrepereira2012/tensorflow,guschmue/tensorflow,cg31/tensorflow,laszlocsomor/tensorflow,XueqingLin/tensorflow,dendisuhubdy/tensorflow,johndpope/tensorflow,scenarios/tensorflow,benoitsteiner/tensorflow-opencl,ppries/tensorflow,thjashin/tensorflow,alheinecke/tensorflow-xsmm,chris-chris/tensorflow,karllessard/tensorflow,jhseu/tensorflow,alsrgv/tensorflow,dancingdan/tensorflow,tntnatbry/tensorflow,tomasreimers/tensorflow-emscripten,alheinecke/tensorflow-xsmm,ibmsoe/tensorflow,paolodedios/tensorflow,Bulochkin/tensorflow_pack,asadziach/tensorflow,jbedorf/tensorflow,dongjoon-hyun/tensorflow,odejesush/tensorflow,tillahoffmann/tensorflow,4Quant/tensorflow,laszlocsomor/tensorflow,hehongliang/tensorflow,chris-chris/tensorflow,DavidNorman/tensorflow,arborh/tensorflow,anilmuthineni/tensorflow,aam-at/tensorflow,alheinecke/tensorflow-xsmm,kobejean/tensorflow,tornadozou/tensorflow,moonboots/tensorflow,pavelchristof/gomoku-ai,tomasreimers/tensorflow-emscripten,MostafaGazar/tensorflow,odejesush/tensorflow,SnakeJenny/TensorFlow,av8ramit/tensorflow,tillahoffmann/tensorflow,mdrumond/tensorflow,tongwang01/tensorflow,alistairlow/tensorflow,with-git/tensorflow,mrry/tensorflow,tensorflow/tensorflow,ZhangXinNan/tensorflow,Mazecreator/tensorflow,unsiloai/syntaxnet-ops-hack,ArtsiomCh/tensorflow,XueqingLin/tensorflow,jart/tensorflow,meteorcloudy/tensorflow,nikste/tensorflow,adit-chandra/tensorflow,hehongliang/tensorflow,cg31/tensorflow,kevin-coder/tensorflow-fork,mixturemodel-flow/tensorflow,manipopopo/tensorflow,xodus7/tensorflow,benoitsteiner/tensorflow-xsmm,ZhangXinNan/tensorflow,AndreasMadsen/tensorflow,alsrgv/tensorflow,ZhangXinNan/tensorflow,caisq/tensorflow,mdrumond/tensorflow,alistairlow/tensorflow,4Quant/tensorflow,zasdfgbnm/tensorflow,Mistobaan/tensorflow,karllessard/tensorflow,tongwang01/tensorflow,jwlawson/tensorflow,gunan/tensorflow,martinbede/second-sight,girving/tensorflow,Moriadry/tensorflow,dancingdan/tensorflow,dongjoon-hyun/tensorflow,lukeiwanski/tensorflow-opencl,raymondxyang/tensorflow,annarev/tensorflow,RapidApplicationDevelopment/tensorflow,mortada/tensorflow,johndpope/tensorflow,mortada/tensorflow,RapidApplicationDevelopment/tensorflow,4Quant/tensorflow,manjunaths/tensorflow,seaotterman/tensorflow,elingg/tensorflow,eadgarchen/tensorflow,annarev/tensorflow,tensorflow/tensorflow,jart/tensorflow,girving/tensorflow,chemelnucfin/tensorflow,MostafaGazar/tensorflow,chenjun0210/tensorflow,yufengg/tensorflow,yongtang/tensorflow,jhaux/tensorflow,haeusser/tensorflow,hfp/tensorflow-xsmm,yanchen036/tensorflow,alisidd/tensorflow,a-doumoulakis/tensorflow,Mistobaan/tensorflow,codrut3/tensorflow,ppries/tensorflow,Bismarrck/tensorflow,lukeiwanski/tensorflow,renyi533/tensorflow,aselle/tensorflow,strint/tensorflow,snnn/tensorflow,xodus7/tensorflow,wchan/tensorflow,tensorflow/tensorflow,rdipietro/tensorflow,MostafaGazar/tensorflow,annarev/tensorflow,ZhangXinNan/tensorflow,zasdfgbnm/tensorflow,alshedivat/tensorflow,jwlawson/tensorflow,pierreg/tensorflow,ibab/tensorflow,tongwang01/tensorflow,juharris/tensorflow,abhitopia/tensorflow,adamtiger/tensorflow,eerwitt/tensorflow,ArtsiomCh/tensorflow,freedomtan/tensorflow,eerwitt/tensorflow,DCSaunders/tensorflow,drpngx/tensorflow,hehongliang/tensorflow,ivano666/tensorflow,jbedorf/tensorflow,ibab/tensorflow,ZhangXinNan/tensorflow,tillahoffmann/tensorflow,alivecor/tensorflow,anilmuthineni/tensorflow,davidzchen/tensorflow,llhe/tensorflow,DCSaunders/tensorflow,yanchen036/tensorflow,DCSaunders/tensorflow,tensorflow/tensorflow,haeusser/tensorflow,strint/tensorflow,cancan101/tensorflow,llhe/tensorflow,awni/tensorflow,Kongsea/tensorflow,anilmuthineni/tensorflow,nikste/tensorflow,Intel-Corporation/tensorflow,tomasreimers/tensorflow-emscripten,laszlocsomor/tensorflow,benoitsteiner/tensorflow-opencl,eaplatanios/tensorflow,unsiloai/syntaxnet-ops-hack,aldian/tensorflow,karllessard/tensorflow,pavelchristof/gomoku-ai,a-doumoulakis/tensorflow,juharris/tensorflow,nikste/tensorflow,Bismarrck/tensorflow,jostep/tensorflow,adamtiger/tensorflow,cg31/tensorflow,asadziach/tensorflow,dyoung418/tensorflow,krikru/tensorflow-opencl,Bismarrck/tensorflow,gibiansky/tensorflow,rabipanda/tensorflow,renyi533/tensorflow,benoitsteiner/tensorflow-xsmm,AnishShah/tensorflow,Intel-tensorflow/tensorflow,apark263/tensorflow,chenjun0210/tensorflow,martinwicke/tensorflow,ville-k/tensorflow,wchan/tensorflow,hsaputra/tensorflow,handroissuazo/tensorflow,johndpope/tensorflow,xodus7/tensorflow,asimshankar/tensorflow,gautam1858/tensorflow,gnieboer/tensorflow,cxxgtxy/tensorflow,Bulochkin/tensorflow_pack,whn09/tensorflow,Xeralux/tensorflow,nburn42/tensorflow,jart/tensorflow,panmari/tensorflow,johndpope/tensorflow,mavenlin/tensorflow,strint/tensorflow,Mistobaan/tensorflow,horance-liu/tensorflow,llhe/tensorflow,zycdragonball/tensorflow,alisidd/tensorflow,jeffzheng1/tensorflow,mortada/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-pywrap_tf_optimizer,HKUST-SING/tensorflow,JVillella/tensorflow,handroissuazo/tensorflow,ArtsiomCh/tensorflow,juharris/tensorflow,mrry/tensorflow,seaotterman/tensorflow,hehongliang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,odejesush/tensorflow,laszlocsomor/tensorflow,arborh/tensorflow,sandeepgupta2k4/tensorflow,panmari/tensorflow,JingJunYin/tensorflow,manipopopo/tensorflow,seanli9jan/tensorflow,hsaputra/tensorflow,jendap/tensorflow,EvenStrangest/tensorflow,tntnatbry/tensorflow,mengxn/tensorflow,pavelchristof/gomoku-ai,ran5515/DeepDecision,Kongsea/tensorflow,cancan101/tensorflow,krikru/tensorflow-opencl,rdipietro/tensorflow,moonboots/tensorflow,hehongliang/tensorflow,ppwwyyxx/tensorflow,dongjoon-hyun/tensorflow,adamtiger/tensorflow,dancingdan/tensorflow,xzturn/tensorflow,with-git/tensorflow,wchan/tensorflow,martinwicke/tensorflow,krikru/tensorflow-opencl,jart/tensorflow,gibiansky/tensorflow,johndpope/tensorflow,hfp/tensorflow-xsmm,sarvex/tensorflow,seaotterman/tensorflow,eaplatanios/tensorflow,benoitsteiner/tensorflow,SnakeJenny/TensorFlow,zycdragonball/tensorflow,frreiss/tensorflow-fred,lukeiwanski/tensorflow-opencl,benoitsteiner/tensorflow,rabipanda/tensorflow,eadgarchen/tensorflow,tillahoffmann/tensorflow,MoamerEncsConcordiaCa/tensorflow,kchodorow/tensorflow,XueqingLin/tensorflow,eadgarchen/tensorflow,Mistobaan/tensorflow,tornadozou/tensorflow,mavenlin/tensorflow,ageron/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,codrut3/tensorflow,krikru/tensorflow-opencl,mortada/tensorflow,whn09/tensorflow,yanchen036/tensorflow,guschmue/tensorflow,Xeralux/tensorflow,ibab/tensorflow,zasdfgbnm/tensorflow,rabipanda/tensorflow,gojira/tensorflow,mixturemodel-flow/tensorflow,AnishShah/tensorflow,davidzchen/tensorflow,horance-liu/tensorflow,zasdfgbnm/tensorflow,ychfan/tensorflow,alshedivat/tensorflow,theflofly/tensorflow,thesuperzapper/tensorflow,Bismarrck/tensorflow,RyanYoung25/tensorflow,jart/tensorflow,HKUST-SING/tensorflow,ghchinoy/tensorflow,sandeepgupta2k4/tensorflow,tensorflow/tensorflow,juharris/tensorflow,ivano666/tensorflow,xzturn/tensorflow,zycdragonball/tensorflow,vrv/tensorflow,sjperkins/tensorflow,Carmezim/tensorflow,eaplatanios/tensorflow,nolanliou/tensorflow,martinwicke/tensorflow,rdipietro/tensorflow,vrv/tensorflow,drpngx/tensorflow,ghchinoy/tensorflow,kobejean/tensorflow,Xeralux/tensorflow,petewarden/tensorflow,lukeiwanski/tensorflow,dongjoon-hyun/tensorflow,JVillella/tensorflow,neilhan/tensorflow,ArtsiomCh/tensorflow,AnishShah/tensorflow,yongtang/tensorflow,gnieboer/tensorflow,jart/tensorflow,yaroslavvb/tensorflow,alsrgv/tensorflow,HKUST-SING/tensorflow,renyi533/tensorflow,xzturn/tensorflow,laszlocsomor/tensorflow,handroissuazo/tensorflow,sandeepgupta2k4/tensorflow,tntnatbry/tensorflow,jeffzheng1/tensorflow,ychfan/tensorflow,gunan/tensorflow,chenjun0210/tensorflow,kchodorow/tensorflow,benoitsteiner/tensorflow-xsmm,lukeiwanski/tensorflow-opencl,tomasreimers/tensorflow-emscripten,tornadozou/tensorflow,asadziach/tensorflow,scenarios/tensorflow,4Quant/tensorflow,Intel-Corporation/tensorflow,theflofly/tensorflow,brchiu/tensorflow,apark263/tensorflow,EvenStrangest/tensorflow,sandeepgupta2k4/tensorflow,yufengg/tensorflow,alistairlow/tensorflow,wangyum/tensorflow,eaplatanios/tensorflow,chenjun0210/tensorflow,asimshankar/tensorflow,a-doumoulakis/tensorflow,mrry/tensorflow,pcm17/tensorflow,Bulochkin/tensorflow_pack,gunan/tensorflow,manazhao/tf_recsys,Mistobaan/tensorflow,freedomtan/tensorflow,ibmsoe/tensorflow,ran5515/DeepDecision,HaebinShin/tensorflow,yanchen036/tensorflow,dongjoon-hyun/tensorflow,sandeepgupta2k4/tensorflow,4Quant/tensorflow,petewarden/tensorflow_makefile,sjperkins/tensorflow,krikru/tensorflow-opencl,dancingdan/tensorflow,aselle/tensorflow,ageron/tensorflow,strint/tensorflow,naturali/tensorflow,zasdfgbnm/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,davidzchen/tensorflow,guschmue/tensorflow,nolanliou/tensorflow,ravindrapanda/tensorflow,renyi533/tensorflow,gnieboer/tensorflow,guschmue/tensorflow,av8ramit/tensorflow,frreiss/tensorflow-fred,gojira/tensorflow,XueqingLin/tensorflow,dendisuhubdy/tensorflow,Moriadry/tensorflow,with-git/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alshedivat/tensorflow,apark263/tensorflow,markslwong/tensorflow,dancingdan/tensorflow,4Quant/tensorflow,alsrgv/tensorflow,pierreg/tensorflow,ravindrapanda/tensorflow,Moriadry/tensorflow,aldian/tensorflow,mengxn/tensorflow,tomasreimers/tensorflow-emscripten,gautam1858/tensorflow,adit-chandra/tensorflow,MycChiu/tensorflow,ran5515/DeepDecision,gibiansky/tensorflow,thesuperzapper/tensorflow,panmari/tensorflow,MostafaGazar/tensorflow,drpngx/tensorflow,juharris/tensorflow,gibiansky/tensorflow,lukeiwanski/tensorflow-opencl,Intel-tensorflow/tensorflow,manipopopo/tensorflow,cxxgtxy/tensorflow,MycChiu/tensorflow,anand-c-goog/tensorflow,sjperkins/tensorflow,ibmsoe/tensorflow,jhseu/tensorflow,asimshankar/tensorflow,dongjoon-hyun/tensorflow,andrewcmyers/tensorflow,jwlawson/tensorflow,wangyum/tensorflow,whn09/tensorflow,kevin-coder/tensorflow-fork,mavenlin/tensorflow,elingg/tensorflow,dendisuhubdy/tensorflow,alsrgv/tensorflow,sandeepdsouza93/TensorFlow-15712,theflofly/tensorflow,suiyuan2009/tensorflow,panmari/tensorflow,benoitsteiner/tensorflow,nolanliou/tensorflow,EvenStrangest/tensorflow,manjunaths/tensorflow,anand-c-goog/tensorflow,dendisuhubdy/tensorflow,davidzchen/tensorflow,eaplatanios/tensorflow,nightjean/Deep-Learning,ychfan/tensorflow,dyoung418/tensorflow,markslwong/tensorflow,naturali/tensorflow,annarev/tensorflow,aldian/tensorflow,maciekcc/tensorflow,vrv/tensorflow,4Quant/tensorflow,mengxn/tensorflow,tornadozou/tensorflow,eerwitt/tensorflow,jostep/tensorflow,Carmezim/tensorflow,davidzchen/tensorflow,aselle/tensorflow,ArtsiomCh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,haeusser/tensorflow,xodus7/tensorflow,haeusser/tensorflow,code-sauce/tensorflow,tongwang01/tensorflow,girving/tensorflow,JingJunYin/tensorflow,Kongsea/tensorflow,HaebinShin/tensorflow,tongwang01/tensorflow,aam-at/tensorflow,krikru/tensorflow-opencl,jeffzheng1/tensorflow,jhaux/tensorflow,allenlavoie/tensorflow,lukeiwanski/tensorflow,freedomtan/tensorflow,taknevski/tensorflow-xsmm,Mazecreator/tensorflow,moonboots/tensorflow,unsiloai/syntaxnet-ops-hack,haeusser/tensorflow,nanditav/15712-TensorFlow,MycChiu/tensorflow,thesuperzapper/tensorflow,alshedivat/tensorflow,jbedorf/tensorflow,MostafaGazar/tensorflow,aldian/tensorflow,alivecor/tensorflow,codrut3/tensorflow,yongtang/tensorflow,EvenStrangest/tensorflow,cancan101/tensorflow,dhalleine/tensorflow,mixturemodel-flow/tensorflow,jeffzheng1/tensorflow,bowang/tensorflow,jbedorf/tensorflow,tensorflow/tensorflow-pywrap_saved_model,markslwong/tensorflow,jhaux/tensorflow,alshedivat/tensorflow,Bulochkin/tensorflow_pack,johndpope/tensorflow,apark263/tensorflow,ychfan/tensorflow,alistairlow/tensorflow,petewarden/tensorflow_makefile,wchan/tensorflow,haeusser/tensorflow,thesuperzapper/tensorflow,eaplatanios/tensorflow,Bismarrck/tensorflow,pavelchristof/gomoku-ai,eerwitt/tensorflow,dhalleine/tensorflow,eaplatanios/tensorflow,alistairlow/tensorflow,gnieboer/tensorflow,hfp/tensorflow-xsmm,pierreg/tensorflow,snnn/tensorflow,neilhan/tensorflow,seaotterman/tensorflow,panmari/tensorflow,jalexvig/tensorflow,MoamerEncsConcordiaCa/tensorflow,freedomtan/tensorflow,andrewcmyers/tensorflow,TakayukiSakai/tensorflow,unsiloai/syntaxnet-ops-hack,zasdfgbnm/tensorflow,Kongsea/tensorflow,Bismarrck/tensorflow,benoitsteiner/tensorflow-xsmm,drpngx/tensorflow,tomasreimers/tensorflow-emscripten,RapidApplicationDevelopment/tensorflow,ibmsoe/tensorflow,gibiansky/tensorflow,tomasreimers/tensorflow-emscripten,laosiaudi/tensorflow,mortada/tensorflow,girving/tensorflow,thjashin/tensorflow,mdrumond/tensorflow,AndreasMadsen/tensorflow,kamcpp/tensorflow,eerwitt/tensorflow,gibiansky/tensorflow,freedomtan/tensorflow,johndpope/tensorflow,alivecor/tensorflow,pierreg/tensorflow,EvenStrangest/tensorflow,XueqingLin/tensorflow,martinwicke/tensorflow,zasdfgbnm/tensorflow,apark263/tensorflow,anilmuthineni/tensorflow,paolodedios/tensorflow,Carmezim/tensorflow,RyanYoung25/tensorflow,nburn42/tensorflow,chenjun0210/tensorflow,girving/tensorflow,JingJunYin/tensorflow,AnishShah/tensorflow,ychfan/tensorflow,karllessard/tensorflow,hsaputra/tensorflow,dhalleine/tensorflow,AnishShah/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,abhitopia/tensorflow,cg31/tensorflow,mrry/tensorflow,sjperkins/tensorflow,abhitopia/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,MycChiu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,adit-chandra/tensorflow,ishay2b/tensorflow,jalexvig/tensorflow,dancingdan/tensorflow,DCSaunders/tensorflow,meteorcloudy/tensorflow,karllessard/tensorflow,RapidApplicationDevelopment/tensorflow,kchodorow/tensorflow,gnieboer/tensorflow,neilhan/tensorflow,yanchen036/tensorflow,kchodorow/tensorflow,sjperkins/tensorflow,gunan/tensorflow,kevin-coder/tensorflow-fork,av8ramit/tensorflow,rdipietro/tensorflow,guschmue/tensorflow,martinbede/second-sight,kobejean/tensorflow,AnishShah/tensorflow,nburn42/tensorflow,yongtang/tensorflow,mavenlin/tensorflow,code-sauce/tensorflow,jalexvig/tensorflow,mortada/tensorflow,aam-at/tensorflow,gojira/tensorflow,snnn/tensorflow,benoitsteiner/tensorflow-opencl,ghchinoy/tensorflow,Moriadry/tensorflow,ageron/tensorflow,cxxgtxy/tensorflow,SnakeJenny/TensorFlow,DavidNorman/tensorflow,Kongsea/tensorflow,krikru/tensorflow-opencl,dyoung418/tensorflow,eadgarchen/tensorflow,ppwwyyxx/tensorflow,ville-k/tensorflow,kamcpp/tensorflow,nburn42/tensorflow,dhalleine/tensorflow,ghchinoy/tensorflow,unsiloai/syntaxnet-ops-hack,sjperkins/tensorflow,alisidd/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,vrv/tensorflow,hehongliang/tensorflow,brchiu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,dhalleine/tensorflow,maciekcc/tensorflow,frreiss/tensorflow-fred,manazhao/tf_recsys,petewarden/tensorflow,raymondxyang/tensorflow,whn09/tensorflow,theflofly/tensorflow,MycChiu/tensorflow,ravindrapanda/tensorflow,gojira/tensorflow,RyanYoung25/tensorflow,davidzchen/tensorflow,Bulochkin/tensorflow_pack,Intel-tensorflow/tensorflow,aselle/tensorflow,jart/tensorflow,thjashin/tensorflow,memo/tensorflow,girving/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,memo/tensorflow,seanli9jan/tensorflow,jhseu/tensorflow,jhaux/tensorflow,chenjun0210/tensorflow,ninotoshi/tensorflow,DavidNorman/tensorflow,awni/tensorflow,aam-at/tensorflow,Mazecreator/tensorflow,RapidApplicationDevelopment/tensorflow,girving/tensorflow,alisidd/tensorflow,ishay2b/tensorflow,RyanYoung25/tensorflow,memo/tensorflow,petewarden/tensorflow,moonboots/tensorflow,nburn42/tensorflow,ppwwyyxx/tensorflow,xodus7/tensorflow,abhitopia/tensorflow,moonboots/tensorflow,karllessard/tensorflow,admcrae/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,hfp/tensorflow-xsmm,gibiansky/tensorflow,cxxgtxy/tensorflow,mrry/tensorflow,kchodorow/tensorflow,ivano666/tensorflow,manipopopo/tensorflow,Mistobaan/tensorflow,allenlavoie/tensorflow,jendap/tensorflow,MoamerEncsConcordiaCa/tensorflow,mrry/tensorflow,asadziach/tensorflow,peterbraden/tensorflow,renyi533/tensorflow,pavelchristof/gomoku-ai,gojira/tensorflow,freedomtan/tensorflow,asimshankar/tensorflow,suiyuan2009/tensorflow,tongwang01/tensorflow,DCSaunders/tensorflow,yongtang/tensorflow,nikste/tensorflow,cg31/tensorflow,yufengg/tensorflow,dongjoon-hyun/tensorflow,manjunaths/tensorflow,peterbraden/tensorflow,tensorflow/tensorflow,jendap/tensorflow,nikste/tensorflow,ychfan/tensorflow,suiyuan2009/tensorflow,seaotterman/tensorflow,eadgarchen/tensorflow,tntnatbry/tensorflow,nolanliou/tensorflow,TakayukiSakai/tensorflow,theflofly/tensorflow,llhe/tensorflow,meteorcloudy/tensorflow,DCSaunders/tensorflow,Intel-tensorflow/tensorflow,odejesush/tensorflow,kevin-coder/tensorflow-fork,hsaputra/tensorflow,sarvex/tensorflow,ravindrapanda/tensorflow,nikste/tensorflow,mengxn/tensorflow,ishay2b/tensorflow,jalexvig/tensorflow,ArtsiomCh/tensorflow,jostep/tensorflow,arborh/tensorflow,mdrumond/tensorflow,wchan/tensorflow,alsrgv/tensorflow,aselle/tensorflow,MycChiu/tensorflow,eerwitt/tensorflow,cg31/tensorflow,apark263/tensorflow,ZhangXinNan/tensorflow,paolodedios/tensorflow,drpngx/tensorflow,yongtang/tensorflow,andrewcmyers/tensorflow,Intel-tensorflow/tensorflow,ArtsiomCh/tensorflow,jbedorf/tensorflow,horance-liu/tensorflow,manipopopo/tensorflow,eaplatanios/tensorflow,Kongsea/tensorflow,benoitsteiner/tensorflow-opencl,petewarden/tensorflow_makefile,ran5515/DeepDecision,allenlavoie/tensorflow,martinbede/second-sight,dongjoon-hyun/tensorflow,thjashin/tensorflow,ninotoshi/tensorflow,alisidd/tensorflow,guschmue/tensorflow,benoitsteiner/tensorflow-xsmm,chris-chris/tensorflow,tensorflow/tensorflow,MoamerEncsConcordiaCa/tensorflow,xodus7/tensorflow,codrut3/tensorflow,jendap/tensorflow,ZhangXinNan/tensorflow,adit-chandra/tensorflow,sandeepdsouza93/TensorFlow-15712,ninotoshi/tensorflow,asimshankar/tensorflow,ZhangXinNan/tensorflow,vrv/tensorflow,with-git/tensorflow,mrry/tensorflow,ninotoshi/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,anand-c-goog/tensorflow,neilhan/tensorflow,hsaputra/tensorflow,a-doumoulakis/tensorflow,drpngx/tensorflow,jbedorf/tensorflow,alivecor/tensorflow,tiagofrepereira2012/tensorflow,asimshankar/tensorflow,caisq/tensorflow,renyi533/tensorflow,naturali/tensorflow,maciekcc/tensorflow,meteorcloudy/tensorflow,martinbede/second-sight,jostep/tensorflow,taknevski/tensorflow-xsmm,nikste/tensorflow,a-doumoulakis/tensorflow,nanditav/15712-TensorFlow,theflofly/tensorflow,annarev/tensorflow,asadziach/tensorflow,apark263/tensorflow,Xeralux/tensorflow,a-doumoulakis/tensorflow,Moriadry/tensorflow,chenjun0210/tensorflow,seaotterman/tensorflow,juharris/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,memo/tensorflow,laosiaudi/tensorflow,aam-at/tensorflow,Moriadry/tensorflow,raymondxyang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,kchodorow/tensorflow,rdipietro/tensorflow,ghchinoy/tensorflow,aam-at/tensorflow,whn09/tensorflow,gautam1858/tensorflow,AndreasMadsen/tensorflow,Xeralux/tensorflow,scenarios/tensorflow,alistairlow/tensorflow,zasdfgbnm/tensorflow,mavenlin/tensorflow,theflofly/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,lukeiwanski/tensorflow-opencl,XueqingLin/tensorflow,snnn/tensorflow,horance-liu/tensorflow,jhseu/tensorflow,jhaux/tensorflow,jart/tensorflow,laosiaudi/tensorflow,laszlocsomor/tensorflow,wangyum/tensorflow,alsrgv/tensorflow,dongjoon-hyun/tensorflow,jbedorf/tensorflow,benoitsteiner/tensorflow-xsmm,kobejean/tensorflow,chenjun0210/tensorflow,jwlawson/tensorflow,AnishShah/tensorflow,frreiss/tensorflow-fred,tomasreimers/tensorflow-emscripten,seanli9jan/tensorflow,manazhao/tf_recsys,jbedorf/tensorflow,tntnatbry/tensorflow,cxxgtxy/tensorflow,Moriadry/tensorflow,admcrae/tensorflow,drpngx/tensorflow,hfp/tensorflow-xsmm,jbedorf/tensorflow,neilhan/tensorflow,lukeiwanski/tensorflow-opencl,yaroslavvb/tensorflow,nburn42/tensorflow,ppwwyyxx/tensorflow,av8ramit/tensorflow,thesuperzapper/tensorflow,petewarden/tensorflow,kevin-coder/tensorflow-fork,seaotterman/tensorflow,sandeepdsouza93/TensorFlow-15712,jhaux/tensorflow,HaebinShin/tensorflow,lukeiwanski/tensorflow,brchiu/tensorflow,ghchinoy/tensorflow,yanchen036/tensorflow,av8ramit/tensorflow,strint/tensorflow,snnn/tensorflow,aselle/tensorflow,with-git/tensorflow,aldian/tensorflow,abhitopia/tensorflow,with-git/tensorflow,arborh/tensorflow,code-sauce/tensorflow,scenarios/tensorflow,nolanliou/tensorflow,aldian/tensorflow,Kongsea/tensorflow,freedomtan/tensorflow,sandeepdsouza93/TensorFlow-15712,AnishShah/tensorflow,sarvex/tensorflow,hfp/tensorflow-xsmm,nanditav/15712-TensorFlow,code-sauce/tensorflow,taknevski/tensorflow-xsmm,pierreg/tensorflow,hfp/tensorflow-xsmm,jostep/tensorflow,johndpope/tensorflow,anilmuthineni/tensorflow,eerwitt/tensorflow,asadziach/tensorflow,jalexvig/tensorflow,dendisuhubdy/tensorflow,nikste/tensorflow,awni/tensorflow,seanli9jan/tensorflow,yaroslavvb/tensorflow,anilmuthineni/tensorflow,ravindrapanda/tensorflow,awni/tensorflow,mixturemodel-flow/tensorflow,manipopopo/tensorflow,Bulochkin/tensorflow_pack,dendisuhubdy/tensorflow,ppwwyyxx/tensorflow,ville-k/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,hfp/tensorflow-xsmm,petewarden/tensorflow_makefile,ppries/tensorflow,jwlawson/tensorflow,caisq/tensorflow,kamcpp/tensorflow,DavidNorman/tensorflow,petewarden/tensorflow_makefile,freedomtan/tensorflow,chemelnucfin/tensorflow,pcm17/tensorflow,alistairlow/tensorflow,gojira/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,kevin-coder/tensorflow-fork,peterbraden/tensorflow,nolanliou/tensorflow,HaebinShin/tensorflow,arborh/tensorflow,hsaputra/tensorflow,jendap/tensorflow,alsrgv/tensorflow,alshedivat/tensorflow,adit-chandra/tensorflow,av8ramit/tensorflow,markslwong/tensorflow,panmari/tensorflow,Bismarrck/tensorflow,theflofly/tensorflow,benoitsteiner/tensorflow-xsmm,mavenlin/tensorflow,tornadozou/tensorflow,yufengg/tensorflow,ibab/tensorflow,benoitsteiner/tensorflow,benoitsteiner/tensorflow,chris-chris/tensorflow,anand-c-goog/tensorflow,DCSaunders/tensorflow,tiagofrepereira2012/tensorflow,suiyuan2009/tensorflow,MostafaGazar/tensorflow,cancan101/tensorflow,kobejean/tensorflow,dendisuhubdy/tensorflow,mixturemodel-flow/tensorflow,cancan101/tensorflow,gautam1858/tensorflow,cg31/tensorflow,asimshankar/tensorflow,horance-liu/tensorflow,sandeepdsouza93/TensorFlow-15712,jart/tensorflow,jostep/tensorflow,wangyum/tensorflow,abhitopia/tensorflow,kchodorow/tensorflow,admcrae/tensorflow,hsaputra/tensorflow,arborh/tensorflow,ran5515/DeepDecision,markslwong/tensorflow,wchan/tensorflow,memo/tensorflow,ishay2b/tensorflow,xzturn/tensorflow,SnakeJenny/TensorFlow,jhseu/tensorflow,asadziach/tensorflow,manazhao/tf_recsys,rabipanda/tensorflow,jhaux/tensorflow,yaroslavvb/tensorflow,laosiaudi/tensorflow,allenlavoie/tensorflow,dyoung418/tensorflow,lakshayg/tensorflow,moonboots/tensorflow,sarvex/tensorflow,RyanYoung25/tensorflow,elingg/tensorflow,whn09/tensorflow,codrut3/tensorflow,laszlocsomor/tensorflow,Bismarrck/tensorflow,aselle/tensorflow,brchiu/tensorflow,gnieboer/tensorflow,ville-k/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,manjunaths/tensorflow,seanli9jan/tensorflow,martinwicke/tensorflow,scenarios/tensorflow,zasdfgbnm/tensorflow,RyanYoung25/tensorflow,ravindrapanda/tensorflow,nightjean/Deep-Learning,llhe/tensorflow,krikru/tensorflow-opencl,kevin-coder/tensorflow-fork,pierreg/tensorflow,ninotoshi/tensorflow,andrewcmyers/tensorflow,brchiu/tensorflow,andrewcmyers/tensorflow,ppwwyyxx/tensorflow,nburn42/tensorflow,ninotoshi/tensorflow,HKUST-SING/tensorflow,dongjoon-hyun/tensorflow,ville-k/tensorflow,dendisuhubdy/tensorflow,peterbraden/tensorflow,brchiu/tensorflow,Bulochkin/tensorflow_pack,markslwong/tensorflow,kamcpp/tensorflow,arborh/tensorflow,nanditav/15712-TensorFlow,chemelnucfin/tensorflow,handroissuazo/tensorflow,llhe/tensorflow,Mazecreator/tensorflow,gautam1858/tensorflow,seanli9jan/tensorflow,dancingdan/tensorflow,ravindrapanda/tensorflow,nburn42/tensorflow,manazhao/tf_recsys,yaroslavvb/tensorflow,admcrae/tensorflow,JingJunYin/tensorflow,annarev/tensorflow,sjperkins/tensorflow,tensorflow/tensorflow,lakshayg/tensorflow,rabipanda/tensorflow,snnn/tensorflow,kobejean/tensorflow,chris-chris/tensorflow,naturali/tensorflow,benoitsteiner/tensorflow-opencl,snnn/tensorflow,yanchen036/tensorflow,alheinecke/tensorflow-xsmm,lukeiwanski/tensorflow,hsaputra/tensorflow,benoitsteiner/tensorflow,ville-k/tensorflow,gautam1858/tensorflow,gnieboer/tensorflow,alheinecke/tensorflow-xsmm,ghchinoy/tensorflow,suiyuan2009/tensorflow,girving/tensorflow,naturali/tensorflow,markslwong/tensorflow,jalexvig/tensorflow,handroissuazo/tensorflow,ibmsoe/tensorflow,manazhao/tf_recsys,admcrae/tensorflow,JVillella/tensorflow,bowang/tensorflow,eaplatanios/tensorflow,xzturn/tensorflow,asadziach/tensorflow,llhe/tensorflow,AndreasMadsen/tensorflow,theflofly/tensorflow,gunan/tensorflow,renyi533/tensorflow,benoitsteiner/tensorflow,jalexvig/tensorflow,petewarden/tensorflow_makefile,paolodedios/tensorflow,gnieboer/tensorflow,maciekcc/tensorflow,meteorcloudy/tensorflow,paolodedios/tensorflow,johndpope/tensorflow,DavidNorman/tensorflow,nburn42/tensorflow,zycdragonball/tensorflow,ppries/tensorflow,aselle/tensorflow,peterbraden/tensorflow,jalexvig/tensorflow,awni/tensorflow,yongtang/tensorflow,martinbede/second-sight,alisidd/tensorflow,arborh/tensorflow,dyoung418/tensorflow,asadziach/tensorflow,caisq/tensorflow,adamtiger/tensorflow,calebfoss/tensorflow,Xeralux/tensorflow,seaotterman/tensorflow,adamtiger/tensorflow,chemelnucfin/tensorflow,manazhao/tf_recsys,wangyum/tensorflow,ishay2b/tensorflow,Xeralux/tensorflow,jwlawson/tensorflow,raymondxyang/tensorflow,HaebinShin/tensorflow,nolanliou/tensorflow,pcm17/tensorflow,elingg/tensorflow,lakshayg/tensorflow,odejesush/tensorflow,wangyum/tensorflow,alivecor/tensorflow,MycChiu/tensorflow,ageron/tensorflow,chris-chris/tensorflow,JingJunYin/tensorflow,gautam1858/tensorflow,arborh/tensorflow,ageron/tensorflow,petewarden/tensorflow,jeffzheng1/tensorflow,peterbraden/tensorflow,ibab/tensorflow,paolodedios/tensorflow,gibiansky/tensorflow,markslwong/tensorflow,eadgarchen/tensorflow,aam-at/tensorflow,apark263/tensorflow,asimshankar/tensorflow,gautam1858/tensorflow,odejesush/tensorflow,admcrae/tensorflow,davidzchen/tensorflow,Bulochkin/tensorflow_pack,ageron/tensorflow,elingg/tensorflow,petewarden/tensorflow,petewarden/tensorflow,RyanYoung25/tensorflow,xzturn/tensorflow,ppries/tensorflow,thjashin/tensorflow,sandeepgupta2k4/tensorflow,petewarden/tensorflow_makefile,pcm17/tensorflow,tornadozou/tensorflow,AnishShah/tensorflow,horance-liu/tensorflow,ageron/tensorflow,cg31/tensorflow,unsiloai/syntaxnet-ops-hack,LUTAN/tensorflow,abhitopia/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,Mazecreator/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,eadgarchen/tensorflow,jendap/tensorflow,TakayukiSakai/tensorflow,gunan/tensorflow,lakshayg/tensorflow,elingg/tensorflow,xodus7/tensorflow,Carmezim/tensorflow,ivano666/tensorflow,chenjun0210/tensorflow,jhaux/tensorflow,manjunaths/tensorflow,AndreasMadsen/tensorflow,alisidd/tensorflow,ville-k/tensorflow,lukeiwanski/tensorflow,jendap/tensorflow,DCSaunders/tensorflow,aselle/tensorflow,ageron/tensorflow,MycChiu/tensorflow,andrewcmyers/tensorflow,eerwitt/tensorflow,ivano666/tensorflow,av8ramit/tensorflow,handroissuazo/tensorflow,jwlawson/tensorflow,ageron/tensorflow,Intel-Corporation/tensorflow,unsiloai/syntaxnet-ops-hack,karllessard/tensorflow,andrewcmyers/tensorflow,chemelnucfin/tensorflow,alheinecke/tensorflow-xsmm,alshedivat/tensorflow,code-sauce/tensorflow,panmari/tensorflow,mixturemodel-flow/tensorflow,pavelchristof/gomoku-ai,strint/tensorflow,adit-chandra/tensorflow,jeffzheng1/tensorflow,AndreasMadsen/tensorflow,LUTAN/tensorflow,yaroslavvb/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,bowang/tensorflow,av8ramit/tensorflow,xodus7/tensorflow,scenarios/tensorflow,mavenlin/tensorflow,LUTAN/tensorflow,sarvex/tensorflow,taknevski/tensorflow-xsmm,gojira/tensorflow,gunan/tensorflow,eadgarchen/tensorflow,rdipietro/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,eadgarchen/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,cancan101/tensorflow,martinwicke/tensorflow,odejesush/tensorflow,LUTAN/tensorflow,alsrgv/tensorflow,alsrgv/tensorflow,calebfoss/tensorflow,scenarios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,kamcpp/tensorflow,Mistobaan/tensorflow,kamcpp/tensorflow,gojira/tensorflow,davidzchen/tensorflow,kevin-coder/tensorflow-fork,dendisuhubdy/tensorflow,XueqingLin/tensorflow,horance-liu/tensorflow,dhalleine/tensorflow,JVillella/tensorflow,AndreasMadsen/tensorflow,kevin-coder/tensorflow-fork,horance-liu/tensorflow,EvenStrangest/tensorflow,Mistobaan/tensorflow,abhitopia/tensorflow,caisq/tensorflow,dancingdan/tensorflow,tornadozou/tensorflow,whn09/tensorflow,laszlocsomor/tensorflow,ravindrapanda/tensorflow,MostafaGazar/tensorflow,strint/tensorflow,mixturemodel-flow/tensorflow,JVillella/tensorflow,dyoung418/tensorflow,mixturemodel-flow/tensorflow,martinbede/second-sight,nightjean/Deep-Learning,nolanliou/tensorflow,alshedivat/tensorflow,LUTAN/tensorflow,drpngx/tensorflow,hfp/tensorflow-xsmm,guschmue/tensorflow,codrut3/tensorflow,annarev/tensorflow,benoitsteiner/tensorflow-opencl,memo/tensorflow,Intel-tensorflow/tensorflow,yaroslavvb/tensorflow,DavidNorman/tensorflow,asimshankar/tensorflow,manjunaths/tensorflow,Bismarrck/tensorflow,lukeiwanski/tensorflow,jostep/tensorflow,jhaux/tensorflow,gojira/tensorflow,apark263/tensorflow,karllessard/tensorflow,thesuperzapper/tensorflow,alistairlow/tensorflow,LUTAN/tensorflow,manipopopo/tensorflow,mavenlin/tensorflow,JingJunYin/tensorflow,xzturn/tensorflow,aam-at/tensorflow,sandeepgupta2k4/tensorflow,karllessard/tensorflow,pavelchristof/gomoku-ai,HaebinShin/tensorflow,sandeepdsouza93/TensorFlow-15712,ppwwyyxx/tensorflow,tntnatbry/tensorflow,Carmezim/tensorflow,anand-c-goog/tensorflow,Intel-tensorflow/tensorflow,dyoung418/tensorflow,calebfoss/tensorflow,taknevski/tensorflow-xsmm,seanli9jan/tensorflow,cg31/tensorflow,alheinecke/tensorflow-xsmm,alistairlow/tensorflow,Mazecreator/tensorflow,maciekcc/tensorflow,hfp/tensorflow-xsmm,arborh/tensorflow,cancan101/tensorflow,code-sauce/tensorflow,jalexvig/tensorflow,bowang/tensorflow,pcm17/tensorflow,raymondxyang/tensorflow,kamcpp/tensorflow,alivecor/tensorflow,calebfoss/tensorflow,caisq/tensorflow,AndreasMadsen/tensorflow,alisidd/tensorflow,drpngx/tensorflow,allenlavoie/tensorflow,snnn/tensorflow,girving/tensorflow,ghchinoy/tensorflow,ppries/tensorflow,jwlawson/tensorflow,renyi533/tensorflow,benoitsteiner/tensorflow-opencl,tensorflow/tensorflow,apark263/tensorflow,seaotterman/tensorflow,adamtiger/tensorflow,thjashin/tensorflow,jendap/tensorflow,aldian/tensorflow,rdipietro/tensorflow,AnishShah/tensorflow,JingJunYin/tensorflow,ville-k/tensorflow,ZhangXinNan/tensorflow,manipopopo/tensorflow,ibab/tensorflow,vrv/tensorflow,xodus7/tensorflow,meteorcloudy/tensorflow,kchodorow/tensorflow,kobejean/tensorflow,lakshayg/tensorflow,laosiaudi/tensorflow,MoamerEncsConcordiaCa/tensorflow,chris-chris/tensorflow,memo/tensorflow,xodus7/tensorflow,gibiansky/tensorflow,ZhangXinNan/tensorflow,MoamerEncsConcordiaCa/tensorflow,mengxn/tensorflow,taknevski/tensorflow-xsmm,naturali/tensorflow,vrv/tensorflow,chemelnucfin/tensorflow,RyanYoung25/tensorflow,ibab/tensorflow,ychfan/tensorflow,hsaputra/tensorflow,DavidNorman/tensorflow,mortada/tensorflow,freedomtan/tensorflow,AnishShah/tensorflow,tensorflow/tensorflow-pywrap_saved_model,seanli9jan/tensorflow,strint/tensorflow,memo/tensorflow,TakayukiSakai/tensorflow,xzturn/tensorflow,dhalleine/tensorflow,tiagofrepereira2012/tensorflow,aam-at/tensorflow,zycdragonball/tensorflow,wangyum/tensorflow,nanditav/15712-TensorFlow,frreiss/tensorflow-fred,krikru/tensorflow-opencl,Mazecreator/tensorflow,gojira/tensorflow,jhseu/tensorflow,asimshankar/tensorflow,suiyuan2009/tensorflow,manipopopo/tensorflow,petewarden/tensorflow_makefile,RapidApplicationDevelopment/tensorflow,tillahoffmann/tensorflow,DavidNorman/tensorflow,taknevski/tensorflow-xsmm,karllessard/tensorflow,tomasreimers/tensorflow-emscripten,zasdfgbnm/tensorflow,meteorcloudy/tensorflow,horance-liu/tensorflow,allenlavoie/tensorflow,ppries/tensorflow,yufengg/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,tiagofrepereira2012/tensorflow,ageron/tensorflow,mengxn/tensorflow,ppries/tensorflow,benoitsteiner/tensorflow,zasdfgbnm/tensorflow,maciekcc/tensorflow,calebfoss/tensorflow,SnakeJenny/TensorFlow,yongtang/tensorflow,DCSaunders/tensorflow,ppwwyyxx/tensorflow,sarvex/tensorflow,alsrgv/tensorflow,peterbraden/tensorflow,anilmuthineni/tensorflow,sarvex/tensorflow,lukeiwanski/tensorflow-opencl,LUTAN/tensorflow,HKUST-SING/tensorflow,freedomtan/tensorflow,sjperkins/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,manipopopo/tensorflow,ageron/tensorflow,davidzchen/tensorflow,pcm17/tensorflow,scenarios/tensorflow,mengxn/tensorflow,thesuperzapper/tensorflow,MoamerEncsConcordiaCa/tensorflow,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,thjashin/tensorflow,TakayukiSakai/tensorflow,yanchen036/tensorflow,tiagofrepereira2012/tensorflow,jostep/tensorflow,av8ramit/tensorflow,renyi533/tensorflow,sandeepdsouza93/TensorFlow-15712,nightjean/Deep-Learning,adit-chandra/tensorflow,gunan/tensorflow,rdipietro/tensorflow,lakshayg/tensorflow,sandeepgupta2k4/tensorflow,yaroslavvb/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,JVillella/tensorflow,tntnatbry/tensorflow,nikste/tensorflow,Bismarrck/tensorflow,codrut3/tensorflow,arborh/tensorflow,rabipanda/tensorflow,gautam1858/tensorflow,raymondxyang/tensorflow,ghchinoy/tensorflow,allenlavoie/tensorflow,jwlawson/tensorflow,mrry/tensorflow,jendap/tensorflow,Bulochkin/tensorflow_pack,alshedivat/tensorflow,nburn42/tensorflow,sjperkins/tensorflow,mdrumond/tensorflow,JingJunYin/tensorflow,kobejean/tensorflow,chemelnucfin/tensorflow,HKUST-SING/tensorflow,yongtang/tensorflow,sandeepgupta2k4/tensorflow,brchiu/tensorflow,Intel-tensorflow/tensorflow,lukeiwanski/tensorflow-opencl,seanli9jan/tensorflow,bowang/tensorflow,ychfan/tensorflow,RapidApplicationDevelopment/tensorflow,martinbede/second-sight,caisq/tensorflow,eaplatanios/tensorflow,panmari/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,nolanliou/tensorflow,benoitsteiner/tensorflow-xsmm,nburn42/tensorflow,tensorflow/tensorflow-pywrap_saved_model,lakshayg/tensorflow,jwlawson/tensorflow,cancan101/tensorflow,chemelnucfin/tensorflow,rabipanda/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,ZhangXinNan/tensorflow,snnn/tensorflow,sandeepdsouza93/TensorFlow-15712,Carmezim/tensorflow,LUTAN/tensorflow,allenlavoie/tensorflow,adit-chandra/tensorflow,ibab/tensorflow,maciekcc/tensorflow,moonboots/tensorflow,nightjean/Deep-Learning,aselle/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,pcm17/tensorflow,HKUST-SING/tensorflow,cancan101/tensorflow,ville-k/tensorflow,brchiu/tensorflow,ppwwyyxx/tensorflow,laszlocsomor/tensorflow,ageron/tensorflow,apark263/tensorflow,mengxn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,girving/tensorflow,lukeiwanski/tensorflow,with-git/tensorflow,maciekcc/tensorflow,handroissuazo/tensorflow,jhaux/tensorflow,karllessard/tensorflow,ville-k/tensorflow,benoitsteiner/tensorflow-xsmm,jeffzheng1/tensorflow,Bismarrck/tensorflow,tntnatbry/tensorflow,aselle/tensorflow,benoitsteiner/tensorflow-opencl,arborh/tensorflow,awni/tensorflow,tillahoffmann/tensorflow,jhseu/tensorflow,girving/tensorflow,rabipanda/tensorflow,alheinecke/tensorflow-xsmm,Bulochkin/tensorflow_pack,adamtiger/tensorflow,wangyum/tensorflow,gunan/tensorflow,tongwang01/tensorflow,mortada/tensorflow,dancingdan/tensorflow,neilhan/tensorflow,paolodedios/tensorflow,caisq/tensorflow,DCSaunders/tensorflow,petewarden/tensorflow,abhitopia/tensorflow,Bulochkin/tensorflow_pack,rabipanda/tensorflow,jalexvig/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,laosiaudi/tensorflow,ibmsoe/tensorflow,alheinecke/tensorflow-xsmm,frreiss/tensorflow-fred,scenarios/tensorflow,strint/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ghchinoy/tensorflow,ychfan/tensorflow,andrewcmyers/tensorflow,Xeralux/tensorflow,llhe/tensorflow,snnn/tensorflow,seanli9jan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,HKUST-SING/tensorflow,jhseu/tensorflow,calebfoss/tensorflow,dancingdan/tensorflow,naturali/tensorflow,nightjean/Deep-Learning,RapidApplicationDevelopment/tensorflow,peterbraden/tensorflow,laosiaudi/tensorflow,tiagofrepereira2012/tensorflow,handroissuazo/tensorflow,nightjean/Deep-Learning,tensorflow/tensorflow-pywrap_tf_optimizer,mdrumond/tensorflow,pcm17/tensorflow,johndpope/tensorflow,brchiu/tensorflow,LUTAN/tensorflow,benoitsteiner/tensorflow,jart/tensorflow,bowang/tensorflow,martinwicke/tensorflow,ninotoshi/tensorflow,tillahoffmann/tensorflow,ishay2b/tensorflow,alistairlow/tensorflow,laosiaudi/tensorflow,ArtsiomCh/tensorflow,suiyuan2009/tensorflow,cxxgtxy/tensorflow,alshedivat/tensorflow,jhseu/tensorflow,annarev/tensorflow,jwlawson/tensorflow,bowang/tensorflow,elingg/tensorflow,SnakeJenny/TensorFlow,JingJunYin/tensorflow,Xeralux/tensorflow,codrut3/tensorflow,ivano666/tensorflow,jbedorf/tensorflow,ibmsoe/tensorflow,allenlavoie/tensorflow,jbedorf/tensorflow,martinwicke/tensorflow,neilhan/tensorflow,Carmezim/tensorflow,TakayukiSakai/tensorflow,freedomtan/tensorflow,taknevski/tensorflow-xsmm,tongwang01/tensorflow,odejesush/tensorflow,thjashin/tensorflow,rabipanda/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,tillahoffmann/tensorflow,manjunaths/tensorflow,petewarden/tensorflow,ppwwyyxx/tensorflow,anand-c-goog/tensorflow,asimshankar/tensorflow,adit-chandra/tensorflow,Moriadry/tensorflow,hehongliang/tensorflow,jeffzheng1/tensorflow,manjunaths/tensorflow,mortada/tensorflow,neilhan/tensorflow,allenlavoie/tensorflow,MoamerEncsConcordiaCa/tensorflow,guschmue/tensorflow,Mazecreator/tensorflow,whn09/tensorflow,alisidd/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,ghchinoy/tensorflow,juharris/tensorflow,XueqingLin/tensorflow,aam-at/tensorflow,zycdragonball/tensorflow,tntnatbry/tensorflow,DavidNorman/tensorflow,chris-chris/tensorflow,ibmsoe/tensorflow,taknevski/tensorflow-xsmm,annarev/tensorflow,awni/tensorflow,chemelnucfin/tensorflow,gunan/tensorflow,yufengg/tensorflow,nanditav/15712-TensorFlow,tiagofrepereira2012/tensorflow,martinwicke/tensorflow,ninotoshi/tensorflow,horance-liu/tensorflow,MycChiu/tensorflow,snnn/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,meteorcloudy/tensorflow,Bulochkin/tensorflow_pack,xzturn/tensorflow,caisq/tensorflow,handroissuazo/tensorflow,odejesush/tensorflow,HaebinShin/tensorflow,raymondxyang/tensorflow,nanditav/15712-TensorFlow,frreiss/tensorflow-fred,unsiloai/syntaxnet-ops-hack,kamcpp/tensorflow,lukeiwanski/tensorflow,meteorcloudy/tensorflow,with-git/tensorflow,HKUST-SING/tensorflow,memo/tensorflow,llhe/tensorflow,AndreasMadsen/tensorflow,a-doumoulakis/tensorflow,whn09/tensorflow,gnieboer/tensorflow,dendisuhubdy/tensorflow,yufengg/tensorflow,anand-c-goog/tensorflow,JVillella/tensorflow,meteorcloudy/tensorflow,ravindrapanda/tensorflow,Xeralux/tensorflow,chemelnucfin/tensorflow,juharris/tensorflow,brchiu/tensorflow,llhe/tensorflow,davidzchen/tensorflow,mdrumond/tensorflow,yongtang/tensorflow,chris-chris/tensorflow,MoamerEncsConcordiaCa/tensorflow,ivano666/tensorflow,calebfoss/tensorflow,mengxn/tensorflow,jalexvig/tensorflow,manipopopo/tensorflow,yaroslavvb/tensorflow,tensorflow/tensorflow-pywrap_saved_model,dhalleine/tensorflow,kamcpp/tensorflow,kevin-coder/tensorflow-fork,jeffzheng1/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,pierreg/tensorflow,raymondxyang/tensorflow,alivecor/tensorflow,nolanliou/tensorflow,jhseu/tensorflow,caisq/tensorflow,benoitsteiner/tensorflow-xsmm,elingg/tensorflow,ishay2b/tensorflow,anilmuthineni/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,thjashin/tensorflow,drpngx/tensorflow,pierreg/tensorflow,mrry/tensorflow,guschmue/tensorflow,wangyum/tensorflow,zycdragonball/tensorflow,ran5515/DeepDecision,lakshayg/tensorflow,gojira/tensorflow,admcrae/tensorflow,wchan/tensorflow,pcm17/tensorflow,manjunaths/tensorflow,thesuperzapper/tensorflow,RapidApplicationDevelopment/tensorflow,av8ramit/tensorflow,admcrae/tensorflow,anand-c-goog/tensorflow,nanditav/15712-TensorFlow,vrv/tensorflow,ibmsoe/tensorflow,hfp/tensorflow-xsmm,ppries/tensorflow,pavelchristof/gomoku-ai,4Quant/tensorflow,code-sauce/tensorflow,aam-at/tensorflow,thesuperzapper/tensorflow,paolodedios/tensorflow,MostafaGazar/tensorflow,neilhan/tensorflow,dancingdan/tensorflow,markslwong/tensorflow,jendap/tensorflow,lukeiwanski/tensorflow,sarvex/tensorflow,JingJunYin/tensorflow,a-doumoulakis/tensorflow,Mistobaan/tensorflow,calebfoss/tensorflow,xodus7/tensorflow,haeusser/tensorflow,ivano666/tensorflow,kobejean/tensorflow,code-sauce/tensorflow,bowang/tensorflow,eaplatanios/tensorflow,alshedivat/tensorflow,TakayukiSakai/tensorflow,hsaputra/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,code-sauce/tensorflow,theflofly/tensorflow,kobejean/tensorflow,brchiu/tensorflow,anand-c-goog/tensorflow,alivecor/tensorflow,awni/tensorflow,Mistobaan/tensorflow,mdrumond/tensorflow,kchodorow/tensorflow,tornadozou/tensorflow,XueqingLin/tensorflow,laszlocsomor/tensorflow,kobejean/tensorflow,wchan/tensorflow,mdrumond/tensorflow | ---
+++
@@ -13,18 +13,11 @@
# limitations under the License.
# ==============================================================================
-"""Libraries to build Recurrent Neural Networks.
-
-This file helps simplify the import process:
-
+"""Libraries to build Recurrent Neural Networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.models.rnn import rnn
from tensorflow.models.rnn import rnn_cell
-...
-"""
-from tensorflow.models.rnn import rnn
-from tensorflow.models.rnn import rnn_cell
from tensorflow.models.rnn import seq2seq |
de2ea6f02af98902bf50afbef25f51760715fc4a | ci/generate_pipeline_yml.py | ci/generate_pipeline_yml.py | #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
| #!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2', '2_3']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
| Add PCF 2.3 to CI pipeline. | Add PCF 2.3 to CI pipeline.
| Python | apache-2.0 | cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator | ---
+++
@@ -3,7 +3,7 @@
import os
from jinja2 import Template
-clusters = ['2_0', '2_1', '2_2']
+clusters = ['2_0', '2_1', '2_2', '2_3']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
|
1b0fdfdc2ff49d6dfc7d239b5a9cda1ff334f20b | candidates/cache.py | candidates/cache.py | from django.core.cache import cache
def post_cache_key(mapit_area_id):
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
def invalidate_posts(post_ids):
for post_id in post_ids:
post_key = post_cache_key(post_id)
cache.delete(post_key)
def get_post_cached(api, mapit_area_id):
post_key = post_cache_key(mapit_area_id)
result_from_cache = cache.get(post_key)
if result_from_cache is not None:
return result_from_cache
mp_post = api.posts(mapit_area_id).get(
embed='membership.person.membership.organization')
cache.set(post_key, mp_post, None)
return mp_post
| from django.core.cache import cache
def post_cache_key(mapit_area_id):
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
def person_cache_key(person_id):
"""Form the cache key used for person data"""
return "person:{0}".format(person_id)
def invalidate_posts(post_ids):
"""Delete cache entries for all of these PopIt posts"""
cache.delete_many(post_cache_key(post_id) for post_id in post_ids)
def invalidate_person(person_id):
"""Delete the cache entry for a particular person's PopIt data"""
person_key = person_cache_key(person_id)
cache.delete(person_key)
def get_post_cached(api, mapit_area_id):
post_key = post_cache_key(mapit_area_id)
result_from_cache = cache.get(post_key)
if result_from_cache is not None:
return result_from_cache
mp_post = api.posts(mapit_area_id).get(
embed='membership.person.membership.organization')
# Add posts data with an indefinite time-out (we should be
# invalidating the cached on any change).
cache.set(post_key, mp_post, None)
return mp_post
def get_person_cached(api, person_id):
person_key = person_cache_key(person_id)
result_from_cache = cache.get(person_key)
if result_from_cache is not None:
return result_from_cache
person_data = api.persons(person_id).get(
embed='membership.organization'
)
# Add it the person data to the cache with a timeout of
# a day.
cache.set(person_key, person_data, 86400)
return person_data
| Add functions for caching person data from PopIt | Add functions for caching person data from PopIt
| Python | agpl-3.0 | mysociety/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative | ---
+++
@@ -4,10 +4,18 @@
"""Form the cache key used for post data"""
return "post:{0}".format(mapit_area_id)
+def person_cache_key(person_id):
+ """Form the cache key used for person data"""
+ return "person:{0}".format(person_id)
+
def invalidate_posts(post_ids):
- for post_id in post_ids:
- post_key = post_cache_key(post_id)
- cache.delete(post_key)
+ """Delete cache entries for all of these PopIt posts"""
+ cache.delete_many(post_cache_key(post_id) for post_id in post_ids)
+
+def invalidate_person(person_id):
+ """Delete the cache entry for a particular person's PopIt data"""
+ person_key = person_cache_key(person_id)
+ cache.delete(person_key)
def get_post_cached(api, mapit_area_id):
post_key = post_cache_key(mapit_area_id)
@@ -17,6 +25,21 @@
mp_post = api.posts(mapit_area_id).get(
embed='membership.person.membership.organization')
+ # Add posts data with an indefinite time-out (we should be
+ # invalidating the cached on any change).
cache.set(post_key, mp_post, None)
return mp_post
+
+def get_person_cached(api, person_id):
+ person_key = person_cache_key(person_id)
+ result_from_cache = cache.get(person_key)
+ if result_from_cache is not None:
+ return result_from_cache
+ person_data = api.persons(person_id).get(
+ embed='membership.organization'
+ )
+ # Add it the person data to the cache with a timeout of
+ # a day.
+ cache.set(person_key, person_data, 86400)
+ return person_data |
5831fe52a4b8296bd4f0c71e5e98369d704b8fc3 | painter/urls.py | painter/urls.py | from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_display'),
]
urlpatterns += staticfiles_urlpatterns()
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_display'),
]
| Remove the staticfiles from the painter app URLconf. | Remove the staticfiles from the painter app URLconf.
| Python | mit | adam-thomas/imperial-painter,adam-thomas/imperial-painter,adam-incuna/imperial-painter,adam-incuna/imperial-painter | ---
+++
@@ -1,5 +1,4 @@
from django.conf.urls import url
-from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
@@ -8,5 +7,3 @@
url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'),
url(r'^$', views.CardDisplayReload.as_view(), name='card_display'),
]
-
-urlpatterns += staticfiles_urlpatterns() |
4971f5cd840d17df237fc09dbd11cb8e265bc6e8 | quickphotos/utils.py | quickphotos/utils.py | from django.utils.timezone import make_aware, utc
from .models import Photo
def update_photos(photos):
for i in photos:
image = i.images['standard_resolution']
obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
'user': i.user.username,
'image': image.url,
'image_width': image.width,
'image_height': image.height,
'created': make_aware(i.created_time, utc),
'caption': i.caption or '',
'link': i.link,
})
| from django.utils.timezone import make_aware, utc
from .models import Photo
def update_photos(photos):
obj_list = []
for i in photos:
image = i.images['standard_resolution']
obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
'user': i.user.username,
'image': image.url,
'image_width': image.width,
'image_height': image.height,
'created': make_aware(i.created_time, utc),
'caption': i.caption or '',
'link': i.link,
})
obj_list.append(obj)
return obj_list
| Return a list of all photo objects which have been updated | Return a list of all photo objects which have been updated
| Python | bsd-3-clause | blancltd/django-quick-photos,kmlebedev/mezzanine-instagram-quickphotos | ---
+++
@@ -4,6 +4,8 @@
def update_photos(photos):
+ obj_list = []
+
for i in photos:
image = i.images['standard_resolution']
@@ -16,3 +18,7 @@
'caption': i.caption or '',
'link': i.link,
})
+
+ obj_list.append(obj)
+
+ return obj_list |
fb8fa7fedd18d751aeb7c060786377c96a8b2319 | characters/tests.py | characters/tests.py | from django.test import TestCase
from .models import Character, Team
class TeamGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = team
result = sut.get_absolute_url()
self.assertTrue(slug_value in result)
def test_team_slug_appears_in_url(self):
team_slug = "team-slug"
team = Team()
team.slug = team_slug
sut = Character()
sut.slug = "dont-care"
sut.team = team
result = sut.get_absolute_url()
self.assertTrue(team_slug in result)
| from django.test import TestCase
from .models import Character, Team
class CharacterGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = team
result = sut.get_absolute_url()
self.assertTrue(slug_value in result)
def test_team_slug_appears_in_url(self):
team_slug = "team-slug"
team = Team()
team.slug = team_slug
sut = Character()
sut.slug = "dont-care"
sut.team = team
result = sut.get_absolute_url()
self.assertTrue(team_slug in result)
| Fix name - it is testing Character, not Team | Fix name - it is testing Character, not Team
| Python | mit | evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca | ---
+++
@@ -3,7 +3,7 @@
from .models import Character, Team
-class TeamGetAbsoluteUrl(TestCase):
+class CharacterGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
|
47162e68dd7662efd8f1c2463d11dc9228726523 | solar/dblayer/standalone_session_wrapper.py | solar/dblayer/standalone_session_wrapper.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Starts single seession, and ends it with `atexit`
can be used from cli / examples
shouldn't be used from long running processes (workers etc)
"""
def create_all():
import sys
if not sys.executable.endswith(('python', )):
# auto add session to only standalone python runs
return
from solar.dblayer.model import ModelMeta
import atexit
ModelMeta.session_start()
atexit.register(ModelMeta.session_end)
| # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Starts single seession, and ends it with `atexit`
can be used from cli / examples
shouldn't be used from long running processes (workers etc)
"""
def create_all():
import sys
if sys.executable.split('/')[-1] not in ['python', 'python2']:
# auto add session to only standalone python runs
return
from solar.dblayer.model import ModelMeta
import atexit
ModelMeta.session_start()
atexit.register(ModelMeta.session_end)
| Fix session in CLI on Debian systems | Fix session in CLI on Debian systems
Change-Id: I4b1a3e45417a8d8442e097d440ebee8a09a8aaa2
| Python | apache-2.0 | openstack/solar,pigmej/solar,openstack/solar,openstack/solar,pigmej/solar,pigmej/solar | ---
+++
@@ -23,7 +23,7 @@
def create_all():
import sys
- if not sys.executable.endswith(('python', )):
+ if sys.executable.split('/')[-1] not in ['python', 'python2']:
# auto add session to only standalone python runs
return
|
fd599497011fcb94d8b5c29dc696128eafb9d603 | tests/app/test_create_app.py | tests/app/test_create_app.py | """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'})
def test_default_instance_links():
"""Validate default instance_links are being populated properly."""
pipeline_config = {
"instance_links": {
"example2": "https://example2.com",
}
}
combined = {'example1': 'https://example1.com'}
combined.update(pipeline_config['instance_links'])
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
| """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'})
def test_default_instance_links():
"""Validate default instance_links are being populated properly."""
pipeline_config = {
"instance_links": {
"example2": "https://example2.com",
}
}
combined = {'example1': 'https://example1.com'}
combined.update(pipeline_config['instance_links'])
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
@mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'})
def test_duplicate_instance_links():
"""Validate behavior when two keys are identical."""
pipeline_config = {
"instance_links": {}
}
duplicate = {'example': 'example2'}
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == duplicate, "Instance links handing duplicates are wrong."
| Check handling duplicate key for instance links | test: Check handling duplicate key for instance links
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -24,3 +24,18 @@
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
+
+
+@mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'})
+def test_duplicate_instance_links():
+ """Validate behavior when two keys are identical."""
+
+ pipeline_config = {
+ "instance_links": {}
+ }
+
+ duplicate = {'example': 'example2'}
+ spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
+ instance_links = spinnaker_app.retrieve_instance_links()
+
+ assert instance_links == duplicate, "Instance links handing duplicates are wrong." |
3f5867695e5b980e05f1516f2bcbd246cdc3241f | install_deps.py | install_deps.py | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
def get_requirements(*args):
"""Parse all requirements files given and return a list of the
dependencies"""
install_deps = []
try:
for fpath in args:
install_deps.extend([str(d.req) for d in parse_requirements(fpath)])
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
return [dep for dep in install_deps if dep != 'None']
if __name__ == '__main__':
for line in fileinput.input():
req_filepaths = sys.argv[1:]
deps = get_requirements(*req_filepaths)
try:
for dep_name in deps:
cmd = "pip install '{0}'".format(dep_name)
print('#', cmd)
subprocess.check_call(cmd, shell=True)
except:
print('Error installing {}'.format(dep_name))
| #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
import uuid
def get_requirements(*args):
"""Parse all requirements files given and return a list of the
dependencies"""
install_deps = []
try:
for fpath in args:
install_deps.extend([str(d.req) for d in parse_requirements(fpath, session=uuid.uuid1())])
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
return [dep for dep in install_deps if dep != 'None']
if __name__ == '__main__':
for line in fileinput.input():
req_filepaths = sys.argv[1:]
deps = get_requirements(*req_filepaths)
try:
for dep_name in deps:
cmd = "pip install '{0}'".format(dep_name)
print('#', cmd)
subprocess.check_call(cmd, shell=True)
except:
print('Error installing {}'.format(dep_name))
| Fix parse_requirements call for new pip version. | Fix parse_requirements call for new pip version.
| Python | bsd-3-clause | Neurita/boyle | ---
+++
@@ -12,6 +12,7 @@
import fileinput
import subprocess
from pip.req import parse_requirements
+import uuid
def get_requirements(*args):
@@ -20,7 +21,7 @@
install_deps = []
try:
for fpath in args:
- install_deps.extend([str(d.req) for d in parse_requirements(fpath)])
+ install_deps.extend([str(d.req) for d in parse_requirements(fpath, session=uuid.uuid1())])
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
|
f1eae848aa48ef3891407f400410827d59d7c880 | pyservice/__init__.py | pyservice/__init__.py | """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
| """
Copyright (c) 2014, Joseph Cross.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from pyservice.client import Client
from pyservice.service import Service
__all__ = ["Client", "Service"]
| Make Client, Service importable from pyservice | Make Client, Service importable from pyservice
| Python | mit | numberoverzero/pyservice | ---
+++
@@ -20,3 +20,8 @@
THE SOFTWARE.
"""
+
+from pyservice.client import Client
+from pyservice.service import Service
+
+__all__ = ["Client", "Service"] |
74d4868a0e43e5eb089d6d7a0a07545b7f829806 | main.py | main.py | from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(settings.config)
ear = listener(settings.config['port'],settings.config['outbound'])
ear.daemon = True
ear.start()
initializePeerConnections()
if __name__ == "__main__":
main()
| from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(settings.config)
ear = listener(settings.config['port'],settings.config['outbound'])
ear.daemon = True
ear.start()
sleep(1)
initializePeerConnections()
if __name__ == "__main__":
main()
| Add delay after listener start (for testing) | Add delay after listener start (for testing) [skip ci] | Python | mit | gappleto97/Senior-Project | ---
+++
@@ -15,6 +15,7 @@
ear = listener(settings.config['port'],settings.config['outbound'])
ear.daemon = True
ear.start()
+ sleep(1)
initializePeerConnections()
if __name__ == "__main__": |
c72500abaeb1149d35fd6fcb28cb6a321b998045 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://github.com/uiureo/demae',
packages=[
'demae',
],
package_dir={'demae':
'demae'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='demae',
classifiers=[
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
from setuptools import setup
requirements = [
'boto3',
'pandas<0.20',
'psycopg2',
]
test_requirements = [
'pytest',
]
setup(
name='demae',
version='0.8.0',
description="",
author="Kazato Sugimoto",
author_email='kazato.sugimoto@gmail.com',
url='https://github.com/uiureo/demae',
packages=[
'demae',
'demae.source',
'demae.dest',
],
package_dir={'demae':
'demae'},
include_package_data=True,
install_requires=requirements,
zip_safe=False,
keywords='demae',
classifiers=[
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
| Add source and dest to packages | Add source and dest to packages
| Python | mit | uiureo/demae | ---
+++
@@ -21,6 +21,8 @@
url='https://github.com/uiureo/demae',
packages=[
'demae',
+ 'demae.source',
+ 'demae.dest',
],
package_dir={'demae':
'demae'}, |
8465394884eea4fd6fa0eb9e45f9ec91bec57cb9 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propagation (message passing) for factor graphs',
long_description=(read('README.rst')),
url='http://github.com/ilyakava/sumproduct/',
license='MIT',
author='Ilya Kavalerov',
author_email='ilyakavalerov@gmail.com',
packages=find_packages(exclude=['tests*']),
py_modules=['sumproduct'],
include_package_data=True,
classifiers=[
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propagation (message passing) for factor graphs',
long_description=(read('README.rst')),
url='http://github.com/ilyakava/sumproduct/',
license='MIT',
author='Ilya Kavalerov',
author_email='ilyakavalerov@gmail.com',
packages=find_packages(exclude=['tests*']),
py_modules=['sumproduct'],
include_package_data=True,
classifiers=[
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| Add some topics for next deploy | Add some topics for next deploy
| Python | mit | ilyakava/sumproduct | ---
+++
@@ -25,6 +25,9 @@
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
+ 'Intended Audience :: Science/Research',
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
+ 'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) |
44b311eade20016f613311a98d666b2463826ad1 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22 | Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.21.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -9,7 +9,7 @@
packages=find_packages(),
include_package_data=True,
install_requires=[
- 'requests>=2.4.2,<2.21',
+ 'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7', |
34452461de40c35d28bfc8b2a18b6fa14ebb875d | onadata/apps/fsforms/management/commands/update_mongo_value_type.py | onadata/apps/fsforms/management/commands/update_mongo_value_type.py | from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type"
def handle(self, *args, **kwargs):
xform_instances = settings.MONGO_DB.instances
#type 2 is for string type
query = {'$or':[{'fs_site':{'$type':2}}, {'fs_uuid':{'$type':2}}]}
cursor = xform_instances.find(query)
for record in cursor:
fs_site = record['fs_site']
if fs_site == '':
new_fs_site = None
else:
new_fs_site = int(fs_site)
fs_uuid = record['fs_uuid']
if fs_uuid == '':
new_fs_uuid = None
elif fs_uuid == 'None':
new_fs_uuid = None
else:
new_fs_uuid = int(fs_uuid)
xform_instances.update({'_id':record['_id']},{'$set':{'fs_site':new_fs_site, 'fs_uuid':new_fs_uuid}})
print('Updating mongo instance for ' + str(record['_id']))
print('Mongo instances updated.......')
| from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type"
def handle(self, *args, **kwargs):
xform_instances = settings.MONGO_DB.instances
#type 2 is for string type
query = {'$or':[{'fs_site':{'$type':2}}, {'fs_uuid':{'$type':2}}]}
cursor = xform_instances.find(query)
for record in cursor:
fs_site = record['fs_site']
if fs_site == '':
new_fs_site = None
else:
new_fs_site = int(fs_site)
fs_uuid = record['fs_uuid']
if fs_uuid == '':
new_fs_uuid = None
elif fs_uuid == 'None':
new_fs_uuid = None
elif fs_uuid == 'NoneType':
new_fs_uuid = None
else:
new_fs_uuid = int(fs_uuid)
xform_instances.update({'_id':record['_id']},{'$set':{'fs_site':new_fs_site, 'fs_uuid':new_fs_uuid}})
print('Updating mongo instance for ' + str(record['_id']))
print('Mongo instances updated.......')
| Handle cases update mongo value type | Handle cases update mongo value type
| Python | bsd-2-clause | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat | ---
+++
@@ -23,6 +23,8 @@
new_fs_uuid = None
elif fs_uuid == 'None':
new_fs_uuid = None
+ elif fs_uuid == 'NoneType':
+ new_fs_uuid = None
else:
new_fs_uuid = int(fs_uuid)
xform_instances.update({'_id':record['_id']},{'$set':{'fs_site':new_fs_site, 'fs_uuid':new_fs_uuid}}) |
c6b51b82fa0503a2696161374160c47297211c7c | qubs_data_api/urls.py | qubs_data_api/urls.py | from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
]
| from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('core.urls')),
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
]
| Include Core URLS at the base URL path. | Include Core URLS at the base URL path.
| Python | apache-2.0 | qubs/data-centre,qubs/data-centre,qubs/climate-data-api,qubs/climate-data-api | ---
+++
@@ -2,6 +2,7 @@
from django.contrib import admin
urlpatterns = [
+ url(r'^', include('core.urls')),
url(r'^climate/', include('climate.urls')),
url(r'^herbarium/', include('herbarium.urls')),
url(r'^api-auth/', include('rest_framework.urls')), |
102a35d9ce74a4f29be2fc0bb34b80cb7ee4d77d | tests/helper_methods_test.py | tests/helper_methods_test.py | import os
import unittest
from config import Config
class HelperMethodsTest(unittest.TestCase):
def test_that_config_week_is_only_A_or_B(self):
"""
This test ensures that the only value set for 'WEEK'
in the envvars is A or B.
"""
config = Config()
if os.path.exists('./rtmbot.conf'):
config.load_yaml('rtmbot.conf')
else:
config.load_os_environ_vars('FB__')
week_options = ['A', 'B']
self.assertIn(config['WEEK'], week_options)
| import os
import unittest
from config import Config
class HelperMethodsTest(unittest.TestCase):
def test_that_config_week_is_only_A_or_B(self):
"""
This test ensures that the only value set for 'WEEK'
in the envvars is A or B.
"""
config = Config()
week_options = ['A', 'B']
if os.path.exists('./rtmbot.conf'):
config.load_yaml('rtmbot.conf')
self.assertIn(config['WEEK'], week_options)
else:
config.load_os_environ_vars('FB__')
self.assertIn(config['FB__WEEK'], week_options)
| Update tests for config week | Update tests for config week
| Python | mit | andela-kanyanwu/food-bot-review | ---
+++
@@ -11,12 +11,11 @@
in the envvars is A or B.
"""
config = Config()
+ week_options = ['A', 'B']
if os.path.exists('./rtmbot.conf'):
config.load_yaml('rtmbot.conf')
-
+ self.assertIn(config['WEEK'], week_options)
else:
config.load_os_environ_vars('FB__')
-
- week_options = ['A', 'B']
- self.assertIn(config['WEEK'], week_options)
+ self.assertIn(config['FB__WEEK'], week_options) |
126d79011221da6692d70f9a9aba1f335155ab58 | us_ignite/apps/management/commands/app_load_fixtures.py | us_ignite/apps/management/commands/app_load_fixtures.py | from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
)
DOMAIN_LIST = (
'Healthcare',
'Education & Workforce',
'Energy',
'Transportation',
'Entrepreneurship',
'Advanced Manufacturing',
'Public Safety',
'General / Platform / Other',
)
class Command(BaseCommand):
def handle(self, *args, **options):
for feature_name in FEATURE_LIST:
feature, is_new = Feature.objects.get_or_create(name=feature_name)
if is_new:
print "Imported feature: %s" % feature_name
for domain_name in DOMAIN_LIST:
domain, is_new = Domain.objects.get_or_create(name=domain_name)
if is_new:
print "Imported domain: %s" % domain_name
print "Done!"
| from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
'Advanced wireless',
'Ultra-fast/Gigabit to end-user',
'GENI/US Ignite Rack',
'Layer 2',
)
DOMAIN_LIST = (
'Healthcare',
'Education & Workforce',
'Energy',
'Transportation',
'Advanced Manufacturing',
'Public Safety',
'General / Platform / Other',
)
class Command(BaseCommand):
def handle(self, *args, **options):
for feature_name in FEATURE_LIST:
feature, is_new = Feature.objects.get_or_create(name=feature_name)
if is_new:
print "Imported feature: %s" % feature_name
for domain_name in DOMAIN_LIST:
domain, is_new = Domain.objects.get_or_create(name=domain_name)
if is_new:
print "Imported domain: %s" % domain_name
print "Done!"
| Update app domain initial fixtures. | Update app domain initial fixtures.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -10,6 +10,10 @@
'Speed',
'Low-latency',
'Local cloud / edge computing',
+ 'Advanced wireless',
+ 'Ultra-fast/Gigabit to end-user',
+ 'GENI/US Ignite Rack',
+ 'Layer 2',
)
DOMAIN_LIST = (
@@ -17,7 +21,6 @@
'Education & Workforce',
'Energy',
'Transportation',
- 'Entrepreneurship',
'Advanced Manufacturing',
'Public Safety',
'General / Platform / Other', |
0bd76b828fbd81ac85b7384174692e46e8ef3205 | devlol/urls.py | devlol/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', 'devlol.views.index'),
url(r'^diary/event/(?P<event_id>[0-9]+)/$', 'diary.views.item'),
# API Stuff
url(r'^api/events$', 'devlol.views.events'),
# iCal Export
url(r'^export/ical/events.ics$', 'devlol.views.ical'),
# Admin Stuff
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', 'devlol.views.index'),
url(r'^diary/event/(?P<item_id>[0-9]+)/$', 'diary.views.item'),
# API Stuff
url(r'^api/events$', 'devlol.views.events'),
# iCal Export
url(r'^export/ical/events.ics$', 'devlol.views.ical'),
# Admin Stuff
url(r'^admin/', include(admin.site.urls)),
)
| Fix rout for diary/event, argument has to be item_id | Fix rout for diary/event, argument has to be item_id
For error see here: http://devlol.at/diary/event/22/ as an example | Python | mit | DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at | ---
+++
@@ -10,7 +10,7 @@
# Diary Stuff
url(r'^diary/$', 'devlol.views.index'),
- url(r'^diary/event/(?P<event_id>[0-9]+)/$', 'diary.views.item'),
+ url(r'^diary/event/(?P<item_id>[0-9]+)/$', 'diary.views.item'),
# API Stuff
url(r'^api/events$', 'devlol.views.events'), |
6e4e073b4979bbf6099d0054181f13134f8cfe73 | stash_test_case.py | stash_test_case.py | import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patches')
REPOSITORY_URI = os.path.join('test', '.repo')
@classmethod
def setUpClass(cls):
"""Makes sure that stash will look for patches in the patches path in
the test directory, and that the repository directory exists.
"""
if not os.path.exists(cls.REPOSITORY_URI):
os.mkdir(cls.REPOSITORY_URI)
if not os.path.exists(cls.PATCHES_PATH):
os.mkdir(cls.PATCHES_PATH)
Stash.PATCHES_PATH = cls.PATCHES_PATH
@classmethod
def tearDownClass(cls):
"""Cleans up the temporary patches path used for the unit tests."""
if os.path.exists(cls.PATCHES_PATH):
shutil.rmtree(cls.PATCHES_PATH)
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
| import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patches')
REPOSITORY_URI = os.path.join('test', '.repo')
@classmethod
def setUpClass(cls):
"""Makes sure that stash will look for patches in the patches path in
the test directory, and that the repository directory exists.
"""
if not os.path.exists(cls.REPOSITORY_URI):
os.mkdir(cls.REPOSITORY_URI)
if not os.path.exists(cls.PATCHES_PATH):
os.mkdir(cls.PATCHES_PATH)
Stash.PATCHES_PATH = cls.PATCHES_PATH
@classmethod
def tearDownClass(cls):
"""Cleans up the temporary patches path used for the unit tests."""
if os.path.exists(cls.PATCHES_PATH):
shutil.rmtree(cls.PATCHES_PATH)
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
def tearDown(self):
"""Removes all stashed patches."""
for patch_name in os.listdir(self.PATCHES_PATH):
os.unlink(os.path.join(self.PATCHES_PATH, patch_name))
| Remove patches in between unit tests. | Remove patches in between unit tests.
| Python | bsd-3-clause | ton/stash,ton/stash | ---
+++
@@ -36,3 +36,8 @@
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
+
+ def tearDown(self):
+ """Removes all stashed patches."""
+ for patch_name in os.listdir(self.PATCHES_PATH):
+ os.unlink(os.path.join(self.PATCHES_PATH, patch_name)) |
7535e8020b2d29abbe45e724f5ff4f51613d95d0 | survey/__init__.py | survey/__init__.py | import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import settings as app_settings
for setting in dir(app_settings):
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
LOGGER.info("Settings '{}' as the default ('{}')".format(setting, getattr(settings, setting)))
except ImportError:
pass
set_default_settings()
| import logging
LOGGER = logging.getLogger(__name__)
DEFAULT_SETTINGS = [
"CHOICES_SEPARATOR",
"USER_DID_NOT_ANSWER",
"TEX_CONFIGURATION_FILE",
"SURVEY_DEFAULT_PIE_COLOR",
"EXCEL_COMPATIBLE_CSV",
]
def set_default_settings():
try:
from django.conf import settings
from . import settings as app_settings
for setting in dir(app_settings):
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
LOGGER.info("Settings '%s' as the default ('%s')", setting, getattr(settings, setting))
except ImportError:
pass
set_default_settings()
| Fix Use % formatting in logging functions | Fix Use % formatting in logging functions
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey | ---
+++
@@ -20,7 +20,7 @@
if setting in DEFAULT_SETTINGS:
if not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
- LOGGER.info("Settings '{}' as the default ('{}')".format(setting, getattr(settings, setting)))
+ LOGGER.info("Settings '%s' as the default ('%s')", setting, getattr(settings, setting))
except ImportError:
pass
|
d4de0c4fdf205c1107b08ccba0b428125d81de1a | src/biokbase/narrative/common/url_config.py | src/biokbase/narrative/common/url_config.py | import os
import json
class Struct:
def __init__(self, **args):
self.__dict__.update(args)
def get_url(self, key):
self._dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"]
config_json = open(os.path.join(nar_path, "config.json")).read()
config = json.loads(config_json)
url_config = config[config['config']] # fun, right?
URLS = Struct(**url_config)
except:
url_dict = {
"workspace": "https://kbase.us/services/ws/",
"invocation": "https://kbase.us/services/invocation",
"fba": "https://kbase.us/services/KBaseFBAModeling",
"genomeCmp": "https://kbase.us/services/genome_comparison/jsonrpc",
"trees": "https://kbase.us/services/trees",
"log_proxy_port": 32001,
"log_proxy_host": "172.17.42.1"
}
URLS = Struct(**url_dict)
| import os
import json
class Struct:
def __init__(self, **args):
self.__dict__.update(args)
def get_url(self, key):
self.__dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"]
config_json = open(os.path.join(nar_path, "config.json")).read()
config = json.loads(config_json)
url_config = config[config['config']] # fun, right?
URLS = Struct(**url_config)
except:
url_dict = {
"workspace": "https://kbase.us/services/ws/",
"invocation": "https://kbase.us/services/invocation",
"fba": "https://kbase.us/services/KBaseFBAModeling",
"genomeCmp": "https://kbase.us/services/genome_comparison/jsonrpc",
"trees": "https://kbase.us/services/trees",
"log_proxy_port": 32001,
"log_proxy_host": "172.17.42.1"
}
URLS = Struct(**url_dict)
| Fix bug in new url config method | Fix bug in new url config method | Python | mit | msneddon/narrative,psnovichkov/narrative,aekazakov/narrative,msneddon/narrative,psnovichkov/narrative,psnovichkov/narrative,jmchandonia/narrative,briehl/narrative,rsutormin/narrative,aekazakov/narrative,psnovichkov/narrative,psnovichkov/narrative,briehl/narrative,nlharris/narrative,msneddon/narrative,scanon/narrative,jmchandonia/narrative,briehl/narrative,mlhenderson/narrative,pranjan77/narrative,scanon/narrative,jmchandonia/narrative,mlhenderson/narrative,nlharris/narrative,briehl/narrative,psnovichkov/narrative,pranjan77/narrative,pranjan77/narrative,aekazakov/narrative,pranjan77/narrative,kbase/narrative,mlhenderson/narrative,rsutormin/narrative,kbase/narrative,nlharris/narrative,msneddon/narrative,jmchandonia/narrative,aekazakov/narrative,mlhenderson/narrative,rsutormin/narrative,kbase/narrative,aekazakov/narrative,scanon/narrative,msneddon/narrative,scanon/narrative,nlharris/narrative,briehl/narrative,scanon/narrative,nlharris/narrative,mlhenderson/narrative,psnovichkov/narrative,nlharris/narrative,pranjan77/narrative,rsutormin/narrative,briehl/narrative,kbase/narrative,pranjan77/narrative,nlharris/narrative,scanon/narrative,mlhenderson/narrative,rsutormin/narrative,aekazakov/narrative,rsutormin/narrative,pranjan77/narrative,jmchandonia/narrative,briehl/narrative,msneddon/narrative,jmchandonia/narrative,msneddon/narrative,kbase/narrative,kbase/narrative,jmchandonia/narrative | ---
+++
@@ -7,7 +7,7 @@
self.__dict__.update(args)
def get_url(self, key):
- self._dict__.get(key)
+ self.__dict__.get(key)
try:
nar_path = os.environ["NARRATIVEDIR"] |
7c9b0ac281d39cbe8b694a4cb7a4dd0c171351e0 | custom/uth/tasks.py | custom/uth/tasks.py | from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys():
files[f] = upload_doc.fetch_attachment(f)
create_case(upload_doc.related_case_id, files)
# TODO delete doc if processing is successful
@task
def async_find_and_attach(upload_id):
upload_doc = VscanUpload.get(upload_id)
case = match_case(
upload_doc.scanner_serial,
upload_doc.scan_id,
upload_doc.date
)
attach_images_to_case(case, [])
# TODO delete doc if successful
| from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
import io
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys():
files[f] = io.BytesIO(upload_doc.fetch_attachment(f))
create_case(upload_doc.related_case_id, files)
# TODO delete doc if processing is successful
@task
def async_find_and_attach(upload_id):
upload_doc = VscanUpload.get(upload_id)
case = match_case(
upload_doc.scanner_serial,
upload_doc.scan_id,
upload_doc.date
)
attach_images_to_case(case, [])
# TODO delete doc if successful
| Fix file type for post submissions | Fix file type for post submissions
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq | ---
+++
@@ -1,6 +1,7 @@
from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
+import io
@task
@@ -9,7 +10,7 @@
files = {}
for f in upload_doc._attachments.keys():
- files[f] = upload_doc.fetch_attachment(f)
+ files[f] = io.BytesIO(upload_doc.fetch_attachment(f))
create_case(upload_doc.related_case_id, files)
|
7902711589cf3ce0fe492442dbfec2497fd06dc4 | build-aux/dist-docs.py | build-aux/dist-docs.py | #!/usr/bin/env python3
import os
import shutil
import subprocess
from pathlib import PurePath
references = [
'docs/json-glib/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT')
buildroot = os.environ.get('MESON_BUILD_ROOT')
distroot = os.environ.get('MESON_DIST_ROOT')
for reference in references:
src_path = os.path.join(buildroot, reference)
if os.path.isdir(src_path):
dst_path = os.path.join(distroot, reference)
shutil.copytree(src_path, dst_path)
| #!/usr/bin/env python3
import os
import shutil
references = [
'doc/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT')
buildroot = os.environ.get('MESON_BUILD_ROOT')
distroot = os.environ.get('MESON_DIST_ROOT')
for reference in references:
src_path = os.path.join(buildroot, reference)
if os.path.isdir(src_path):
dst_path = os.path.join(distroot, reference)
shutil.copytree(src_path, dst_path)
| Fix the docs path in the dist script | build: Fix the docs path in the dist script
Fixes: #66
| Python | lgpl-2.1 | frida/json-glib,GNOME/json-glib,GNOME/json-glib,frida/json-glib | ---
+++
@@ -2,13 +2,10 @@
import os
import shutil
-import subprocess
-
-from pathlib import PurePath
references = [
- 'docs/json-glib/json-glib-1.0',
+ 'doc/json-glib-1.0',
]
sourceroot = os.environ.get('MESON_SOURCE_ROOT') |
ac00ef4ac08c6e47de80c33a6781d00c7b2bc943 | flask_sockets.py | flask_sockets.py | # -*- coding: utf-8 -*-
def log_request(self):
log = self.server.log
if log:
if hasattr(log, 'info'):
log.info(self.format_request() + '\n')
else:
log.write(self.format_request() + '\n')
# Monkeys are made for freedom.
try:
import gevent
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
except ImportError:
pass
if 'gevent' in locals():
# Freedom-Patch logger for Gunicorn.
if hasattr(gevent, 'pywsgi'):
gevent.pywsgi.WSGIHandler.log_request = log_request
class SocketMiddleware(object):
def __init__(self, wsgi_app, socket):
self.ws = socket
self.app = wsgi_app
def __call__(self, environ, start_response):
path = environ['PATH_INFO']
if path in self.ws.url_map:
handler = self.ws.url_map[path]
environment = environ['wsgi.websocket']
handler(environment)
else:
return self.app(environ, start_response)
class Sockets(object):
def __init__(self, app=None):
self.url_map = {}
if app:
self.init_app(app)
def init_app(self, app):
app.wsgi_app = SocketMiddleware(app.wsgi_app, self)
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
def add_url_rule(self, rule, _, f, **options):
self.url_map[rule] = f
# CLI sugar.
if 'Worker' in locals():
worker = Worker | # -*- coding: utf-8 -*-
from functools import wraps
from flask import request
def log_request(self):
log = self.server.log
if log:
if hasattr(log, 'info'):
log.info(self.format_request() + '\n')
else:
log.write(self.format_request() + '\n')
# Monkeys are made for freedom.
try:
import gevent
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
except ImportError:
pass
if 'gevent' in locals():
# Freedom-Patch logger for Gunicorn.
if hasattr(gevent, 'pywsgi'):
gevent.pywsgi.WSGIHandler.log_request = log_request
class Sockets(object):
def __init__(self, app=None):
self.app = app
def route(self, rule, **options):
def decorator(f):
@wraps(f)
def inner(*args, **kwargs):
return f(request.environ['wsgi.websocket'], *args, **kwargs)
if self.app:
endpoint = options.pop('endpoint', None)
self.app.add_url_rule(rule, endpoint, inner, **options)
return inner
return decorator
# CLI sugar.
if 'Worker' in locals():
worker = Worker
| Use Flask routing to allow for variables in URL | Use Flask routing to allow for variables in URL
| Python | mit | clarkduvall/flask-sockets | ---
+++
@@ -1,4 +1,9 @@
# -*- coding: utf-8 -*-
+
+from functools import wraps
+
+from flask import request
+
def log_request(self):
log = self.server.log
@@ -21,46 +26,25 @@
if hasattr(gevent, 'pywsgi'):
gevent.pywsgi.WSGIHandler.log_request = log_request
-
-
-class SocketMiddleware(object):
-
- def __init__(self, wsgi_app, socket):
- self.ws = socket
- self.app = wsgi_app
-
- def __call__(self, environ, start_response):
- path = environ['PATH_INFO']
-
- if path in self.ws.url_map:
- handler = self.ws.url_map[path]
- environment = environ['wsgi.websocket']
-
- handler(environment)
- else:
- return self.app(environ, start_response)
-
-
class Sockets(object):
def __init__(self, app=None):
- self.url_map = {}
- if app:
- self.init_app(app)
-
- def init_app(self, app):
- app.wsgi_app = SocketMiddleware(app.wsgi_app, self)
+ self.app = app
def route(self, rule, **options):
def decorator(f):
- endpoint = options.pop('endpoint', None)
- self.add_url_rule(rule, endpoint, f, **options)
- return f
+ @wraps(f)
+ def inner(*args, **kwargs):
+ return f(request.environ['wsgi.websocket'], *args, **kwargs)
+
+ if self.app:
+ endpoint = options.pop('endpoint', None)
+ self.app.add_url_rule(rule, endpoint, inner, **options)
+ return inner
+
return decorator
- def add_url_rule(self, rule, _, f, **options):
- self.url_map[rule] = f
# CLI sugar.
if 'Worker' in locals(): |
b77174948721413de84d6037ef4e4329978978cc | taskzilla/views.py | taskzilla/views.py | from django.shortcuts import render
from .models import Task
def index(request):
tasks_list = Task.objects.filter(closed=False)
context = {'tasks_list' : tasks_list,}
return render(request, 'taskzilla/index.html', context)
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
context = {'task' : task}
return render(request, 'taskzilla/task_page.html', context)
| from django.shortcuts import render
from .models import Task
def index(request):
tasks_list = Task.objects.filter(closed=False)
context = {'tasks_list' : tasks_list,}
return render(request, 'taskzilla/index.html', context)
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
context = {'task' : task, 'comments': task.comment_set.all()}
return render(request, 'taskzilla/task_page.html', context)
| Add comments to the Task Page | Views: Add comments to the Task Page
| Python | mit | static-code-generators/taskzilla,jailuthra/taskzilla,jailuthra/taskzilla,static-code-generators/taskzilla,static-code-generators/taskzilla,jailuthra/taskzilla | ---
+++
@@ -9,5 +9,5 @@
def task_page(request, task_id):
task = Task.objects.get(pk=task_id)
- context = {'task' : task}
+ context = {'task' : task, 'comments': task.comment_set.all()}
return render(request, 'taskzilla/task_page.html', context) |
1f13b7734b06e3c9572865734defa0b1afd4db8b | jobs_executor.py | jobs_executor.py | import subprocess
import os
import mail_handler
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
finally:
output = "tmp/output.mobi"
if os.path.isfile(output):
os.remove(output)
def execJob(job):
recipe = "\"%s\".recipe" % job.recipeRef
output = "tmp/output.%s" % settings.format
returned = subprocess.call("ebook-convert %s %s" %(recipe,output) ,shell=True)
if returned != 0:
print "Returned: " + returned
return False
# send the stuff
subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
mail_handler.sendMail(subject, "", output)
# delete the tmp file
os.remove(output)
return True | import subprocess
import os
import mail_handler
import tempfile
from datetime import datetime
from settings_handler import settings
def execJobs(jobs):
try:
for job in jobs:
if not execJob(job):
return False
print "Jobs executed"
return True
except:
print "Executed failed"
return False
def execJob(job):
recipe = "\"%s\".recipe" % job.recipeRef
output = tempfile.mkstemp(suffix="." + settings.format)
outputPath = output[1]
try:
returned = subprocess.call("ebook-convert %s %s" %(recipe,outputPath) ,shell=True)
if returned != 0:
print "Returned: " + returned
return False
# send the stuff
subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
mail_handler.sendMail(subject, "", outputPath)
except Exception, e:
pass
# delete the tmp file
os.remove(outputPath)
return True | Use the tempfile module to create system indipendend temporary file for the output. | Use the tempfile module to create system indipendend temporary file for the output.
closes #1
| Python | apache-2.0 | baumartig/paperboy | ---
+++
@@ -1,6 +1,7 @@
import subprocess
import os
import mail_handler
+import tempfile
from datetime import datetime
from settings_handler import settings
@@ -14,24 +15,24 @@
except:
print "Executed failed"
return False
- finally:
- output = "tmp/output.mobi"
- if os.path.isfile(output):
- os.remove(output)
def execJob(job):
recipe = "\"%s\".recipe" % job.recipeRef
- output = "tmp/output.%s" % settings.format
+ output = tempfile.mkstemp(suffix="." + settings.format)
+ outputPath = output[1]
- returned = subprocess.call("ebook-convert %s %s" %(recipe,output) ,shell=True)
- if returned != 0:
- print "Returned: " + returned
- return False
+ try:
+ returned = subprocess.call("ebook-convert %s %s" %(recipe,outputPath) ,shell=True)
+ if returned != 0:
+ print "Returned: " + returned
+ return False
- # send the stuff
- subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
- mail_handler.sendMail(subject, "", output)
+ # send the stuff
+ subject = "%s %s" % (job.recipeRef, datetime.date(datetime.now()))
+ mail_handler.sendMail(subject, "", outputPath)
+ except Exception, e:
+ pass
# delete the tmp file
- os.remove(output)
+ os.remove(outputPath)
return True |
7ff11cc0d8183a03bb83430236b12aa70ac2f8dc | lib/allosmod/get_ss.py | lib/allosmod/get_ss.py | """Get secondary structure with DSSP."""
from __future__ import print_function, absolute_import
import optparse
import subprocess
def check_output(args, stderr=None, retcode=0, input=None, *other):
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr,
stdin=subprocess.PIPE if input else None,
*other)
stdout, stderr = p.communicate(input)
if p.returncode != retcode:
raise OSError("Process %s exited with code %d"
% (" ".join(args), p.returncode))
return stdout
def get_ss(pdb_file):
out = check_output(["dssp", pdb_file])
start = False
for line in out.split("\n"):
if "RESIDUE AA STRUCTURE" in line:
start = True
elif start and len(line) > 16 and line[11] != ' ':
print(line[16] if line[16] != ' ' else '-')
def parse_args():
usage = """%prog <PDB file>
Get secondary structure of <PDB file> with DSSP, and print the secondary
structure type for each residue, one per line.
"""
parser = optparse.OptionParser(usage)
options, args = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
return args[0]
def main():
pdb_file = parse_args()
get_ss(pdb_file)
if __name__ == '__main__':
main()
| """Get secondary structure with DSSP."""
from __future__ import print_function, absolute_import
import optparse
import subprocess
def check_output(args, stderr=None, retcode=0, input=None, *other):
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr,
stdin=subprocess.PIPE if input else None,
*other)
stdout, stderr = p.communicate(input)
if p.returncode != retcode:
raise OSError("Process %s exited with code %d"
% (" ".join(args), p.returncode))
return stdout
def get_ss(pdb_file):
out = check_output(["dssp", pdb_file])
start = False
for line in out.split("\n"):
if "RESIDUE AA STRUCTURE" in line:
start = True
elif start and len(line) > 16 and line[11] != ' ':
yield line[16] if line[16] != ' ' else '-'
def parse_args():
usage = """%prog <PDB file>
Get secondary structure of <PDB file> with DSSP, and print the secondary
structure type for each residue, one per line.
"""
parser = optparse.OptionParser(usage)
options, args = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
return args[0]
def main():
pdb_file = parse_args()
for res in get_ss(pdb_file):
print(res)
if __name__ == '__main__':
main()
| Return results as a generator, not in a file. | Return results as a generator, not in a file.
| Python | lgpl-2.1 | salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib | ---
+++
@@ -21,7 +21,7 @@
if "RESIDUE AA STRUCTURE" in line:
start = True
elif start and len(line) > 16 and line[11] != ' ':
- print(line[16] if line[16] != ' ' else '-')
+ yield line[16] if line[16] != ' ' else '-'
def parse_args():
usage = """%prog <PDB file>
@@ -37,7 +37,8 @@
def main():
pdb_file = parse_args()
- get_ss(pdb_file)
+ for res in get_ss(pdb_file):
+ print(res)
if __name__ == '__main__':
main() |
b0c7e61178a5eb81dc24aab9911baaeccda546ff | searchapi/__init__.py | searchapi/__init__.py | import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
| import os, logging
from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
app.logger.debug("\nConfiguration\n%s\n" % app.config)
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
| Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/search-api-alpha,LandRegistry/search-api-alpha | ---
+++
@@ -8,6 +8,9 @@
app.logger.debug("\nConfiguration\n%s\n" % app.config)
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
+
# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) |
d49118a52c15b2434a43a717476cdc7340dfc8c6 | test/test_suite.py | test/test_suite.py |
# list examples
a=['spam','eggs',100,1234]
log(a[:2]+['bacon',2*2])
log(3*a[:3]+['Boo!'])
log(a[:])
a[2]=a[2]+23
log(a)
a[0:2]=[1,12]
log(a)
a[0:2]=[]
log(a)
a[1:1]=['bletch','xyzzy']
log(a)
a[:0]=a
log(a)
a[:]=[]
log(a) |
# list examples
a=['spam','eggs',100,1234]
log(a[:2]+['bacon',2*2])
log(3*a[:3]+['Boo!'])
log(a[:])
a[2]=a[2]+23
log(a)
a[0:2]=[1,12]
log(a)
a[0:2]=[]
log(a)
a[1:1]=['bletch','xyzzy']
log(a)
a[:0]=a
log(a)
a[:]=[]
log(a)
a.extend('ab')
log(a)
a.extend([1,2,33])
log(a)
| Test suite copied from Python tutorial | Test suite copied from Python tutorial | Python | bsd-3-clause | sgzwiz/brython,sgzwiz/brython,sgzwiz/brython | ---
+++
@@ -16,3 +16,7 @@
log(a)
a[:]=[]
log(a)
+a.extend('ab')
+log(a)
+a.extend([1,2,33])
+log(a) |
eec8ddc6beb08a02577831b6f64b0455e5c1ef05 | local.py | local.py | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
icon=noticeIcon
) | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Local Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
) | Disable icon temporarily and adjust the debug print statements | Disable icon temporarily and adjust the debug print statements | Python | mit | kfdm/gntp | ---
+++
@@ -3,7 +3,7 @@
class GNTPRegister(gntp.GNTPRegister):
def send(self):
- print 'Sending Registration'
+ print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
@@ -13,7 +13,7 @@
class GNTPNotice(gntp.GNTPNotice):
def send(self):
- print 'Sending Notification'
+ print 'Sending Local Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
@@ -32,5 +32,4 @@
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
- icon=noticeIcon
) |
0d3507d5eb9801b38c66fb03804e15b089fb2233 | tests/cdek_test.py | tests/cdek_test.py | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unreg_user = api.CdekCalc()
def test_valid_get_secure(self, urlopen):
self.assertEqual(self.reg_user._get_secure(
datetime.datetime.today().date(), self.reg_user.auth_password),
'c5750d7c97a89aa33b8e030d4c7a4847')
self.assertNotEqual(self.reg_user._get_secure(
datetime.datetime.today().date() - datetime.timedelta(days=2),
self.reg_user.auth_password), 'c5750d7c97a89aa33b8e030d4c7a4847') | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unreg_user = api.CdekCalc()
def test_valid_get_secure(self, urlopen):
self.assertEqual(self.reg_user._get_secure(
datetime.datetime.strptime('2013-05-30', '%Y-%m-%d'), self.reg_user.auth_password),
'21de6125dbaac7adf68007c6bcf9ac98')
self.assertNotEqual(self.reg_user._get_secure(
datetime.datetime.today().date(), self.reg_user.auth_password),
'21de6125dbaac7adf68007c6bcf9ac98') | Fix date for generate secure_key | Fix date for generate secure_key
| Python | mit | xtelaur/python-cdek,xtelaur/python-cdek | ---
+++
@@ -19,9 +19,9 @@
def test_valid_get_secure(self, urlopen):
self.assertEqual(self.reg_user._get_secure(
- datetime.datetime.today().date(), self.reg_user.auth_password),
- 'c5750d7c97a89aa33b8e030d4c7a4847')
+ datetime.datetime.strptime('2013-05-30', '%Y-%m-%d'), self.reg_user.auth_password),
+ '21de6125dbaac7adf68007c6bcf9ac98')
self.assertNotEqual(self.reg_user._get_secure(
- datetime.datetime.today().date() - datetime.timedelta(days=2),
- self.reg_user.auth_password), 'c5750d7c97a89aa33b8e030d4c7a4847')
+ datetime.datetime.today().date(), self.reg_user.auth_password),
+ '21de6125dbaac7adf68007c6bcf9ac98') |
00fd8b13e36c5e7020b7769f6dcd1afecfb79fb3 | examples/source.py | examples/source.py | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr = tr
self.lost = False
self.loop = get_event_loop()
self.waiter = Future()
self.write_some_data()
def write_some_data(self):
dprint('writing', len(self.data), 'bytes')
self.tr.write(self.data)
if not self.lost:
self.loop.call_soon(self.write_some_data)
def connection_lost(self, exc):
dprint('lost connection', repr(exc))
self.lost = True
self.waiter.set_result(None)
@coroutine
def start(loop):
tr, pr = yield from loop.create_connection(Client, 'localhost', 1111)
dprint('tr =', tr)
dprint('pr =', pr)
res = yield from pr.waiter
return res
def main():
loop = get_event_loop()
loop.run_until_complete(start(loop))
if __name__ == '__main__':
main()
| """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr = tr
self.lost = False
self.loop = get_event_loop()
self.waiter = Future()
self.write_some_data()
def write_some_data(self):
if self.lost:
dprint('lost already')
return
dprint('writing', len(self.data), 'bytes')
self.tr.write(self.data)
self.loop.call_soon(self.write_some_data)
def connection_lost(self, exc):
dprint('lost connection', repr(exc))
self.lost = True
self.waiter.set_result(None)
@coroutine
def start(loop):
tr, pr = yield from loop.create_connection(Client, 'localhost', 1111)
dprint('tr =', tr)
dprint('pr =', pr)
res = yield from pr.waiter
return res
def main():
loop = get_event_loop()
loop.run_until_complete(start(loop))
if __name__ == '__main__':
main()
| Fix logic around lost connection. | Fix logic around lost connection.
| Python | apache-2.0 | Martiusweb/asyncio,manipopopo/asyncio,jashandeep-sohi/asyncio,manipopopo/asyncio,ajdavis/asyncio,1st1/asyncio,gvanrossum/asyncio,manipopopo/asyncio,1st1/asyncio,fallen/asyncio,vxgmichel/asyncio,haypo/trollius,gvanrossum/asyncio,vxgmichel/asyncio,fallen/asyncio,ajdavis/asyncio,gsb-eng/asyncio,jashandeep-sohi/asyncio,Martiusweb/asyncio,jashandeep-sohi/asyncio,gvanrossum/asyncio,fallen/asyncio,haypo/trollius,haypo/trollius,gsb-eng/asyncio,gsb-eng/asyncio,Martiusweb/asyncio,ajdavis/asyncio,1st1/asyncio,vxgmichel/asyncio | ---
+++
@@ -20,10 +20,12 @@
self.write_some_data()
def write_some_data(self):
+ if self.lost:
+ dprint('lost already')
+ return
dprint('writing', len(self.data), 'bytes')
self.tr.write(self.data)
- if not self.lost:
- self.loop.call_soon(self.write_some_data)
+ self.loop.call_soon(self.write_some_data)
def connection_lost(self, exc):
dprint('lost connection', repr(exc)) |
991a376736e50ddd6622947d713f61cebb565c8d | server/server/urls.py | server/server/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^django/inventory/$', 'inventory.views.index'),
url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'),
url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
url(r'^django/create/inventory/$', 'inventory.views.create'),
url(r'^django/admin/', include(admin.site.urls)),
)
| Add some CRUD URLs to Django. | Add some CRUD URLs to Django.
| Python | agpl-3.0 | TomDataworks/angular-inventory,TomDataworks/angular-inventory | ---
+++
@@ -5,8 +5,12 @@
urlpatterns = patterns('',
# Examples:
- # url(r'^$', 'server.views.home', name='home'),
+ # url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
-
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^django/inventory/$', 'inventory.views.index'),
+ url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'),
+ url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
+ url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
+ url(r'^django/create/inventory/$', 'inventory.views.create'),
+ url(r'^django/admin/', include(admin.site.urls)),
) |
4823b42b23580e0a294c1e4ddb3b5b62abf9c7bc | sf/mmck/parameters.py | sf/mmck/parameters.py | from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def __init__(self, default=None, label=None, range=None, step=1):
super(Integer, self).__init__(default, label)
self.range = range
self.step = step
class PathList(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else []
super().__init__(default, label)
class String(Parameter):
def __init__(self, default=None, label=None, choices=None):
super(String, self).__init__(default, label)
self.choices = choices
| from collections import OrderedDict
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def __init__(self, default=None, label=None, range=None, step=1):
super(Integer, self).__init__(default, label)
self.range = range
self.step = step
class KeyValuePairs(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else OrderedDict()
super().__init__(default, label)
class PathList(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else []
super().__init__(default, label)
class String(Parameter):
def __init__(self, default=None, label=None, choices=None):
super(String, self).__init__(default, label)
self.choices = choices
| Add a key/value pairs parameter type | Add a key/value pairs parameter type
| Python | mit | metrasynth/solar-flares | ---
+++
@@ -1,3 +1,5 @@
+from collections import OrderedDict
+
from sf.lib.orderedattrdict import OrderedAttrDict
@@ -24,6 +26,13 @@
self.step = step
+class KeyValuePairs(Parameter):
+
+ def __init__(self, default=None, label=None):
+ default = default if default is not None else OrderedDict()
+ super().__init__(default, label)
+
+
class PathList(Parameter):
def __init__(self, default=None, label=None): |
ab83da7b6152dfdc50cf40fa328f3c3d24c13861 | emailmgr/urls.py | emailmgr/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^email/add/$',
email_add,
name='emailmgr_email_add'
),
url(
r'^email/send_activation/(?P<identifier>\w+)/$',
email_send_activation,
name='emailmgr_email_send_activation'
),
url(
r'^email/activate/(?P<identifier>\w+)/$',
email_activate,
name='emailmgr_email_activate'
),
url(
r'^email/make_primary/(?P<identifier>\w+)/$',
email_make_primary,
name='emailmgr_email_make_primary'
),
url(
r'^email/delete/(?P<identifier>\w+)/$',
email_delete,
name='emailmgr_email_delete'
),
url(
r'^email/$',
email_list,
name='emailmgr_email_list'
),
) | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^email/add/$',
email_add,
name='emailmgr_email_add'
),
url(
r'^email/send_activation/(?P<identifier>\w+)/$',
email_send_activation,
name='emailmgr_email_send_activation'
),
url(
r'^email/activate/(?P<identifier>\w+)/$',
email_activate,
name='emailmgr_email_activate'
),
url(
r'^email/make_primary/(?P<identifier>\w+)/$',
email_make_primary,
name='emailmgr_email_make_primary'
),
url(
r'^email/delete/(?P<identifier>\w+)/$',
email_delete,
name='emailmgr_email_delete'
),
url(
r'^email/$',
email_list,
name='emailmgr_email_list'
),
)
| Fix import for django 1.6 | Fix import for django 1.6 | Python | bsd-3-clause | un33k/django-emailmgr,un33k/django-emailmgr | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from django.conf.urls.defaults import patterns, include, url
+from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary |
aa15e9195c6e16ec000338e71051f64a692642e0 | nightreads/user_manager/forms.py | nightreads/user_manager/forms.py | from django.contrib.auth.models import User
from django import forms
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags'].split(',')
return [t.strip().lower() for t in tags]
class UnsubscribeForm(forms.Form):
email = forms.EmailField()
class ConfirmEmailForm(forms.Form):
email = forms.EmailField()
subscribe = forms.IntegerField()
code = forms.CharField(max_length=80)
def clean_subscribe(self):
value = bool(self.cleaned_data['subscribe'])
self.cleaned_data['subscribe'] = value
return value
def clean(self):
cleaned_data = super(ConfirmEmailForm, self).clean()
if self.errors:
return cleaned_data
email = cleaned_data['email']
code = cleaned_data['code']
user = User.objects.filter(username=email).first()
if not user:
raise forms.ValidationError('Email not found')
self.cleaned_data['user'] = user
if user.emailverification.is_key_expired():
raise forms.ValidationError('Link expired, please regenerate')
if not user.emailverification.key == code:
raise forms.ValidationError('Invalid Link')
return cleaned_data
| from django.contrib.auth.models import User
from django.core.signing import BadSignature, SignatureExpired
from django import forms
from . import user_service
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags'].split(',')
return [t.strip().lower() for t in tags]
class UnsubscribeForm(forms.Form):
email = forms.EmailField()
class ConfirmEmailForm(forms.Form):
email = forms.EmailField()
subscribe = forms.IntegerField()
code = forms.CharField(max_length=80)
def clean_subscribe(self):
value = bool(self.cleaned_data['subscribe'])
self.cleaned_data['subscribe'] = value
return value
def clean(self):
cleaned_data = super(ConfirmEmailForm, self).clean()
if self.errors:
return cleaned_data
email = cleaned_data['email']
code = cleaned_data['code']
for_subscription = cleaned_data['subscribe']
user = User.objects.filter(username=email).first()
if not user:
raise forms.ValidationError('Email not found')
self.cleaned_data['user'] = user
try:
user_service.validate_key(key=code, user=user,
for_subscription=for_subscription)
except BadSignature:
raise forms.ValidationError('Invalid Link')
except SignatureExpired:
raise forms.ValidationError('Link expired, please regenerate')
return cleaned_data
| Update `ConfirmEmailForm` to use `user_service.validate_key` | Update `ConfirmEmailForm` to use `user_service.validate_key`
| Python | mit | avinassh/nightreads,avinassh/nightreads | ---
+++
@@ -1,5 +1,8 @@
from django.contrib.auth.models import User
+from django.core.signing import BadSignature, SignatureExpired
from django import forms
+
+from . import user_service
class SubscribeForm(forms.Form):
@@ -31,12 +34,16 @@
return cleaned_data
email = cleaned_data['email']
code = cleaned_data['code']
+ for_subscription = cleaned_data['subscribe']
user = User.objects.filter(username=email).first()
if not user:
raise forms.ValidationError('Email not found')
self.cleaned_data['user'] = user
- if user.emailverification.is_key_expired():
+ try:
+ user_service.validate_key(key=code, user=user,
+ for_subscription=for_subscription)
+ except BadSignature:
+ raise forms.ValidationError('Invalid Link')
+ except SignatureExpired:
raise forms.ValidationError('Link expired, please regenerate')
- if not user.emailverification.key == code:
- raise forms.ValidationError('Invalid Link')
return cleaned_data |
d3356d42aa083ecebf53bb7792a573ed2289173b | unityparser/csharp/csharp_class_body_parser.py | unityparser/csharp/csharp_class_body_parser.py | import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from csharp_element import CSharpElement
import csharp_class_method_parser
import csharp_class_member_parser
import csharp_class_property_parser
# class_region = (token_start, token_end) of enclosure class
def parse_tokens(tokens_data, class_region, class_name, class_instance):
tokens_data = csharp_class_method_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
tokens_data = csharp_class_member_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
return tokens_data | import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from csharp_element import CSharpElement
import csharp_class_method_parser
import csharp_class_member_parser
# import csharp_class_property_parser
# class_region = (token_start, token_end) of enclosure class
def parse_tokens(tokens_data, class_region, class_name, class_instance):
tokens_data = csharp_class_method_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
tokens_data = csharp_class_member_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
# tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
return tokens_data | Comment out property parser due to commit mistake | Comment out property parser due to commit mistake
| Python | mit | adrianogil/SublimeUnityIntel | ---
+++
@@ -12,12 +12,12 @@
import csharp_class_method_parser
import csharp_class_member_parser
-import csharp_class_property_parser
+# import csharp_class_property_parser
# class_region = (token_start, token_end) of enclosure class
def parse_tokens(tokens_data, class_region, class_name, class_instance):
tokens_data = csharp_class_method_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
tokens_data = csharp_class_member_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
- tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
+ # tokens_data = csharp_class_property_parser.parse_tokens(tokens_data, class_region, class_name, class_instance)
return tokens_data |
8f226fffd17b9d89d916ad4a1c42d43afc1f0634 | minitrue/utils.py | minitrue/utils.py | """
Generically useful utilities.
"""
import urlparse
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self.kw = {}
def kwarg(self, kwargName=None):
"""
Decorator to pass a function as a kwarg on construction.
"""
def decorator(f):
name = f.__name__ if kwargName is None else kwargName
self.kw[name] = f
return f
return decorator
def __call__(self):
return self.factory(**self.kw)
def passthrough(f):
def callback(result, *a, **kw):
f(*a, **kw)
return result
return callback
def replace(url, **kw):
split = urlparse.urlsplit(url)._replace(**kw)
return urlparse.urlunsplit(split)
class Combined(object):
def __init__(self):
self._fs = []
def part(self, f):
self._fs.append(f)
return f
def __call__(self, *a, **kw):
for f in self._fs:
f(*a, **kw)
| """
Generically useful utilities.
"""
import urlparse
from twisted.internet import defer
from twisted.python import log
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self.kw = {}
def kwarg(self, kwargName=None):
"""
Decorator to pass a function as a kwarg on construction.
"""
def decorator(f):
name = f.__name__ if kwargName is None else kwargName
self.kw[name] = f
return f
return decorator
def __call__(self):
return self.factory(**self.kw)
def passthrough(f):
def callback(result, *a, **kw):
f(*a, **kw)
return result
return callback
def replace(url, **kw):
split = urlparse.urlsplit(url)._replace(**kw)
return urlparse.urlunsplit(split)
class Combined(object):
def __init__(self):
self._fs = []
def part(self, f):
self._fs.append(f)
return f
def __call__(self, *a, **kw):
ds = [defer.maybeDeferred(f, *a, **kw) for f in self._fs]
return defer.DeferredList(ds)
class OrderedCombined(Combined):
@defer.inlineCallbacks
def __call__(self, *a, **kw):
for f in self._fs:
yield defer.maybeDeferred(f, *a, **kw)
| Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution. | Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution.
| Python | isc | lvh/minitrue | ---
+++
@@ -2,6 +2,9 @@
Generically useful utilities.
"""
import urlparse
+
+from twisted.internet import defer
+from twisted.python import log
try: # pragma: no cover
from cStringIO import StringIO; StringIO
@@ -54,5 +57,13 @@
def __call__(self, *a, **kw):
+ ds = [defer.maybeDeferred(f, *a, **kw) for f in self._fs]
+ return defer.DeferredList(ds)
+
+
+
+class OrderedCombined(Combined):
+ @defer.inlineCallbacks
+ def __call__(self, *a, **kw):
for f in self._fs:
- f(*a, **kw)
+ yield defer.maybeDeferred(f, *a, **kw) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.