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
e5b341c7ddbd085e7203276398bdf10a1d86446b
fastapi/__init__.py
fastapi/__init__.py
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.1.16" from .applications import FastAPI from .routing import APIRouter from .params import Body, Path, Query, Header, Cookie, Form, File, Security, Depends
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.1.17" from .applications import FastAPI from .routing import APIRouter from .params import Body, Path, Query, Header, Cookie, Form, File, Security, Depends
Bump version after fix for constrained bytes
:bookmark: Bump version after fix for constrained bytes
Python
mit
tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi
--- +++ @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.1.16" +__version__ = "0.1.17" from .applications import FastAPI from .routing import APIRouter
752dca349d9f93c2a756e0b1b891006159eecbad
impactstoryanalytics/highcharts.py
impactstoryanalytics/highcharts.py
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': 'null'}, 'subtitle': {'text': 'null'}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker': { 'enabled': False } } }, }
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': None}, 'subtitle': {'text': None}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker': { 'enabled': False } } }, }
Use None instead of "null" in Highcharts boilerplate
Use None instead of "null" in Highcharts boilerplate
Python
mit
Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,total-impact/impactstory-analytics,Impactstory/impactstory-analytics,total-impact/impactstory-analytics
--- +++ @@ -4,8 +4,8 @@ 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, - 'title': {'text': 'null'}, - 'subtitle': {'text': 'null'}, + 'title': {'text': None}, + 'subtitle': {'text': None}, 'credits': { 'enabled': False },
aee8d2911c3f19a9b748f21ae82592d823e0c57e
update.py
update.py
#! /usr/bin/python import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', 'public/', 's3://tempura.8-p.info/' ])
#! /usr/bin/python import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ])
Set ACL explicitly to make files readable
Set ACL explicitly to make files readable
Python
mit
kzys/planet-tempura
--- +++ @@ -9,4 +9,5 @@ subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', + '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ])
9656b9fb1590513398bfca20f53483c6397b8095
morepath/generic.py
morepath/generic.py
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ @reg.generic def app(obj): """Get the application that this object is associated with. """ @reg.generic def base(model): """Get the base that this model is associated with. """ @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ @reg.generic def link(request, model): """Create a link (URL) to model. """ @reg.generic def traject(obj): """Get traject for obj. """ @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ raise NotImplementedError @reg.generic def app(obj): """Get the application that this object is associated with. """ raise NotImplementedError @reg.generic def base(model): """Get the base that this model is associated with. """ raise NotImplementedError @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ raise NotImplementedError @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ raise NotImplementedError @reg.generic def link(request, model): """Create a link (URL) to model. """ raise NotImplementedError @reg.generic def traject(obj): """Get traject for obj. """ raise NotImplementedError @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ raise NotImplementedError @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """ raise NotImplementedError
Raise NotImplementedError for basic stuff.
Raise NotImplementedError for basic stuff.
Python
bsd-3-clause
morepath/morepath,faassen/morepath,taschini/morepath
--- +++ @@ -5,42 +5,49 @@ def consumer(obj): """A consumer consumes steps in a stack to find an object. """ + raise NotImplementedError @reg.generic def app(obj): """Get the application that this object is associated with. """ + raise NotImplementedError @reg.generic def base(model): """Get the base that this model is associated with. """ + raise NotImplementedError @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ + raise NotImplementedError @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ + raise NotImplementedError @reg.generic def link(request, model): """Create a link (URL) to model. """ + raise NotImplementedError @reg.generic def traject(obj): """Get traject for obj. """ + raise NotImplementedError @reg.generic @@ -52,9 +59,11 @@ returned, the string is converted to a Response with the string as the response body. """ + raise NotImplementedError @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """ + raise NotImplementedError
8723611817a982907f3f0a98ed4678d587597002
src/appleseed.python/test/runtests.py
src/appleseed.python/test/runtests.py
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import unittest from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import unittest from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
Add new unit tests to collection
Add new unit tests to collection
Python
mit
pjessesco/appleseed,dictoon/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,glebmish/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,dictoon/appleseed,luisbarrancos/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,dictoon/appleseed,aiivashchenko/appleseed,gospodnetic/appleseed,gospodnetic/appleseed,Biart95/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,Biart95/appleseed,dictoon/appleseed,aiivashchenko/appleseed,aiivashchenko/appleseed,Aakash1312/appleseed,Biart95/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,dictoon/appleseed,appleseedhq/appleseed,Aakash1312/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,pjessesco/appleseed,glebmish/appleseed,aiivashchenko/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,aytekaman/appleseed,est77/appleseed,est77/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,glebmish/appleseed,est77/appleseed,appleseedhq/appleseed
--- +++ @@ -28,6 +28,7 @@ import unittest +from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import *
e85883389dd14377d63fc8c0b4decf486b3b7c2c
conveyor/exceptions.py
conveyor/exceptions.py
class HashMismatch(ValueError): """ Raised when the incoming hash of a file does not match the expected. """
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class HashMismatch(ValueError): """ Raised when the incoming hash of a file does not match the expected. """
Bring the standard imports over
Bring the standard imports over
Python
bsd-2-clause
crateio/carrier
--- +++ @@ -1,3 +1,8 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals + + class HashMismatch(ValueError): """ Raised when the incoming hash of a file does not match the expected.
d5acdacbbe4e4a5464b789a92a31b56cb94aa6a0
GTT/test/example_usage.py
GTT/test/example_usage.py
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) my_excel_writer = ew.ExcelWriter("test/testData/test_excel_write.xlsx") my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
""" This module is a general example using test data showing usage of sparks, excel and the studbook structure. """ import os from GTT import SPARKS from GTT import excel as ew from GTT import studBookStruct TEST_DIR = os.path.dirname(__file__) TEST_DATA_DIR = os.path.join(TEST_DIR, 'testData') # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) excel_write = os.path.join(TEST_DATA_DIR, 'test_excel_write.xlsx') my_excel_writer = ew.ExcelWriter(excel_write) my_studbook = studBookStruct.Studbook() my_studbook.add_header(my_sparks_reader.get_header_as_list()) my_studbook.add_records_from_list(my_sparks_reader.get_records_as_list()) my_excel_writer.write_studbook(my_studbook) my_excel_writer.close()
Use the correct excel path.
Use the correct excel path.
Python
mit
314ish/StudbookToolkit
--- +++ @@ -14,7 +14,8 @@ # my_sparks_reader = SPARKS.SPARKSReader("test/testData/test_sparks_data.dbf") moves_data = os.path.join(TEST_DATA_DIR, 'test_moves_data.dbf') my_sparks_reader = SPARKS.SPARKSReader(moves_data) -my_excel_writer = ew.ExcelWriter("test/testData/test_excel_write.xlsx") +excel_write = os.path.join(TEST_DATA_DIR, 'test_excel_write.xlsx') +my_excel_writer = ew.ExcelWriter(excel_write) my_studbook = studBookStruct.Studbook()
e1399a76dc7a3f69f8e4c76127a05652505bc26e
src/pymp/__init__.py
src/pymp/__init__.py
import logging import multiprocessing DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level) return logger if DEBUG: logger = get_logger(logging.DEBUG) else: logger = get_logger() def trace_function(f): if DEBUG: def run(*args, **kwargs): logger.debug("%s called" % repr(f)) value = f(*args, **kwargs) logger.debug("%s returned" % repr(f)) return value return run else: return f
import logging import multiprocessing from pymp.dispatcher import State, Dispatcher, Proxy DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level) return logger if DEBUG: logger = get_logger(logging.DEBUG) else: logger = get_logger() def trace_function(f): if DEBUG: def run(*args, **kwargs): logger.debug("%s called" % repr(f)) value = f(*args, **kwargs) logger.debug("%s returned" % repr(f)) return value return run else: return f
Allow importing from pymp module directly
Allow importing from pymp module directly
Python
mit
ekarulf/pymp
--- +++ @@ -1,5 +1,7 @@ import logging import multiprocessing + +from pymp.dispatcher import State, Dispatcher, Proxy DEBUG = False # for now
faac7b98d3270267b731c97aa0318d532f75610c
dash_table/__init__.py
dash_table/__init__.py
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table`""", stacklevel=2, )
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format import Group` with `from dash.dash_table.Format import Group`""", stacklevel=2, )
Add info on table format helpers to warning message
Add info on table format helpers to warning message
Python
mit
plotly/dash-table,plotly/dash-table,plotly/dash-table
--- +++ @@ -4,6 +4,10 @@ warnings.warn( """ The dash_table package is deprecated. Please replace -`import dash_table` with `from dash import dash_table`""", +`import dash_table` with `from dash import dash_table` + +Also, if you're using any of the table format helpers (e.g. Group), replace +`from dash_table.Format import Group` with +`from dash.dash_table.Format import Group`""", stacklevel=2, )
34a2b3a93bd96643d74fcb3c8d2f8db52d18253f
desubot.py
desubot.py
from motobot.irc_bot import IRCBot, IRCLevel import desubot import threading def worker(): desubot.bot.run() def main(): desubot.bot.load_plugins('plugins') desubot.bot.join('#Moto-chan') thread = threading.Thread(target=worker) thread.start() while True: msg = input() if msg.startswith(':'): desubot.bot.load_plugins('plugins') else: desubot.bot.send(msg) if __name__ == '__main__': main() else: bot = IRCBot('desutest', 'irc.rizon.net', command_prefix='!')
from motobot.irc_bot import IRCBot, IRCLevel import desubot import threading import traceback def worker(): desubot.bot.run() def main(): desubot.bot.load_plugins('plugins') desubot.bot.join('#Moto-chan') desubot.bot.join('#animu') desubot.bot.join('#anime-planet.com') thread = threading.Thread(target=worker) thread.start() while True: try: msg = input() if msg.startswith(':'): desubot.bot.load_plugins('plugins') else: desubot.bot.send(msg) except: traceback.print_exc() if __name__ == '__main__': main() else: bot = IRCBot('desubot', 'irc.rizon.net', command_prefix='!')
Make exception on reload not crash input
Make exception on reload not crash input
Python
mit
Motoko11/MotoBot
--- +++ @@ -1,6 +1,7 @@ from motobot.irc_bot import IRCBot, IRCLevel import desubot import threading +import traceback def worker(): desubot.bot.run() @@ -8,19 +9,24 @@ def main(): desubot.bot.load_plugins('plugins') desubot.bot.join('#Moto-chan') + desubot.bot.join('#animu') + desubot.bot.join('#anime-planet.com') thread = threading.Thread(target=worker) thread.start() while True: - msg = input() - if msg.startswith(':'): - desubot.bot.load_plugins('plugins') - else: - desubot.bot.send(msg) + try: + msg = input() + if msg.startswith(':'): + desubot.bot.load_plugins('plugins') + else: + desubot.bot.send(msg) + except: + traceback.print_exc() if __name__ == '__main__': main() else: - bot = IRCBot('desutest', 'irc.rizon.net', command_prefix='!') + bot = IRCBot('desubot', 'irc.rizon.net', command_prefix='!')
61421a84d908d89925abeefb189f62c024ab8e83
mopidy_mpris/__init__.py
mopidy_mpris/__init__.py
from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.4.0' class Extension(ext.Extension): dist_name = 'Mopidy-MPRIS' ext_name = 'mpris' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['desktop_file'] = config.Path() schema['bus_type'] = config.String(choices=['session', 'system']) return schema def validate_environment(self): try: import dbus # noqa except ImportError as e: raise exceptions.ExtensionError('dbus library not found', e) def setup(self, registry): from .frontend import MprisFrontend registry.add('frontend', MprisFrontend)
from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '1.4.0' class Extension(ext.Extension): dist_name = 'Mopidy-MPRIS' ext_name = 'mpris' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['desktop_file'] = config.Path() schema['bus_type'] = config.String(choices=['session', 'system']) return schema def validate_environment(self): try: import pydbus # noqa except ImportError as e: raise exceptions.ExtensionError('pydbus library not found', e) def setup(self, registry): from .frontend import MprisFrontend registry.add('frontend', MprisFrontend)
Test for pydbus instead of dbus on startup
Test for pydbus instead of dbus on startup
Python
apache-2.0
mopidy/mopidy-mpris
--- +++ @@ -26,9 +26,9 @@ def validate_environment(self): try: - import dbus # noqa + import pydbus # noqa except ImportError as e: - raise exceptions.ExtensionError('dbus library not found', e) + raise exceptions.ExtensionError('pydbus library not found', e) def setup(self, registry): from .frontend import MprisFrontend
fbd7c3b5627ba288ac400944ee242f3369143291
calico_containers/tests/st/test_container_to_host.py
calico_containers/tests/st/test_container_to_host.py
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop")
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
Clarify test_containers_to_host not using libnetwork
Clarify test_containers_to_host not using libnetwork
Python
apache-2.0
fasaxc/calicoctl,fasaxc/calicoctl,projectcalico/calico-containers,insequent/calico-docker,tomdee/calico-docker,robbrockbank/calico-containers,robbrockbank/calicoctl,Metaswitch/calico-docker,TrimBiggs/calico-containers,tomdee/calico-docker,dalanlan/calico-docker,CiscoCloud/calico-docker,TeaBough/calico-docker,webwurst/calico-docker,webwurst/calico-docker,caseydavenport/calico-containers,quater/calico-containers,quater/calico-containers,dalanlan/calico-docker,TrimBiggs/calico-containers,robbrockbank/calico-docker,fasaxc/calico-docker,tomdee/calico-containers,CiscoCloud/calico-docker,projectcalico/calico-docker,Metaswitch/calico-docker,fasaxc/calico-docker,insequent/calico-docker,projectcalico/calico-docker,caseydavenport/calico-containers,johscheuer/calico-docker,robbrockbank/calicoctl,caseydavenport/calico-docker,projectcalico/calico-containers,alexhersh/calico-docker,johscheuer/calico-docker,TrimBiggs/calico-docker,robbrockbank/calico-containers,caseydavenport/calico-docker,TrimBiggs/calico-docker,robbrockbank/calico-docker,caseydavenport/calico-containers,alexhersh/calico-docker,TeaBough/calico-docker,tomdee/calico-containers,projectcalico/calico-containers
--- +++ @@ -7,11 +7,16 @@ class TestContainerToHost(TestBase): def test_container_to_host(self): """ - Test that a container can ping the host. (Without using the docker - network driver, since it doesn't support that yet.) + Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. + + Note also that we do not use the Docker Network driver for this test. + The Docker Container Network Model defines a "network" as a group of + endpoints that can communicate with each other, but are isolated from + everything else. Thus, an endpoint of a Docker network should not be + able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") @@ -31,9 +36,3 @@ # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) - - # Test the teardown commands - host.calicoctl("profile remove TEST") - host.calicoctl("container remove %s" % node1) - host.calicoctl("pool remove 192.168.0.0/16") - host.calicoctl("node stop")
a5585f7e437a402b10e4fa9094172a10a8955eac
__init__.py
__init__.py
import sys import importlib sys.modules[__package__] = importlib.import_module('.dataset', __package__)
import os __path__.append(os.path.dirname(__file__) + '/dataset') from .dataset import *
Replace importlib hack with __path__
Replace importlib hack with __path__
Python
apache-2.0
analysiscenter/dataset
--- +++ @@ -1,4 +1,4 @@ -import sys -import importlib +import os -sys.modules[__package__] = importlib.import_module('.dataset', __package__) +__path__.append(os.path.dirname(__file__) + '/dataset') +from .dataset import *
e230f3af592ffce613fa7c2bcf05e2993df9e1a6
__init__.py
__init__.py
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by Gabriel Brammer on 2011-05-18. $URL$ $Author$ $Date$ """ __version__ = "$Rev$" from socket import gethostname as hostname if hostname().startswith('uni'): GRISM_HOME = '/3DHST/Spectra/Work/' else: GRISM_HOME = '/research/HST/GRISM/3DHST/' if hostname().startswith('850dhcp8'): GRISM_HOME = '/3DHST/Spectra/Work/' #threedhst.sex.RUN_MODE='direct' import threedhst try: import utils_c #as utils_c except: print """Couldn't import "utils_c" """ import prepare import reduce import candels import analysis import go_3dhst import galfit import plotting import catalogs import survey_paper import go_acs import fast import interlace_fit import intersim noNewLine = '\x1b[1A\x1b[1M'
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by Gabriel Brammer on 2011-05-18. $URL$ $Author$ $Date$ """ __version__ = "$Rev$" from socket import gethostname as hostname if hostname().startswith('uni'): GRISM_HOME = '/3DHST/Spectra/Work/' else: GRISM_HOME = '/research/HST/GRISM/3DHST/' if hostname().startswith('850dhcp8'): GRISM_HOME = '/3DHST/Spectra/Work/' #threedhst.sex.RUN_MODE='direct' import threedhst try: import utils_c #as utils_c except: print """Couldn't import "utils_c" """ import plotting import prepare import reduce import candels import analysis import go_3dhst import galfit import catalogs import survey_paper import go_acs import fast import interlace_fit import intersim noNewLine = '\x1b[1A\x1b[1M'
Add separate "plotting" script for general plot setup.
Add separate "plotting" script for general plot setup. git-svn-id: b93d21f79df1f7407664ec6e512ac344bf52ef2a@711 f9184c78-529c-4a83-b317-4cf1064cc5e0
Python
mit
gbrammer/pygrism,gbrammer/unicorn,gbrammer/unicorn,gbrammer/pygrism
--- +++ @@ -30,13 +30,13 @@ except: print """Couldn't import "utils_c" """ +import plotting import prepare import reduce import candels import analysis import go_3dhst import galfit -import plotting import catalogs import survey_paper
f8de0443c9c03286bb1bc8aabe3aa1badc2db6e3
db/db.py
db/db.py
import sys import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir, self.username), self.password) def save(self): aesjsonfile.dump("%s/%s.json"%(config.dbdir, self.username), self.db, self.password) def accountstodo(self): return self.db["accounts"]
#!/usr/bin/python import sys import copy import json import getpass import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir, self.username), self.password) def save(self): aesjsonfile.dump("%s/%s.json"%(config.dbdir, self.username), self.db, self.password) def accountstodo(self): return self.db["accounts"] def accounts(self): ret = copy.deepcopy(self.db["accounts"]) for acct in ret: acct.pop("password",None) return ret if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) password = getpass.getpass() db = DB(sys.argv[1],password) print "accountstodo" print json.dumps(db.accountstodo(),indent=2) print "accounts" print json.dumps(db.accounts(),indent=2)
Add accounts function, testing mode.
Add accounts function, testing mode.
Python
agpl-3.0
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
--- +++ @@ -1,4 +1,8 @@ +#!/usr/bin/python import sys +import copy +import json +import getpass import aesjsonfile sys.path.append("../") @@ -16,3 +20,19 @@ def accountstodo(self): return self.db["accounts"] + + def accounts(self): + ret = copy.deepcopy(self.db["accounts"]) + for acct in ret: + acct.pop("password",None) + return ret + +if __name__ == "__main__": + if len(sys.argv) < 2: + sys.exit(1) + password = getpass.getpass() + db = DB(sys.argv[1],password) + print "accountstodo" + print json.dumps(db.accountstodo(),indent=2) + print "accounts" + print json.dumps(db.accounts(),indent=2)
57f5d8c1f02aa5d3a1be5fdc7302a15d416071dc
utils/decorators.py
utils/decorators.py
from functools import wraps def bot_only(func): @wraps(func) def inner(self, *args, **kwargs): if not self.user.bot: return return func(self, *args, **kwargs) return inner
from functools import wraps def bot_only(coro): @wraps(coro) async def inner(self, *args, **kwargs): if not self.user.bot: return return await coro(self, *args, **kwargs) return inner
Make bot_only async, because duh
Make bot_only async, because duh
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
--- +++ @@ -1,10 +1,10 @@ from functools import wraps -def bot_only(func): - @wraps(func) - def inner(self, *args, **kwargs): +def bot_only(coro): + @wraps(coro) + async def inner(self, *args, **kwargs): if not self.user.bot: return - return func(self, *args, **kwargs) + return await coro(self, *args, **kwargs) return inner
c2a2628d2a7cfe5c5fb73b0ae4beeeaf6f7bc6c5
kahvid.py
kahvid.py
""" The main measurement program, responsible for polling the sensor periodically and inserting the results into a database. Must be run as root (to access the GPIO and to create a PID). """ #import db, sensor, config import sys # TODO: see http://www.gavinj.net/2012/06/building-python-daemon-process.html import daemon import lockfile import signal from daemon import pidfile #from daemon import runner def main(): import time i = 0 #try: while True: with open("test.txt", "a") as f: #print(i) f.write(str(i) + "\n") i += 1 time.sleep(1) #except KeyboardInterrupt: # print("exiting.") # python daemon example from https://gist.github.com/javisantana/339430 class MyApp(object): def __init__(self): import os self.root = os.path.abspath(os.path.dirname(__file__)) self.run_dir = self.root self.working_directory = self.root #TODO: replace these with actual logging ... self.stdin_path = "/dev/null" self.stdout_path = "./stdout.txt" self.stderr_path = "./stderr.txt" self.pidfile_path = "/var/run/kahvid.pid" self.pidfile_timeout = 1 def run(self): main() #TODO: see example on how to start / stop the daemon using commands ... # https://pagure.io/python-daemon/blob/master/f/daemon/runner.py if __name__ == "__main__": #context = daemon.DaemonContext( # stdout = sys.stdout, # stderr = sys.stderr, # #pidfile = lockfile.FileLock("/var/run/kahvid.pid"), # pidfile = pidfile.TimeoutPIDLockFile("/var/run/kahvid.pid"), # umask = 0o002, # working_directory = ".", # ) #context.signal_map = { ## signal.SIGHUP: "terminate", ## signal.SIGTERM: "terminate", ## signal.SIGUSR1 : "terminate", ## signal.SIGUSR2 : "terminate", ## #signal.SIGUSR0 : "terminate", ## } from daemon.runner import DaemonRunner dr = DaemonRunner(MyApp()) dr.daemon_context.working_directory = "." #TODO #TODO: figure out how to respond to result of do_action ... dr.do_action()
Implement daemon example, now to make it actually do something.
Implement daemon example, now to make it actually do something.
Python
mit
mgunyho/kiltiskahvi
--- +++ @@ -0,0 +1,73 @@ +""" +The main measurement program, responsible for polling the sensor periodically +and inserting the results into a database. + +Must be run as root (to access the GPIO and to create a PID). +""" + +#import db, sensor, config +import sys + +# TODO: see http://www.gavinj.net/2012/06/building-python-daemon-process.html +import daemon +import lockfile +import signal +from daemon import pidfile +#from daemon import runner + +def main(): + import time + i = 0 + #try: + while True: + with open("test.txt", "a") as f: + #print(i) + f.write(str(i) + "\n") + i += 1 + time.sleep(1) + #except KeyboardInterrupt: + # print("exiting.") + +# python daemon example from https://gist.github.com/javisantana/339430 +class MyApp(object): + def __init__(self): + import os + self.root = os.path.abspath(os.path.dirname(__file__)) + self.run_dir = self.root + self.working_directory = self.root + #TODO: replace these with actual logging ... + self.stdin_path = "/dev/null" + self.stdout_path = "./stdout.txt" + self.stderr_path = "./stderr.txt" + self.pidfile_path = "/var/run/kahvid.pid" + self.pidfile_timeout = 1 + + def run(self): + main() + +#TODO: see example on how to start / stop the daemon using commands ... +# https://pagure.io/python-daemon/blob/master/f/daemon/runner.py + +if __name__ == "__main__": + #context = daemon.DaemonContext( + # stdout = sys.stdout, + # stderr = sys.stderr, + # #pidfile = lockfile.FileLock("/var/run/kahvid.pid"), + # pidfile = pidfile.TimeoutPIDLockFile("/var/run/kahvid.pid"), + # umask = 0o002, + # working_directory = ".", + # ) + + #context.signal_map = { + ## signal.SIGHUP: "terminate", + ## signal.SIGTERM: "terminate", + ## signal.SIGUSR1 : "terminate", + ## signal.SIGUSR2 : "terminate", + ## #signal.SIGUSR0 : "terminate", + ## } + + from daemon.runner import DaemonRunner + dr = DaemonRunner(MyApp()) + dr.daemon_context.working_directory = "." #TODO + #TODO: figure out how to respond to result of do_action ... + dr.do_action()
1e775fbc8e11f44b8a680e17ac35e735e52d5739
fabfile.py
fabfile.py
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def fetch_episodes(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py fetchepisodes') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
Add fab command for fetching episodes
Add fab command for fetching episodes
Python
mit
matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik
--- +++ @@ -8,6 +8,11 @@ def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') + + +def fetch_episodes(): + with cd('"{}"'.format(os.path.dirname(__file__))): + run('python3 manage.py fetchepisodes') def setup_dev():
d81ab5b0cc5deecaef53359f422c94c50a4838f5
feed/feed.home.tracer.py
feed/feed.home.tracer.py
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home configuration from common.shconfig import shConfig from common.sheventhandler import shEventHandler import logging as log import time # Simple tracer that 'fires' events on a predefined interval config = shConfig('~/.config/home/home.cfg', name='SentientHome Tracer') handler = shEventHandler(config, config.getfloat('sentienthome', 'tracer_interval', 10)) count = 0 while True: count += 1 # time in milliseconds since epoch tm = time.time()*1000 event = [{ 'name': 'tracer', # Time Series Name 'columns': ['time', 'count'], # Keys 'points': [[tm, count]] # Data points }] log.debug('Event data: %s', event) handler.postEvent(event) # We reset the poll interval in case the configuration has changed handler.sleep(config.getfloat('sentienthome', 'tracer_interval', 10))
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home configuration from common.shconfig import shConfig from common.sheventhandler import shEventHandler import logging as log import time # Simple tracer that 'fires' events on a predefined interval config = shConfig('~/.config/home/home.cfg', name='SentientHome Tracer') handler = shEventHandler(config, config.getfloat('sentienthome', 'tracer_interval', 10)) count = 0 while True: count += 1 event = [{ 'name': 'tracer', # Time Series Name 'columns': ['time', 'count'], # Keys # time in milliseconds since epoch 'points': [[time.time()*1000, count]] # Data points }] log.debug('Event data: %s', event) handler.postEvent(event) # We reset the poll interval in case the configuration has changed handler.sleep(config.getfloat('sentienthome', 'tracer_interval', 10))
Simplify - Less is more
Simplify - Less is more
Python
apache-2.0
fxstein/SentientHome
--- +++ @@ -24,12 +24,11 @@ while True: count += 1 - # time in milliseconds since epoch - tm = time.time()*1000 event = [{ 'name': 'tracer', # Time Series Name 'columns': ['time', 'count'], # Keys - 'points': [[tm, count]] # Data points + # time in milliseconds since epoch + 'points': [[time.time()*1000, count]] # Data points }] log.debug('Event data: %s', event)
e41d46fe0539aa102a8af92236add5ba876db7a0
elections/mixins.py
elections/mixins.py
from django.conf import settings from django.http import Http404 from django.utils.translation import ugettext as _ class ElectionMixin(object): '''A mixin to add election data from the URL to the context''' def dispatch(self, request, *args, **kwargs): self.election = election = self.kwargs['election'] if election not in settings.ELECTIONS: raise Http404(_("Unknown election: '{election}'").format(election=election)) self.election_data = settings.ELECTIONS[election] return super(ElectionMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ElectionMixin, self).get_context_data(**kwargs) context['election'] = self.election context['election_data'] = self.election_data return context
from django.utils.translation import ugettext as _ from django.shortcuts import get_object_or_404 from models import Election class ElectionMixin(object): '''A mixin to add election data from the URL to the context''' def dispatch(self, request, *args, **kwargs): self.election = election = self.kwargs['election'] self.election_data = get_object_or_404(Election, slug=election) return super(ElectionMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ElectionMixin, self).get_context_data(**kwargs) context['election'] = self.election context['election_data'] = self.election_data return context
Use the Election model in the elections Mixin
Use the Election model in the elections Mixin
Python
agpl-3.0
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit
--- +++ @@ -1,16 +1,14 @@ -from django.conf import settings -from django.http import Http404 from django.utils.translation import ugettext as _ +from django.shortcuts import get_object_or_404 +from models import Election class ElectionMixin(object): '''A mixin to add election data from the URL to the context''' def dispatch(self, request, *args, **kwargs): self.election = election = self.kwargs['election'] - if election not in settings.ELECTIONS: - raise Http404(_("Unknown election: '{election}'").format(election=election)) - self.election_data = settings.ELECTIONS[election] + self.election_data = get_object_or_404(Election, slug=election) return super(ElectionMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs):
d9e7816da08a3d66e63356ea6f4474cc5f7d6b26
bush/main.py
bush/main.py
from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() spinner.stop() if output: print("\n".join(output))
import sys import traceback from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 from bush.aws.iam import IAM def run(): (options, args) = option.parse_args("bush") output = '' spinner = Spinner() spinner.start() try: output = run_aws(options, args) except: spinner.stop() traceback.print_exc() sys.exit(2) spinner.stop() if output: print("\n".join(output)) def run_aws(options, args): if args[0] == 'ec2': ec2 = EC2(options) if args[1] == 'ls': output = ec2.ls() elif args[1] == "images": output = ec2.images() if args[0] == 'iam': iam = IAM(options) if args[1] == 'users': output = iam.list_users() if args[1] == 'keys': output = iam.list_access_keys() return output
Fix keep turning spinner when error occurred
Fix keep turning spinner when error occurred
Python
mit
okamos/bush
--- +++ @@ -1,3 +1,6 @@ +import sys +import traceback + from bush import option from bush.spinner import Spinner from bush.aws.ec2 import EC2 @@ -11,6 +14,18 @@ spinner = Spinner() spinner.start() + try: + output = run_aws(options, args) + except: + spinner.stop() + traceback.print_exc() + sys.exit(2) + + spinner.stop() + if output: + print("\n".join(output)) + +def run_aws(options, args): if args[0] == 'ec2': ec2 = EC2(options) @@ -28,6 +43,4 @@ if args[1] == 'keys': output = iam.list_access_keys() - spinner.stop() - if output: - print("\n".join(output)) + return output
18c99ee2b96564913cbd406bb540af10b078b2f3
example.py
example.py
from datetime import datetime from timetabler.schedule import Schedule from timetabler.ssc.course import Lecture, Discussion def main(): s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"], session="2014W", terms=[2]) # STTs are for Vantage College students s.courses["GEOG 122"].add_constraint( lambda acts: all(a.status not in [u"STT"] for a in acts) ) # Default sections contained a Tutorial but that is for Vantage # students, so removing that and only setting Lecture and Discussion s.courses["GEOG 122"].num_section_constraints = [ (Lecture, 1), (Discussion, 1) ] return s.generate_schedules() if __name__ == '__main__': start_time = datetime.now() scheds = main() print(datetime.now() - start_time)
import json from datetime import datetime from timetabler.schedule import Schedule from timetabler.ssc.course import Lecture, Discussion def main(): s = Schedule(["EECE 353", "CPSC 304", "EECE 381", "GEOG 122"], session="2014W", terms=[2]) # STTs are for Vantage College students s.courses["GEOG 122"].add_constraint( lambda acts: all(a.status not in [u"STT"] for a in acts) ) # Default sections contained a Tutorial but that is for Vantage # students, so removing that and only setting Lecture and Discussion s.courses["GEOG 122"].num_section_constraints = [ (Lecture, 1), (Discussion, 1) ] return s.generate_schedules() if __name__ == '__main__': start_time = datetime.now() scheds = main() # Unwrap activities out of course-specific tuples scheds = [[act for crs in sched for act in crs] for sched in scheds] # Sort so that the sum of starting times for courses # throughout the week are greatest scheds = sorted( scheds, key=lambda s: sum(int(a.start_time.replace(":", "")) for a in s), reverse=True ) print("Schedule with latest starting times (sum): {}".format( json.dumps([repr(s) for s in scheds[0]], indent=4) )) print("This took {} to calculate.".format( datetime.now() - start_time ))
Add latest starting time sorting
Add latest starting time sorting
Python
mit
hfaran/ubc-timetabler
--- +++ @@ -1,3 +1,4 @@ +import json from datetime import datetime from timetabler.schedule import Schedule @@ -22,4 +23,19 @@ if __name__ == '__main__': start_time = datetime.now() scheds = main() - print(datetime.now() - start_time) + # Unwrap activities out of course-specific tuples + scheds = [[act for crs in sched for act in crs] + for sched in scheds] + # Sort so that the sum of starting times for courses + # throughout the week are greatest + scheds = sorted( + scheds, + key=lambda s: sum(int(a.start_time.replace(":", "")) for a in s), + reverse=True + ) + print("Schedule with latest starting times (sum): {}".format( + json.dumps([repr(s) for s in scheds[0]], indent=4) + )) + print("This took {} to calculate.".format( + datetime.now() - start_time + ))
d5e3a4f76121b4c1c38787156c50e0602c4de43f
fabfile.py
fabfile.py
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ] def deploy_page(): run('rm -rf fabric-workshop') run('git clone https://github.com/zkan/fabric-workshop.git') run('sudo cp fabric-workshop/index.html /usr/share/nginx/html') run('sudo service nginx restart')
Add deploy task to deploy a new Nginx index page
Add deploy task to deploy a new Nginx index page
Python
mit
zkan/fabric-workshop,zkan/fabric-workshop
--- +++ @@ -45,3 +45,10 @@ env.hosts = [ 'ubuntu@54.251.184.112:22', ] + + +def deploy_page(): + run('rm -rf fabric-workshop') + run('git clone https://github.com/zkan/fabric-workshop.git') + run('sudo cp fabric-workshop/index.html /usr/share/nginx/html') + run('sudo service nginx restart')
35308ba3dbfc25e86fab720e67d6a9576d6937c9
fabfile.py
fabfile.py
from fabric.api import lcd, local from fabric.decorators import runs_once import os fabfile_dir = os.path.dirname(__file__) def update_theme(): theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx') if not os.path.exists('/tmp/sphinx_rtd_theme'): local('git clone https://github.com/snide/sphinx_rtd_theme.git /tmp/sphinx_rtd_theme') with lcd('/tmp/sphinx_rtd_theme'): local('git remote update') local('git reset --hard origin/master ') local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme %s' % theme_dir) local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/fonts/ %s' % os.path.join(fabfile_dir, 'media', 'font')) local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/badge_only.css %s' % os.path.join(fabfile_dir, 'media', 'css')) local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/theme.css %s' % os.path.join(fabfile_dir, 'media', 'css', 'sphinx_rtd_theme.css')) def i18n(): with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('tx pull') local('./manage.py makemessages --all') #local('tx push -s') local('./manage.py compilemessages') def i18n_docs(): with lcd('docs'): # Update our tanslations local('tx pull -a') local('sphinx-intl build') # Push new ones local('make gettext') local('tx push -s') @runs_once def spider(): local('patu.py -d1 readthedocs.org')
from fabric.api import lcd, local from fabric.decorators import runs_once import os fabfile_dir = os.path.dirname(__file__) def i18n(): with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('tx pull') local('./manage.py makemessages --all') #local('tx push -s') local('./manage.py compilemessages') def i18n_docs(): with lcd('docs'): # Update our tanslations local('tx pull -a') local('sphinx-intl build') # Push new ones local('make gettext') local('tx push -s') @runs_once def spider(): local('patu.py -d1 readthedocs.org')
Drop fab file task for updating theme as well
Drop fab file task for updating theme as well
Python
mit
espdev/readthedocs.org,pombredanne/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,techtonik/readthedocs.org,wijerasa/readthedocs.org,techtonik/readthedocs.org,espdev/readthedocs.org,stevepiercy/readthedocs.org,gjtorikian/readthedocs.org,espdev/readthedocs.org,clarkperkins/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,SteveViss/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,stevepiercy/readthedocs.org,emawind84/readthedocs.org,SteveViss/readthedocs.org,emawind84/readthedocs.org,wijerasa/readthedocs.org,espdev/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,SteveViss/readthedocs.org,stevepiercy/readthedocs.org,pombredanne/readthedocs.org,tddv/readthedocs.org,rtfd/readthedocs.org,clarkperkins/readthedocs.org,istresearch/readthedocs.org,clarkperkins/readthedocs.org,istresearch/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,SteveViss/readthedocs.org,safwanrahman/readthedocs.org,gjtorikian/readthedocs.org,istresearch/readthedocs.org,techtonik/readthedocs.org,gjtorikian/readthedocs.org,istresearch/readthedocs.org,emawind84/readthedocs.org,techtonik/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,clarkperkins/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org
--- +++ @@ -4,20 +4,6 @@ import os fabfile_dir = os.path.dirname(__file__) - - -def update_theme(): - theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx') - if not os.path.exists('/tmp/sphinx_rtd_theme'): - local('git clone https://github.com/snide/sphinx_rtd_theme.git /tmp/sphinx_rtd_theme') - with lcd('/tmp/sphinx_rtd_theme'): - local('git remote update') - local('git reset --hard origin/master ') - local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme %s' % theme_dir) - local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/fonts/ %s' % os.path.join(fabfile_dir, 'media', 'font')) - local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/badge_only.css %s' % os.path.join(fabfile_dir, 'media', 'css')) - local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/theme.css %s' % - os.path.join(fabfile_dir, 'media', 'css', 'sphinx_rtd_theme.css')) def i18n():
97990ea039228eb3311b148c047fae015a4f4d7e
examples/boilerplates/base_test_case.py
examples/boilerplates/base_test_case.py
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. With Python 3, simplify "super(...)" to super().setUp() and super().tearDown() ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def setUp(self): super(BaseTestCase, self).setUp() # <<< Add custom setUp code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() # <<< Add custom tearDown code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. With Python 3, simplify "super(...)" to super().setUp() and super().tearDown() ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def setUp(self): super(BaseTestCase, self).setUp() # <<< Run custom setUp() code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() if self.has_exception(): # <<< Run custom code if the test failed. >>> pass else: # <<< Run custom code if the test passed. >>> pass # (Wrap unreliable tearDown() code in a try/except block.) # <<< Run custom tearDown() code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
Update the boilerplate example by adding "has_exception()"
Update the boilerplate example by adding "has_exception()"
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
--- +++ @@ -13,11 +13,18 @@ def setUp(self): super(BaseTestCase, self).setUp() - # <<< Add custom setUp code for tests AFTER the super().setUp() >>> + # <<< Run custom setUp() code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() - # <<< Add custom tearDown code BEFORE the super().tearDown() >>> + if self.has_exception(): + # <<< Run custom code if the test failed. >>> + pass + else: + # <<< Run custom code if the test passed. >>> + pass + # (Wrap unreliable tearDown() code in a try/except block.) + # <<< Run custom tearDown() code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self):
88964dc79be1c88f1a197c5a59f342c9b7749ed2
fantasyStocks/stocks/views.py
fantasyStocks/stocks/views.py
from django.shortcuts import render from django.http import HttpResponse from stocks import forms # Create your views here. def index(request): regForm = forms.RegistrationForm() logForm = forms.LoginForm() return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) def instructions(request): return render(request, "instructions.html")
from django.shortcuts import render from django.http import HttpResponse from stocks import forms from django.contrib.auth.models import User # Create your views here. def index(request): # If we got here through a submission... if request.method == "POST": if request.POST.get("password1", None): form = forms.RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data["email"], email=form.cleaned_data["email"], password=form.cleaned_data["password"]) user.save() else: if form._errors["already_exists"]: error = form._errors["already_exists"] else: error = "There was an error with your registration" elif request.POST["password"]: form = forms.LoginForm(request.POST) else: regForm = forms.RegistrationForm() logForm = forms.LoginForm() return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) def instructions(request): return render(request, "instructions.html")
Make some progress on the view.
Make some progress on the view. I need to make it return a HttpResponse though. oops.
Python
apache-2.0
ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks
--- +++ @@ -1,11 +1,27 @@ from django.shortcuts import render from django.http import HttpResponse from stocks import forms +from django.contrib.auth.models import User # Create your views here. def index(request): - regForm = forms.RegistrationForm() - logForm = forms.LoginForm() - return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) + # If we got here through a submission... + if request.method == "POST": + if request.POST.get("password1", None): + form = forms.RegistrationForm(request.POST) + if form.is_valid(): + user = User.objects.create_user(username=form.cleaned_data["email"], email=form.cleaned_data["email"], password=form.cleaned_data["password"]) + user.save() + else: + if form._errors["already_exists"]: + error = form._errors["already_exists"] + else: + error = "There was an error with your registration" + elif request.POST["password"]: + form = forms.LoginForm(request.POST) + else: + regForm = forms.RegistrationForm() + logForm = forms.LoginForm() + return render(request, "index.html", {"loginForm" : logForm, "registrationForm" : regForm}) def instructions(request): return render(request, "instructions.html")
93af551b8f0ce03b16dd7aad1a2963cc4e5b6d6a
fabfile.py
fabfile.py
from fabric.api import cd, run, sudo, env, roles, execute from datetime import datetime env.roledefs = { 'webuser': ['bloge@andrewlorente.com'], 'sudoer': ['alorente@andrewlorente.com'], } env.hosts = ['andrewlorente.com'] def deploy(): release_id = datetime.now().strftime("%Y%m%d%H%M%S") execute(build, release_id) release(release) @roles('webuser') def build(release_id): releases_dir = "/u/apps/bloge/releases/" run("git clone -q https://github.com/AndrewLorente/bloge.git " + releases_dir + release_id) with cd(releases_dir + release_id): run("cabal update") run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v") run("cabal configure") run("cabal build") run("ln -nfs /u/apps/bloge/releases/{0} " "/u/apps/bloge/current".format(release_id)) @roles('sudoer') def release(*args): sudo("initctl restart bloge")
from fabric.api import cd, run, sudo, env, roles, execute from datetime import datetime env.roledefs = { 'webuser': ['bloge@andrewlorente.com'], 'sudoer': ['alorente@andrewlorente.com'], } env.hosts = ['andrewlorente.com'] def deploy(): release_id = datetime.now().strftime("%Y%m%d%H%M%S") execute(build, release_id) execute(release) @roles('webuser') def build(release_id): releases_dir = "/u/apps/bloge/releases/" run("git clone -q https://github.com/AndrewLorente/bloge.git " + releases_dir + release_id) with cd(releases_dir + release_id): run("cabal update") run("cabal install --constraint 'template-haskell installed' --dependencies-only --force-reinstall -v") run("cabal configure") run("cabal build") run("ln -nfs /u/apps/bloge/releases/{0} " "/u/apps/bloge/current".format(release_id)) @roles('sudoer') def release(): sudo("initctl restart bloge")
Fix the `release` step of deploy
Fix the `release` step of deploy lol
Python
mit
ErinCall/bloge
--- +++ @@ -10,7 +10,7 @@ def deploy(): release_id = datetime.now().strftime("%Y%m%d%H%M%S") execute(build, release_id) - release(release) + execute(release) @roles('webuser') def build(release_id): @@ -26,6 +26,6 @@ "/u/apps/bloge/current".format(release_id)) @roles('sudoer') -def release(*args): +def release(): sudo("initctl restart bloge")
1efbc464c651d99c7482a9674a90fb639f044c6e
mpxapi/__init__.py
mpxapi/__init__.py
from .http import MPXApi from api_base import get_guid_based_id __version__ = '0.0.4' __title__ = 'mpxapi'
from .http import MPXApi from .api_base import get_guid_based_id __version__ = '0.0.4' __title__ = 'mpxapi'
Fix error to handle using mpxapi in subdirs
Fix error to handle using mpxapi in subdirs
Python
mit
blockbuster/mpxapi,blockbuster/mpxapi
--- +++ @@ -1,5 +1,5 @@ from .http import MPXApi -from api_base import get_guid_based_id +from .api_base import get_guid_based_id __version__ = '0.0.4'
cf026dbabffd92cb51baeb63c1e1e88045e946b9
netfields/forms.py
netfields/forms.py
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return self.python_type(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return IP(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
Fix casting in form to_python() method
Fix casting in form to_python() method NetAddressFormField.to_python() was calling "self.python_type()" to cast the form value to an IP() object. Unfortunately, for is no such method defined here, or in the Django forms.Field() class, at least in 1.4 and up
Python
bsd-3-clause
jmacul2/django-postgresql-netfields
--- +++ @@ -35,7 +35,7 @@ if isinstance(value, IP): return value - return self.python_type(value) + return IP(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$')
87bd987ebb802200540c23cfccaba2c56a672ed5
openmc/__init__.py
openmc/__init__.py
from openmc.arithmetic import * from openmc.cell import * from openmc.checkvalue import * from openmc.mesh import * from openmc.element import * from openmc.geometry import * from openmc.nuclide import * from openmc.macroscopic import * from openmc.material import * from openmc.plots import * from openmc.region import * from openmc.volume import * from openmc.source import * from openmc.settings import * from openmc.surface import * from openmc.universe import * from openmc.lattice import * from openmc.filter import * from openmc.filter_expansion import * from openmc.trigger import * from openmc.tally_derivative import * from openmc.tallies import * from openmc.mgxs_library import * from openmc.executor import * from openmc.statepoint import * from openmc.summary import * from openmc.particle_restart import * from openmc.mixin import * from openmc.plotter import * from openmc.search import * from openmc.polynomial import * from . import examples # Import a few convencience functions that used to be here from openmc.model import rectangular_prism, hexagonal_prism __version__ = '0.13.0-dev'
from openmc.arithmetic import * from openmc.cell import * from openmc.checkvalue import * from openmc.mesh import * from openmc.element import * from openmc.geometry import * from openmc.nuclide import * from openmc.macroscopic import * from openmc.material import * from openmc.plots import * from openmc.region import * from openmc.volume import * from openmc.source import * from openmc.settings import * from openmc.surface import * from openmc.universe import * from openmc.lattice import * from openmc.filter import * from openmc.filter_expansion import * from openmc.trigger import * from openmc.tally_derivative import * from openmc.tallies import * from openmc.mgxs_library import * from openmc.executor import * from openmc.statepoint import * from openmc.summary import * from openmc.particle_restart import * from openmc.mixin import * from openmc.plotter import * from openmc.search import * from openmc.polynomial import * from . import examples # Import a few names from the model module from openmc.model import rectangular_prism, hexagonal_prism, Model __version__ = '0.13.0-dev'
Make Model available in main openmc namespace
Make Model available in main openmc namespace
Python
mit
amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,walshjon/openmc,amandalund/openmc
--- +++ @@ -31,7 +31,7 @@ from openmc.polynomial import * from . import examples -# Import a few convencience functions that used to be here -from openmc.model import rectangular_prism, hexagonal_prism +# Import a few names from the model module +from openmc.model import rectangular_prism, hexagonal_prism, Model __version__ = '0.13.0-dev'
3d58796f9bedb607cd2c23aa7dcb6ce86b8af075
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = 'markdown' cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
Add more markdown syntax detection's
Add more markdown syntax detection's Detect 'markdown gfm', 'multimarkdown' and 'markdown extended'. Closes #2
Python
mit
jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint
--- +++ @@ -16,7 +16,7 @@ class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" - syntax = 'markdown' + syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version'
8b4b5705907e1ec5f9dd3148560dc1bf4cd5b9b7
bin/detail/get_nmake_environment.py
bin/detail/get_nmake_environment.py
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual Studio {} is not installed'.format( vs_path_env, vs_version ) ) vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') if not os.path.isdir(vcvarsall_dir): sys.exit( 'Directory `{}` not exists ' '({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat') if not os.path.isfile(vcvarsall_path): sys.exit( 'File vcvarsall.bat not found in directory ' '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])
# Copyright (c) 2014, Ruslan Baratov # All rights reserved. import detail.util import os import sys def get(arch, vs_version): vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version) vs_path = os.getenv(vs_path_env) if not vs_path: sys.exit( 'Environment variable {} is empty, ' 'looks like Visual Studio {} is not installed'.format( vs_path_env, vs_version ) ) if vs_version == '15': vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC', 'Auxiliary', 'Build') else: vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') if not os.path.isdir(vcvarsall_dir): sys.exit( 'Directory `{}` not exists ' '({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat') if not os.path.isfile(vcvarsall_path): sys.exit( 'File vcvarsall.bat not found in directory ' '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env) ) return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])
Fix vcvarsall_dir for Visual Studio 2017
polly.py: Fix vcvarsall_dir for Visual Studio 2017 [skip ci]
Python
bsd-2-clause
idscan/polly,idscan/polly,ruslo/polly,ruslo/polly
--- +++ @@ -15,7 +15,12 @@ vs_path_env, vs_version ) ) - vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') + + if vs_version == '15': + vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC', 'Auxiliary', 'Build') + else: + vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC') + if not os.path.isdir(vcvarsall_dir): sys.exit( 'Directory `{}` not exists '
07e300e393701d8bddf6646a76542555b92c9f4d
pmxbot/__init__.py
pmxbot/__init__.py
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'irc.freenode.net', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) "The config object" if __name__ == '__main__': importlib.import_module('pmxbot.core').run()
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) "The config object" if __name__ == '__main__': importlib.import_module('pmxbot.core').run()
Use IRC server on localhost by default
Use IRC server on localhost by default
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
--- +++ @@ -8,7 +8,7 @@ config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', - server_host = 'irc.freenode.net', + server_host = 'localhost', server_port = 6667, use_ssl = False, password = None,
024a1d90ae890450167f697d97aa166dca3c0c5f
tbmodels/__init__.py
tbmodels/__init__.py
r""" TBmodels is a tool for creating / loading and manipulating tight-binding models. """ __version__ = '1.3.0b1' # import order is important due to circular imports from . import helpers from ._tb_model import Model from . import _kdotp from . import io
r""" TBmodels is a tool for creating / loading and manipulating tight-binding models. """ __version__ = '1.3.0' # import order is important due to circular imports from . import helpers from ._tb_model import Model from . import _kdotp from . import io
Remove beta tag from version.
Remove beta tag from version.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
--- +++ @@ -2,7 +2,7 @@ TBmodels is a tool for creating / loading and manipulating tight-binding models. """ -__version__ = '1.3.0b1' +__version__ = '1.3.0' # import order is important due to circular imports from . import helpers
76cef8ae9961a64b2868fae32511f525860f8172
semillas_backend/users/serializers.py
semillas_backend/users/serializers.py
from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ class Meta: model = User fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ class Meta: model = User fields = ('id', 'name', 'picture', 'location', 'username', 'last_login')
Remove email from serializer for security
Remove email from serializer for security
Python
mit
Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform
--- +++ @@ -12,4 +12,4 @@ """ class Meta: model = User - fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login') + fields = ('id', 'name', 'picture', 'location', 'username', 'last_login')
b3807e5ddb50ca34af3f4f187bc01fcc284afb20
bin/jenkins.py
bin/jenkins.py
#!/usr/bin/env python3 # Copyright (c) 2014, Ruslan Baratov # All rights reserved. import os import subprocess import sys def run(): toolchain = os.getenv('TOOLCHAIN') if not toolchain: sys.exit('Environment variable TOOLCHAIN is empty') build_type = os.getenv('BUILD_TYPE') if not build_type: sys.exit('Environment variable BUILD_TYPE is empty') build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py') print('Run script: {}'.format(build)) print('Toolchain: {}'.format(toolchain)) print('Config: {}'.format(build_type)) args = [ sys.executable, build, '--toolchain', toolchain, '--config', build_type, '--verbose', '--test' ] try: subprocess.check_call(args) except subprocess.CalledProcessError as error: print(error) print(error.output) sys.exit(1)
#!/usr/bin/env python3 # Copyright (c) 2014, Ruslan Baratov # All rights reserved. import os import subprocess import sys def run(): toolchain = os.getenv('TLC') if not toolchain: sys.exit('Environment variable TLC is empty (TooLChain)') config = os.getenv('CFG') if not config: sys.exit('Environment variable CFG is empty (ConFiG)') build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py') print('Run script: {}'.format(build)) print('Toolchain: {}'.format(toolchain)) print('Config: {}'.format(config)) args = [ sys.executable, build, '--toolchain', toolchain, '--config', config, '--verbose', '--test' ] try: subprocess.check_call(args) except subprocess.CalledProcessError as error: print(error) print(error.output) sys.exit(1)
Use short axis names to prevent windows path overflow
Use short axis names to prevent windows path overflow
Python
bsd-2-clause
headupinclouds/polly,ruslo/polly,headupinclouds/polly,idscan/polly,idscan/polly,headupinclouds/polly,ruslo/polly
--- +++ @@ -8,19 +8,19 @@ import sys def run(): - toolchain = os.getenv('TOOLCHAIN') + toolchain = os.getenv('TLC') if not toolchain: - sys.exit('Environment variable TOOLCHAIN is empty') + sys.exit('Environment variable TLC is empty (TooLChain)') - build_type = os.getenv('BUILD_TYPE') - if not build_type: - sys.exit('Environment variable BUILD_TYPE is empty') + config = os.getenv('CFG') + if not config: + sys.exit('Environment variable CFG is empty (ConFiG)') build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py') print('Run script: {}'.format(build)) print('Toolchain: {}'.format(toolchain)) - print('Config: {}'.format(build_type)) + print('Config: {}'.format(config)) args = [ sys.executable, @@ -28,7 +28,7 @@ '--toolchain', toolchain, '--config', - build_type, + config, '--verbose', '--test' ]
92340a1238636d9160ce120cd9a12ed260007aca
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' from . import views, models
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' login_manager.login_message_category = "info" from . import views, models
Add default login manager message category
Add default login manager message category
Python
mit
timzdevz/fm-flask-app
--- +++ @@ -11,5 +11,6 @@ db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' +login_manager.login_message_category = "info" from . import views, models
928c70518af5580d803c69207028f566d572f3f4
app/settings.py
app/settings.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Flask application default config: # http://flask.pocoo.org/docs/config/#configuring-from-files # https://github.com/mbr/flask-appconfig project_name = u'Ninhursag' class Default(object): APP_NAME = project_name DEBUG = False TESTING = False # Servers and URLs SERVER_NAME = 'localhost:5000' # Authentication etc # To generate: import os; os.urandom(24) SECRET_KEY = 'some-secret-key' CSRF_ENABLED = True # API API_SERVER = SERVER_NAME API_TOKEN = 'some-api-token' # Flat pages FLATPAGES_ROOT = 'pages/flat' FLATPAGES_EXTENSION = '.md' FLATPAGES_MARKDOWN_EXTENSIONS = [] class Dev(Default): APP_NAME = project_name + ' (dev)' DEBUG = True SERVER_NAME = '0.0.0.0:5000' API_SERVER = SERVER_NAME class Testing(Default): TESTING = True CSRF_ENABLED = False class Production(Default): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Flask application default config: # http://flask.pocoo.org/docs/config/#configuring-from-files # https://github.com/mbr/flask-appconfig project_name = u'Ninhursag' class Default(object): APP_NAME = project_name DEBUG = False TESTING = False # Servers and URLs SERVER_NAME = 'localhost:5000' # Authentication etc # To generate: import os; os.urandom(24) SECRET_KEY = 'some-secret-key' CSRF_ENABLED = True # API API_SERVER = SERVER_NAME API_TOKEN = 'some-api-token' # Flat pages FLATPAGES_ROOT = 'pages/flat' FLATPAGES_EXTENSION = '.md' FLATPAGES_MARKDOWN_EXTENSIONS = [] class Dev(Default): APP_NAME = project_name + ' (dev)' DEBUG = True SERVER_NAME = '0.0.0.0:5000' API_SERVER = SERVER_NAME class Testing(Default): TESTING = True CSRF_ENABLED = False class Production(Default): pass
Add back a newline to have two rows between class definitions.
Add back a newline to have two rows between class definitions.
Python
mit
peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag
--- +++ @@ -41,6 +41,7 @@ SERVER_NAME = '0.0.0.0:5000' API_SERVER = SERVER_NAME + class Testing(Default): TESTING = True CSRF_ENABLED = False
dbfc1a11c0ced8ab7a997944e943a17ff0069199
lexer.py
lexer.py
import ply.lex as lex import re tokens = ( 'SECTION', 'IDENTIFIER', 'LBRACE', 'RBRACE', 'SEMI', 'TRUE', 'FALSE' ) def t_SECTION(t): r'section' return t def t_TRUE(t): r'(true|1)' return t def t_FALSE(t): r'(false|0)' return t def t_IDENTIFIER(t): r'[a-zA-Z\-0-9]+' return t def t_LBRACE(t): r'{' return t def t_RBRACE(t): r'}' return t def t_SEMI(t): r';' return t def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) return t t_ignore = ' \t\n' # Error handling rule def t_error(t): print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno)) t.lexer.skip(1) lexer = lex.lex()
import ply.lex as lex import re tokens = ( 'SECTION', 'IDENTIFIER', 'STRING', 'LBRACE', 'RBRACE', 'SEMI', 'EQU', 'TRUE', 'FALSE' ) def t_SECTION(t): r'section' return t def t_TRUE(t): r'(true|1)' return t def t_FALSE(t): r'(false|0)' return t def t_IDENTIFIER(t): r'[a-zA-Z\-0-9]+' return t def t_STRING(t): r'(\".*\"|\'.*\')' t.value = t.value[1:-1] return t def t_LBRACE(t): r'{' return t def t_EQU(t): r'=' return t def t_RBRACE(t): r'}' return t def t_SEMI(t): r';' return t def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) return t t_ignore = ' \t\n' # Error handling rule def t_error(t): print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno)) t.lexer.skip(1) lexer = lex.lex()
Add rudimentary string support and a token for '=' sign.
Add rudimentary string support and a token for '=' sign.
Python
cc0-1.0
dmbaturin/ply-example
--- +++ @@ -3,9 +3,11 @@ tokens = ( 'SECTION', 'IDENTIFIER', + 'STRING', 'LBRACE', 'RBRACE', 'SEMI', + 'EQU', 'TRUE', 'FALSE' ) @@ -26,8 +28,17 @@ r'[a-zA-Z\-0-9]+' return t +def t_STRING(t): + r'(\".*\"|\'.*\')' + t.value = t.value[1:-1] + return t + def t_LBRACE(t): r'{' + return t + +def t_EQU(t): + r'=' return t def t_RBRACE(t):
8e28c627c0a84939bb44c2c77fa3e4b3de4932bf
erroneous/models.py
erroneous/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class Error(models.Model): """ Model for storing the individual errors. """ kind = models.CharField(_('type'), null=True, blank=True, max_length=128, db_index=True ) info = models.TextField( null=False, ) data = models.TextField( blank=True, null=True ) path = models.URLField( null=True, blank=True, verify_exists=False, ) when = models.DateTimeField( null=False, auto_now_add=True, db_index=True, ) html = models.TextField( null=True, blank=True, ) modified = models.DateTimeField(auto_now=True) class Meta: """ Meta information for the model. """ verbose_name = _('Error') verbose_name_plural = _('Errors') def __unicode__(self): """ String representation of the object. """ return "%s: %s" % (self.kind, self.info)
from django.db import models from django.utils.translation import ugettext_lazy as _ class Error(models.Model): """ Model for storing the individual errors. """ kind = models.CharField(_('type'), null=True, blank=True, max_length=128, db_index=True ) info = models.TextField( null=False, ) data = models.TextField( blank=True, null=True ) path = models.URLField( null=True, blank=True, ) when = models.DateTimeField( null=False, auto_now_add=True, db_index=True, ) html = models.TextField( null=True, blank=True, ) modified = models.DateTimeField(auto_now=True) class Meta: """ Meta information for the model. """ verbose_name = _('Error') verbose_name_plural = _('Errors') def __unicode__(self): """ String representation of the object. """ return "%s: %s" % (self.kind, self.info)
Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5
Remove verify_exists kwarg, which was deprecated in django 1.3 and causes an error in django 1.5
Python
mit
mbelousov/django-erroneous,mbelousov/django-erroneous,mridang/django-erroneous
--- +++ @@ -15,7 +15,7 @@ blank=True, null=True ) path = models.URLField( - null=True, blank=True, verify_exists=False, + null=True, blank=True, ) when = models.DateTimeField( null=False, auto_now_add=True, db_index=True,
66d69bb487a7d5f60138a7c6d5191608a2611e6a
rest/views.py
rest/views.py
import hashlib from rest.models import Sound from rest.serializers import SoundSerializer from rest_framework import generics def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): queryset = Sound.objects.all() serializer_class = SoundSerializer def perform_create(self, serializer): sound = self.request._files['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO tempfile = self.request._files['sound'].file.name sha1 = hashfile(open(tempfile, 'rb'), hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Sound.objects.all() serializer_class = SoundSerializer
import hashlib from rest.models import Sound from rest.serializers import SoundSerializer from rest_framework import generics def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): queryset = Sound.objects.all() serializer_class = SoundSerializer def perform_create(self, serializer): sound = self.request._files['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO tempfile = self.request._files['sound'].file.name sha1 = hashfile(open(tempfile, 'rb'), hashlib.sha1()).hex() self.request._files['sound']._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Sound.objects.all() serializer_class = SoundSerializer
Rename uploaded files to their SHA1
Rename uploaded files to their SHA1
Python
bsd-3-clause
Soundphy/soundphy
--- +++ @@ -24,6 +24,7 @@ duration = 0.0 # TODO tempfile = self.request._files['sound'].file.name sha1 = hashfile(open(tempfile, 'rb'), hashlib.sha1()).hex() + self.request._files['sound']._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1)
99a3d522a451ee91e3731a3b2159df69f22364c9
DebianChangesBot/utils/parse_mail.py
DebianChangesBot/utils/parse_mail.py
# -*- coding: utf-8 -*- import email from DebianChangesBot.utils import quoted_printable def parse_mail(fileobj): headers, body = {}, [] msg = email.message_from_file(fileobj) for k, v in msg.items(): headers[k] = quoted_printable(v).replace('\n', '').strip() for line in email.iterators.body_line_iterator(msg): line = unicode(line, 'utf-8', 'replace').replace('\n', '') body.append(line) # Merge lines joined with "=\n" i = len(body) - 1 while i > 0: i -= 1 prev = body[i] if len(prev) == 74 and prev.endswith('='): body[i] = body[i][:-1] + body[i + 1] del body[i + 1] # Remove =20 from end of lines i = 0 while i < len(body): if body[i].endswith('=20'): body[i] = body[i][:-3] + ' ' i += 1 return headers, body
# -*- coding: utf-8 -*- import email from DebianChangesBot.utils import quoted_printable def parse_mail(fileobj): headers, body = {}, [] msg = email.message_from_file(fileobj) for k, v in msg.items(): headers[k] = quoted_printable(v).replace('\n', '').strip() for line in email.Iterators.body_line_iterator(msg): line = unicode(line, 'utf-8', 'replace').replace('\n', '') body.append(line) # Merge lines joined with "=\n" i = len(body) - 1 while i > 0: i -= 1 prev = body[i] if len(prev) == 74 and prev.endswith('='): body[i] = body[i][:-1] + body[i + 1] del body[i + 1] # Remove =20 from end of lines i = 0 while i < len(body): if body[i].endswith('=20'): body[i] = body[i][:-3] + ' ' i += 1 return headers, body
Use 2.4 email iterator syntax so the fixture tests pass
Use 2.4 email iterator syntax so the fixture tests pass python2.4 called its email iterators: email.Iterators. python2.5 uses email.iterators, but to allow cross-version code, Iterators works. Signed-off-by: Jonny Lamb <54cd04502facfcf96b325c60af9b1611ee761860@jonnylamb.com>
Python
agpl-3.0
lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot
--- +++ @@ -11,7 +11,7 @@ for k, v in msg.items(): headers[k] = quoted_printable(v).replace('\n', '').strip() - for line in email.iterators.body_line_iterator(msg): + for line in email.Iterators.body_line_iterator(msg): line = unicode(line, 'utf-8', 'replace').replace('\n', '') body.append(line)
79d02616ab6d70b029876b8a2de425026e6268c4
pycalc.py
pycalc.py
import sys import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
# vim: set fileencoding=utf-8 import sys if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
Make main program throw warning on python2.
Make main program throw warning on python2.
Python
mit
5225225/pycalc,5225225/pycalc
--- +++ @@ -1,4 +1,10 @@ +# vim: set fileencoding=utf-8 + import sys + +if sys.version_info.major < 3: + print("This program is for python version 3 only.") + sys.exit(3) import lexer import execute
b636affedea494f1733bf413986a8546d3495c53
chipy_org/apps/meetings/urls.py
chipy_org/apps/meetings/urls.py
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from meetings.views import (PastMeetings, ProposeTopic, MyTopics, RSVP, PastTopics, ) urlpatterns = patterns("", url(r'^past/$', PastMeetings.as_view(), name='past_meetings'), url(r'^rsvp/$', RSVP.as_view(), name='rsvp'), url(r'^rsvp/anonymous/$', RSVP.as_view(), name='anonymous_rsvp'), url(r'^topics/propose$', login_required(ProposeTopic.as_view()), name='propose_topic'), url(r'^topics/mine$', login_required(MyTopics.as_view()), name='my_topics'), url(r'^topics/past$', PastTopics.as_view(), name='past_topics'), )
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from meetings.views import (PastMeetings, ProposeTopic, MyTopics, RSVP, PastTopics, ) urlpatterns = patterns("", url(r'^past/$', PastMeetings.as_view(), name='past_meetings'), url(r'^rsvp/$', RSVP.as_view(), name='rsvp'), url(r'^rsvp/anonymous/$', RSVP.as_view(), name='anonymous_rsvp'), url(r'^rsvp/anonymous/(?P<rsvp_key>[a-z0-1]{40})/$', RSVP.as_view(), name='anonymous_rsvp_with_key'), url(r'^topics/propose$', login_required(ProposeTopic.as_view()), name='propose_topic'), url(r'^topics/mine$', login_required(MyTopics.as_view()), name='my_topics'), url(r'^topics/past$', PastTopics.as_view(), name='past_topics'), )
Add url for anonymous rsvp with key
Add url for anonymous rsvp with key
Python
mit
agfor/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,agfor/chipy.org
--- +++ @@ -11,6 +11,7 @@ url(r'^past/$', PastMeetings.as_view(), name='past_meetings'), url(r'^rsvp/$', RSVP.as_view(), name='rsvp'), url(r'^rsvp/anonymous/$', RSVP.as_view(), name='anonymous_rsvp'), + url(r'^rsvp/anonymous/(?P<rsvp_key>[a-z0-1]{40})/$', RSVP.as_view(), name='anonymous_rsvp_with_key'), url(r'^topics/propose$', login_required(ProposeTopic.as_view()), name='propose_topic'), url(r'^topics/mine$', login_required(MyTopics.as_view()), name='my_topics'), url(r'^topics/past$', PastTopics.as_view(), name='past_topics'),
5fa43e2943c44223fc5d7d5414caca98e0be0a11
cla_backend/settings/jenkins.py
cla_backend/settings/jenkins.py
import os from .testing import * DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('CLA', 'cla-alerts@digital.justice.gov.uk'), ) MANAGERS = ADMINS INSTALLED_APPS += ('django_jenkins',) JENKINS_TASKS = ( 'django_jenkins.tasks.with_coverage', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cla_backend', 'TEST_NAME': 'test_cla_backend%s' % (os.environ.get('BACKEND_BASE_PORT', '')), # WARNING: if you want to change this, you NEED to change the dropdb arg in frontend build.py as well 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner' #HOST_NAME = "" ALLOWED_HOSTS = [ '*' ]
import os from .testing import * DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('CLA', 'cla-alerts@digital.justice.gov.uk'), ) MANAGERS = ADMINS INSTALLED_APPS += ('django_jenkins',) JENKINS_TASKS = ( 'django_jenkins.tasks.with_coverage', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_USERNAME', ''), 'TEST_NAME': 'test_cla_backend%s' % (os.environ.get('BACKEND_BASE_PORT', '')), # WARNING: if you want to change this, you NEED to change the dropdb arg in frontend build.py as well 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': os.environ.get('DB_PORT', ''), } } JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner' #HOST_NAME = "" ALLOWED_HOSTS = [ '*' ]
Change Jenkins settings.py to use env vars
Change Jenkins settings.py to use env vars
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
--- +++ @@ -19,12 +19,12 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', - 'NAME': 'cla_backend', + 'NAME': os.environ.get('DB_USERNAME', ''), 'TEST_NAME': 'test_cla_backend%s' % (os.environ.get('BACKEND_BASE_PORT', '')), # WARNING: if you want to change this, you NEED to change the dropdb arg in frontend build.py as well - 'USER': '', - 'PASSWORD': '', - 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. - 'PORT': '', # Set to empty string for default. + 'USER': os.environ.get('DB_USERNAME', ''), + 'PASSWORD': os.environ.get('DB_PASSWORD', ''), + 'HOST': os.environ.get('DB_HOST', ''), + 'PORT': os.environ.get('DB_PORT', ''), } }
ee61dab40c4c3eaa1553397091a17a3292dcf9d6
grako/ast.py
grako/ast.py
from collections import OrderedDict, Mapping import json class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable)
from collections import OrderedDict, Mapping import json __all__ = ['AST'] class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] else: previous.append(value) def update(self, *args, **kwargs): for dct in args: for k, v in dct: self.add(k, v) for k, v in kwargs.items(): self.add(k, v) @property def first(self): key = self.elements.keys[0] return self.elements[key] def __iter__(self): return iter(self._elements) def __contains__(self, key): return key in self._elements def __len__(self): return len(self._elements) def __getitem__(self, key): if key not in self._elements: self._elements[key] = list() return self._elements[key] def __setitem__(self, key, value): self._elements[key] = value def __getattr__(self, key): return self.__getitem__(key) if key in self._elements: return self.__getitem__(key) raise KeyError(key) @staticmethod def serializable(obj): if isinstance(obj, AST): return obj._elements return obj def __repr__(self): return self.serializable(self._elements) def __str__(self): return json.dumps(self._elements, indent=4, default=self.serializable)
Allow to set items in AST.
Allow to set items in AST.
Python
bsd-2-clause
frnknglrt/grako,vmuriart/grako
--- +++ @@ -1,5 +1,7 @@ from collections import OrderedDict, Mapping import json + +__all__ = ['AST'] class AST(Mapping): def __init__(self, **kwargs): @@ -38,6 +40,9 @@ self._elements[key] = list() return self._elements[key] + def __setitem__(self, key, value): + self._elements[key] = value + def __getattr__(self, key): return self.__getitem__(key) if key in self._elements:
5442facddbcf9b8adff247edcf3bd27a8fda2c10
great/tap.py
great/tap.py
from __future__ import absolute_import from minion.twisted import MinionResource from twisted.application import strports from twisted.python import usage from twisted.python.filepath import FilePath from twisted.web import server from twisted.web.static import File import twisted.web.resource from great.web import create_app import great class Options(usage.Options): optParameters = [ [ "access-log", "l", None, "Path to web CLF (Combined Log Format) log file for access logs.", ], ["port", "p", "tcp:8080", "The endpoint to listen on."], ] def makeService(options): greatPath = FilePath(great.__file__).parent() staticPath = greatPath.child("static") templatesPath = greatPath.child("templates") rootResource = twisted.web.resource.Resource() rootResource.putChild("", File(staticPath.child("index.html").path)) rootResource.putChild("static", File(staticPath.path)) rootResource.putChild("templates", File(templatesPath.path)) rootResource.putChild("great", MinionResource(create_app())) site = server.Site(rootResource) return strports.service(description=options["port"], factory=site)
from __future__ import absolute_import from minion.twisted import MinionResource from twisted.application import strports from twisted.python import usage from twisted.python.filepath import FilePath from twisted.web import server from twisted.web.static import File import alembic import alembic.config import twisted.web.resource from great.web import create_app import great class Options(usage.Options): optFlags = [ [ "migrate", "", "Run `alembic upgrade head` first to migrate the DB if necessary.", ], ] optParameters = [ [ "access-log", "l", None, "Path to web CLF (Combined Log Format) log file for access logs.", ], ["port", "p", "tcp:8080", "The endpoint to listen on."], ] def makeService(options): if options["migrate"]: alembic_config = alembic.config.Config(FilePath("alembic.ini").path) alembic.command.upgrade(alembic_config, "head") greatPath = FilePath(great.__file__).parent() staticPath = greatPath.child("static") templatesPath = greatPath.child("templates") rootResource = twisted.web.resource.Resource() rootResource.putChild("", File(staticPath.child("index.html").path)) rootResource.putChild("static", File(staticPath.path)) rootResource.putChild("templates", File(templatesPath.path)) rootResource.putChild("great", MinionResource(create_app())) site = server.Site(rootResource) return strports.service(description=options["port"], factory=site)
Add a flag during startup.
Add a flag during startup.
Python
mit
Julian/Great,Julian/Great,Julian/Great
--- +++ @@ -6,6 +6,8 @@ from twisted.python.filepath import FilePath from twisted.web import server from twisted.web.static import File +import alembic +import alembic.config import twisted.web.resource from great.web import create_app @@ -13,6 +15,13 @@ class Options(usage.Options): + optFlags = [ + [ + "migrate", + "", + "Run `alembic upgrade head` first to migrate the DB if necessary.", + ], + ] optParameters = [ [ "access-log", @@ -25,6 +34,10 @@ def makeService(options): + if options["migrate"]: + alembic_config = alembic.config.Config(FilePath("alembic.ini").path) + alembic.command.upgrade(alembic_config, "head") + greatPath = FilePath(great.__file__).parent() staticPath = greatPath.child("static") templatesPath = greatPath.child("templates")
b4613b6b20c6fae1b73095363078201e666bd5bc
djangosaml2/urls.py
djangosaml2/urls.py
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Fix imports for Django 1.6 and above
Fix imports for Django 1.6 and above
Python
apache-2.0
damienmarie-alation/djangosaml2,writepython/djangosaml2,BetterWorks/djangosaml2,knaperek/djangosaml2,writepython/djangosaml2,WebSpider/djangosaml2,knaperek/djangosaml2,MiguelSR/djangosaml2,WebSpider/djangosaml2,BetterWorks/djangosaml2,MiguelSR/djangosaml2,damienmarie-alation/djangosaml2
--- +++ @@ -13,7 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from django.conf.urls.defaults import patterns, handler500, url +try: + from django.conf.urls import patterns, handler500, url +# Fallback for Django versions < 1.4 +except ImportError: + from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views',
99ea4348efe1212ddb814680272643829ffabf8f
djangosaml2/urls.py
djangosaml2/urls.py
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@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. try: from django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Fix imports for Django 1.6 and above
Fix imports for Django 1.6 and above
Python
apache-2.0
City-of-Helsinki/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,advisory/djangosaml2_tenant,GradConnection/djangosaml2,WiserTogether/djangosaml2,City-of-Helsinki/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,kviktor/djangosaml2-py3
--- +++ @@ -13,7 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from django.conf.urls.defaults import patterns, handler500, url +try: + from django.conf.urls import patterns, handler500, url +# Fallback for Django versions < 1.4 +except ImportError: + from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views',
eedd6f7dce57b30841bcaa10f25cc4ac3b314d57
setup.py
setup.py
import os import itertools import platform from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), "mongomock", "__version__.py")) as version_file: exec(version_file.read()) install_requires = ["sentinels", "six"] if platform.python_version() < '2.7': install_requires.append('unittest2') install_requires.append('ordereddict') if os.environ.get("INSTALL_PYMONGO", "false") == "true": install_requires.append("pymongo") if os.environ.get("INSTALL_PYEXECJS", "false") == "true": install_requires.append("pyexecjs") setup(name="mongomock", classifiers = [ "Programming Language :: Python :: 2.7", ], description="Fake pymongo stub for testing simple MongoDB-dependent code", license="BSD", author="Rotem Yaari", author_email="vmalloc@gmail.com", version=__version__, packages=find_packages(exclude=["tests"]), install_requires=install_requires, scripts=[], namespace_packages=[] )
import os import platform from setuptools import setup, find_packages version_file_path = os.path.join( os.path.dirname(__file__), "mongomock", "__version__.py") with open(version_file_path) as version_file: exec(version_file.read()) install_requires = ["sentinels", "six"] if platform.python_version() < '2.7': install_requires.append('unittest2') install_requires.append('ordereddict') if os.environ.get("INSTALL_PYMONGO", "false") == "true": install_requires.append("pymongo") if os.environ.get("INSTALL_PYEXECJS", "false") == "true": install_requires.append("pyexecjs") setup(name="mongomock", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Database"], description="Fake pymongo stub for testing simple MongoDB-dependent code", license="BSD", author="Rotem Yaari", author_email="vmalloc@gmail.com", version=__version__, packages=find_packages(exclude=["tests"]), install_requires=install_requires, scripts=[], namespace_packages=[] )
Add version and platform specifiers.
Add version and platform specifiers.
Python
bsd-3-clause
julianhille/mongomock,mdomke/mongomock,StarfishStorage/mongomock,marcinbarczynski/mongomock,vmalloc/mongomock,drorasaf/mongomock,magaman384/mongomock
--- +++ @@ -1,10 +1,15 @@ import os -import itertools import platform from setuptools import setup, find_packages -with open(os.path.join(os.path.dirname(__file__), "mongomock", "__version__.py")) as version_file: + +version_file_path = os.path.join( + os.path.dirname(__file__), "mongomock", "__version__.py") + + +with open(version_file_path) as version_file: exec(version_file.read()) + install_requires = ["sentinels", "six"] if platform.python_version() < '2.7': @@ -13,14 +18,27 @@ if os.environ.get("INSTALL_PYMONGO", "false") == "true": install_requires.append("pymongo") + if os.environ.get("INSTALL_PYEXECJS", "false") == "true": install_requires.append("pyexecjs") setup(name="mongomock", - classifiers = [ + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Operating System :: MacOS :: MacOS X", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", - ], + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database"], description="Fake pymongo stub for testing simple MongoDB-dependent code", license="BSD", author="Rotem Yaari",
22ba81ee7bed81c3a1da4b8d2ace4c38a957b5dd
server.py
server.py
import bottle import waitress import controller import breathe if __name__ == '__main__': bottle_app = bottle.app() breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, breather) waitress.serve(bottle_app, host='0.0.0.0', port=7000)
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = controller.Controller(bottle_app, None) @scheduler.scheduled_job(trigger='cron', hour=21, minute=0) def on_job(): """Start at 9:00pm PT""" print('STARTING BREATHER') breather.restart() @scheduler.scheduled_job(trigger='cron', hour=23, minute=0) def off_job(): """End at 11:00pm PT""" print("STOPPING BREATHER") breather.shutdown() if __name__ == '__main__': scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm
Add scheduler. Schedule lights on for 9:00pm and lights off for 11:00pm
Python
mit
tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,YonasBerhe/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse
--- +++ @@ -2,10 +2,28 @@ import waitress import controller import breathe +from pytz import timezone +from apscheduler.schedulers.background import BackgroundScheduler + +bottle_app = bottle.app() +scheduler = BackgroundScheduler() +scheduler.configure(timezone=timezone('US/Pacific')) +breather = breathe.Breathe() +my_controller = controller.Controller(bottle_app, None) +@scheduler.scheduled_job(trigger='cron', hour=21, minute=0) +def on_job(): + """Start at 9:00pm PT""" + print('STARTING BREATHER') + breather.restart() + +@scheduler.scheduled_job(trigger='cron', hour=23, minute=0) +def off_job(): + """End at 11:00pm PT""" + print("STOPPING BREATHER") + breather.shutdown() + if __name__ == '__main__': - bottle_app = bottle.app() - breather = breathe.Breathe() - my_controller = controller.Controller(bottle_app, breather) + scheduler.start() waitress.serve(bottle_app, host='0.0.0.0', port=7000)
b8f893089a35627305b2a6dd1f6ba27268f8e865
openphoto/multipart_post.py
openphoto/multipart_post.py
import mimetypes import mimetools def encode_multipart_formdata(params, files): boundary = mimetools.choose_boundary() lines = [] for name in params: lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"" % name) lines.append("") lines.append(str(params[name])) for name in files: filename = files[name] content_type, _ = mimetypes.guess_type(filename) if content_type is None: content_type = "application/octet-stream" lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (name, filename)) lines.append("Content-Type: %s" % content_type) lines.append("") lines.append(open(filename, "rb").read()) lines.append("--" + boundary + "--") lines.append("") body = "\r\n".join(lines) headers = {'Content-Type': "multipart/form-data; boundary=%s" % boundary, 'Content-Length': str(len(body))} return headers, body
import os import mimetypes import mimetools def encode_multipart_formdata(params, files): boundary = mimetools.choose_boundary() lines = [] for name in params: lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"" % name) lines.append("") lines.append(str(params[name])) for name in files: filename = files[name] content_type, _ = mimetypes.guess_type(filename) if content_type is None: content_type = "application/octet-stream" lines.append("--" + boundary) lines.append("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (name, filename)) lines.append("Content-Type: %s" % content_type) lines.append("") lines.append(open(os.path.expanduser(filename), "rb").read()) lines.append("--" + boundary + "--") lines.append("") body = "\r\n".join(lines) headers = {'Content-Type': "multipart/form-data; boundary=%s" % boundary, 'Content-Length': str(len(body))} return headers, body
Expand "~" to home path
Expand "~" to home path
Python
apache-2.0
photo/openphoto-python,photo/openphoto-python
--- +++ @@ -1,3 +1,4 @@ +import os import mimetypes import mimetools @@ -20,7 +21,7 @@ lines.append("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"" % (name, filename)) lines.append("Content-Type: %s" % content_type) lines.append("") - lines.append(open(filename, "rb").read()) + lines.append(open(os.path.expanduser(filename), "rb").read()) lines.append("--" + boundary + "--") lines.append("")
605011cbb7953e8629f844d16d62f4632727b023
core/cachecontroller/schedinstances/ArtPackages.py
core/cachecontroller/schedinstances/ArtPackages.py
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'))) return urlsQueue
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 N_DAYS_WINDOW = 14 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=self.N_DAYS_WINDOW)).strftime('%Y-%m-%d'))) return urlsQueue
Increase the timewindow check of ART tests in cachecontroller
Increase the timewindow check of ART tests in cachecontroller
Python
apache-2.0
PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core,PanDAWMS/panda-bigmon-core
--- +++ @@ -6,6 +6,7 @@ class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 + N_DAYS_WINDOW = 14 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') @@ -14,5 +15,6 @@ urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + - (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'))) + (datetime.now() - timedelta(days=self.N_DAYS_WINDOW)).strftime('%Y-%m-%d'))) return urlsQueue +
a5626b61892549aa376969e44a26c01a69ddd8f8
lib/oeqa/runtime/cases/parselogs_rpi.py
lib/oeqa/runtime/cases/parselogs_rpi.py
from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
Add 5.4 specific error messages to ignore list
oeqa: Add 5.4 specific error messages to ignore list with 5.4 fd580000.genet has been replaced with fd580000.ethernet in the error text Fixes https://github.com/raspberrypi/linux/issues/3884 Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
Python
mit
agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,schnitzeltony/meta-raspberrypi,agherzan/meta-raspberrypi
--- +++ @@ -4,6 +4,9 @@ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', + 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', + 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', + 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors
2f95af84d585c19a8eb6a8e6d437acdbe3c3d2ae
release.py
release.py
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import pkg_resources pkg_resources.require('jaraco.packaging>=2.0') pkg_resources.require('wheel') files_with_versions = 'setuptools/version.py', # bdist_wheel must be included or pip will break dist_commands = 'sdist', 'bdist_wheel' test_info = "Travis-CI tests: http://travis-ci.org/#!/pypa/setuptools" os.environ["SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES"] = "1"
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import pkg_resources pkg_resources.require('jaraco.packaging>=2.11') pkg_resources.require('wheel') files_with_versions = 'setuptools/version.py', # bdist_wheel must be included or pip will break dist_commands = 'sdist', 'bdist_wheel' test_info = "Travis-CI tests: http://travis-ci.org/#!/pypa/setuptools" os.environ["SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES"] = "1"
Use jaraco.packaging 2.11 for better support for bookmarks and thus Git push targets.
Use jaraco.packaging 2.11 for better support for bookmarks and thus Git push targets.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
--- +++ @@ -7,7 +7,7 @@ import pkg_resources -pkg_resources.require('jaraco.packaging>=2.0') +pkg_resources.require('jaraco.packaging>=2.11') pkg_resources.require('wheel') files_with_versions = 'setuptools/version.py',
b4e065bb15cdc7eda91c89fc0bc3472064d5aac0
djangocms_spa/decorators.py
djangocms_spa/decorators.py
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.path cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError from django.utils.decorators import available_attrs def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): cache_key = view.request.get_full_path() cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated(): return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not view.request.user.is_authenticated(): try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
Use full path as cache key
Use full path as cache key
Python
mit
dreipol/djangocms-spa,dreipol/djangocms-spa
--- +++ @@ -9,7 +9,7 @@ def cache_view(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(view, *args, **kwargs): - cache_key = view.request.path + cache_key = view.request.get_full_path() cached_response = cache.get(cache_key) if cached_response and not view.request.user.is_authenticated():
8a34e665539b10a8e90c86f89a7e2d5881b36519
functional_tests.py
functional_tests.py
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get('http://localhost:8000') # User notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # User is invited to enter a to-do item straight away # User types "Buy peacock feathers" # When user hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list # There is still a text box inviting the user to add another item. # User enters "Use peacock feathers to make a fly" # The page updates again, and now shows both items on their list # User wonders whether the site will remember their list. # Then user sees that the site has generated a unique URL for them # -- there is some explanatory text to that effect. # User visits that URL - their to-do list is still there. # Satisfied, user goes back to sleep if __name__ == '__main__': unittest.main(warnings='ignore')
Add first FT spec comments
Add first FT spec comments
Python
mit
rodowi/remember-the-beer
--- +++ @@ -1,7 +1,42 @@ from selenium import webdriver +import unittest -browser = webdriver.Firefox() -browser.get('http://localhost:8000') +class NewVisitorTest(unittest.TestCase): -assert 'Django' in browser.title + def setUp(self): + self.browser = webdriver.Firefox() + self.browser.implicitly_wait(3) + def tearDown(self): + self.browser.quit() + + def test_can_start_a_list_and_retrieve_it_later(self): + self.browser.get('http://localhost:8000') + + # User notices the page title and header mention to-do lists + self.assertIn('To-Do', self.browser.title) + self.fail('Finish the test!') + + # User is invited to enter a to-do item straight away + + # User types "Buy peacock feathers" + + # When user hits enter, the page updates, and now the page lists + # "1: Buy peacock feathers" as an item in a to-do list + + # There is still a text box inviting the user to add another item. + # User enters "Use peacock feathers to make a fly" + + # The page updates again, and now shows both items on their list + + # User wonders whether the site will remember their list. + # Then user sees that the site has generated a unique URL for them + # -- there is some explanatory text to that effect. + + # User visits that URL - their to-do list is still there. + + # Satisfied, user goes back to sleep + +if __name__ == '__main__': + unittest.main(warnings='ignore') +
e53232a0d4118f415f694084deb602bcc05cb635
scripts/server_socket.py
scripts/server_socket.py
# Echo server program import socket HOST = '' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close()
#!/usr/bin/python import socket import rospy from geometry_msgs.msg import ( Twist ) from std_msgs.msg import ( String, ) class SocketListener(object): def __init__(self, host, port, topic): # ROS stuff first rospy.init_node("myo_socket_listener") self._pub = rospy.Publisher(topic, String) # networking stuff later self.host = host self.port = port self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket.bind((self.host, self.port)) self._socket.listen(1) self._conn, self.addr = self._socket.accept() rospy.loginfo("Connected by %s", self.addr) def loop(self): while 1: data = self._conn.recv(1024) s = repr(data) if not data: break rospy.loginfo("Received: %s", s) self._pub.publish(s) self._conn.sendall(data) self._conn.close() def main(): s = SocketListener('', 50007, 'myo_data') s.loop() if __name__ == "__main__": main()
Create class for server and create publisher
Create class for server and create publisher
Python
mit
ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo,ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc
--- +++ @@ -1,15 +1,48 @@ -# Echo server program +#!/usr/bin/python + import socket -HOST = '' # Symbolic name meaning all available interfaces -PORT = 50007 # Arbitrary non-privileged port -s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -s.bind((HOST, PORT)) -s.listen(1) -conn, addr = s.accept() -print 'Connected by', addr -while 1: - data = conn.recv(1024) - if not data: break - conn.sendall(data) -conn.close() +import rospy +from geometry_msgs.msg import ( + Twist +) +from std_msgs.msg import ( + String, +) + +class SocketListener(object): + + def __init__(self, host, port, topic): + # ROS stuff first + rospy.init_node("myo_socket_listener") + self._pub = rospy.Publisher(topic, String) + + # networking stuff later + self.host = host + self.port = port + self._socket = socket.socket(socket.AF_INET, + socket.SOCK_STREAM) + self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._socket.bind((self.host, self.port)) + self._socket.listen(1) + self._conn, self.addr = self._socket.accept() + rospy.loginfo("Connected by %s", self.addr) + + def loop(self): + while 1: + data = self._conn.recv(1024) + s = repr(data) + if not data: + break + rospy.loginfo("Received: %s", s) + self._pub.publish(s) + self._conn.sendall(data) + self._conn.close() + + +def main(): + s = SocketListener('', 50007, 'myo_data') + s.loop() + +if __name__ == "__main__": + main()
7a408eb5186ef5a7adce026f0629ee1592cd6077
inpassing/config.py
inpassing/config.py
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3' SQLALCHEMY_TRACK_MODIFICATIONS=False
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. import os SECRET_KEY=os.getenv('INPASSING_SECRET_KEY') SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3' SQLALCHEMY_TRACK_MODIFICATIONS=False
Use a secret key (get it from an env var)
Use a secret key (get it from an env var)
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. +import os +SECRET_KEY=os.getenv('INPASSING_SECRET_KEY') + SQLALCHEMY_DATABASE_URI='sqlite:///db.sqlite3' SQLALCHEMY_TRACK_MODIFICATIONS=False
7c2311534cf1cbef7880795827c88e7ce075e2ae
tests/pthread_barrier/tests/01-run.py
tests/pthread_barrier/tests/01-run.py
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect(f'Start {i + 1}') for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect(r'NUM_CHILDREN: (\d+), NUM_ITERATIONS: (\d+)\r\n') children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): child.expect('Start {}'.format(i + 1)) for _ in range(iterations): sleeps = [] for _ in range(children): child.expect(r'Child (\d+) sleeps for \s* (\d+) us.\r\n') child_num = int(child.match.group(1)) sleep = int(child.match.group(2)) sleeps.append([sleep, child_num]) for _, child_num in sorted(sleeps): child.expect(r'Done (\d+)\r\n') assert(child_num == int(child.match.group(1))) child.expect('SUCCESS') if __name__ == "__main__": sys.exit(run(testfunc))
Remove f string in test
tests/thread_pthread_barrier: Remove f string in test This causes nightlies to fail as the HiL test runners don't have python3.6+
Python
lgpl-2.1
kYc0o/RIOT,OlegHahm/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,jasonatran/RIOT,OlegHahm/RIOT,ant9000/RIOT,miri64/RIOT,kaspar030/RIOT,kaspar030/RIOT,RIOT-OS/RIOT,kYc0o/RIOT,kYc0o/RIOT,ant9000/RIOT,miri64/RIOT,miri64/RIOT,OlegHahm/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,ant9000/RIOT,jasonatran/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,RIOT-OS/RIOT,jasonatran/RIOT,kYc0o/RIOT,RIOT-OS/RIOT,miri64/RIOT,OlegHahm/RIOT,kaspar030/RIOT,ant9000/RIOT,kaspar030/RIOT,kYc0o/RIOT
--- +++ @@ -9,7 +9,7 @@ children = int(child.match.group(1)) iterations = int(child.match.group(2)) for i in range(children): - child.expect(f'Start {i + 1}') + child.expect('Start {}'.format(i + 1)) for _ in range(iterations): sleeps = [] for _ in range(children):
316b1f87be3ec75ea629cd95d7727151d8f11391
prompt_toolkit/layout/mouse_handlers.py
prompt_toolkit/layout/mouse_handlers.py
from __future__ import unicode_literals from itertools import product from collections import defaultdict __all__ = ( 'MouseHandlers', ) class MouseHandlers(object): """ Two dimentional raster of callbacks for mouse events. """ def __init__(self): def dummy_callback(mouse_event): """ :param mouse_event: `MouseEvent` instance. """ # Map (x,y) tuples to handlers. self.mouse_handlers = defaultdict(lambda: dummy_callback) def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None): """ Set mouse handler for a region. """ for x, y in product(range(x_min, x_max), range(y_min, y_max)): self.mouse_handlers[x, y] = handler
from __future__ import unicode_literals from itertools import product from collections import defaultdict __all__ = ( 'MouseHandlers', ) class MouseHandlers(object): """ Two dimensional raster of callbacks for mouse events. """ def __init__(self): def dummy_callback(mouse_event): """ :param mouse_event: `MouseEvent` instance. """ # Map (x,y) tuples to handlers. self.mouse_handlers = defaultdict(lambda: dummy_callback) def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None): """ Set mouse handler for a region. """ for x, y in product(range(x_min, x_max), range(y_min, y_max)): self.mouse_handlers[x, y] = handler
Fix typo: `dimentional` -> `dimensional`
Fix typo: `dimentional` -> `dimensional`
Python
bsd-3-clause
jonathanslenders/python-prompt-toolkit
--- +++ @@ -10,7 +10,7 @@ class MouseHandlers(object): """ - Two dimentional raster of callbacks for mouse events. + Two dimensional raster of callbacks for mouse events. """ def __init__(self): def dummy_callback(mouse_event):
bfbb685854724285bdbfcd583b3d6c41674a6222
vext/syspy/pyinfo.py
vext/syspy/pyinfo.py
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'], "sys.path": sys.path } return data if __name__ == '__main__': print json.dumps(py_info())
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'].split(os.pathsep), "sys.path": sys.path } return data if __name__ == '__main__': print json.dumps(py_info())
Make sure path is in a list
Make sure path is in a list
Python
mit
stuaxo/vext
--- +++ @@ -13,7 +13,7 @@ """ def py_info(): data = { - "path": os.environ['PATH'], + "path": os.environ['PATH'].split(os.pathsep), "sys.path": sys.path } return data
6346c8844bc654806e39cf294dad3c57ec303589
vezilka/lib/utils.py
vezilka/lib/utils.py
from __future__ import absolute_import, division from genshi.output import DocType from genshi.template import TemplateLoader from .restzeug import Response, Request as BaseRequest class Request(BaseRequest): '''This is the central Request class used in Vezilka. It will need to supply all the API needed by the views (controllers)''' def render(self, template_name, **data): loader = self.app.config['GenshiLoader'] template = loader.load(template_name) stream = template.generate(req=self, **data) response = stream.render('html', doctype=DocType.HTML_TRANSITIONAL) # response = stream.render('xhtml', doctype=DocType.XHTML_STRICT) return Response(response) __all__ = ('Request', )
from __future__ import absolute_import, division from genshi.output import DocType from genshi.template import TemplateLoader from .restzeug import Response, Request as BaseRequest class Request(BaseRequest): '''This is the central Request class used in Vezilka. It will need to supply all the API needed by the views (controllers)''' def render(self, template_name, **data): loader = self.global_config['GenshiLoader'] template = loader.load(template_name) stream = template.generate(req=self, **data) response = stream.render('html', doctype=DocType.HTML_TRANSITIONAL) # response = stream.render('xhtml', doctype=DocType.XHTML_STRICT) return Response(response) __all__ = ('Request', )
Use Request.global_config in Request.render too
Use Request.global_config in Request.render too
Python
mit
gdamjan/vezilka
--- +++ @@ -10,7 +10,7 @@ supply all the API needed by the views (controllers)''' def render(self, template_name, **data): - loader = self.app.config['GenshiLoader'] + loader = self.global_config['GenshiLoader'] template = loader.load(template_name) stream = template.generate(req=self, **data) response = stream.render('html', doctype=DocType.HTML_TRANSITIONAL)
fd48bda18bac9fe5380205ba1333af0d4066ae82
tests/test_types.py
tests/test_types.py
import numpy as np from pybotics.types import Vector def test_vector(): x = [1.1, 2.2, 3.3] assert isinstance(x, Vector) x = np.array([1.1, 2.2, 3.3]) assert isinstance(x, Vector) x = (1.1, 2.2, 3.3) assert isinstance(x, Vector) pass
import numpy as np from typing import List from pybotics.types import Vector def test_vector(): pass
Revert "want to be able to test for Vector type"
Revert "want to be able to test for Vector type" This reverts commit 93f09d784a73adcdccef3a77cf8fdc2d12ce4518.
Python
mit
nnadeau/pybotics
--- +++ @@ -1,14 +1,8 @@ import numpy as np +from typing import List + from pybotics.types import Vector def test_vector(): - x = [1.1, 2.2, 3.3] - assert isinstance(x, Vector) - - x = np.array([1.1, 2.2, 3.3]) - assert isinstance(x, Vector) - - x = (1.1, 2.2, 3.3) - assert isinstance(x, Vector) pass
436b005217ab92fd06526d9681bc37266c394212
estmator_project/est_quote/views.py
estmator_project/est_quote/views.py
from .models import Quote, Category, Product from django.views.generic.edit import CreateView, UpdateView class QuoteCreateView(CreateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self, form): form = super(QuoteCreateView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteCreateView, self).form_valid(form) class QuoteEditView(UpdateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self, form): form = super(QuoteEditView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteEditView, self).form_valid(form)
from .models import Quote, Category, Product from django.views.generic.edit import CreateView, UpdateView class QuoteCreateView(CreateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self): form = super(QuoteCreateView, self).get_form() # form.fields['category'].queryset = Category.objects.all() # form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteCreateView, self).form_valid(form) class QuoteEditView(UpdateView): model = Quote fields = ['name'] template_name = 'quote.html' success_url = '/' def get_form(self): form = super(QuoteEditView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): form.instance.user = self.request.user return super(QuoteEditView, self).form_valid(form)
Update view for basic quote form.
Update view for basic quote form.
Python
mit
Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp
--- +++ @@ -8,10 +8,10 @@ template_name = 'quote.html' success_url = '/' - def get_form(self, form): + def get_form(self): form = super(QuoteCreateView, self).get_form() - form.fields['category'].queryset = Category.objects.all() - form.fields['products'].queryset = Product.objects.all() + # form.fields['category'].queryset = Category.objects.all() + # form.fields['products'].queryset = Product.objects.all() return form def form_valid(self, form): @@ -25,7 +25,7 @@ template_name = 'quote.html' success_url = '/' - def get_form(self, form): + def get_form(self): form = super(QuoteEditView, self).get_form() form.fields['category'].queryset = Category.objects.all() form.fields['products'].queryset = Product.objects.all()
9d2161ada6a0d957ca13e49431533770ef672014
files.py
files.py
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1))): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor return samples, fs
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)) - 1)), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
Allow mixing the loaded WAV file from stereo to mono.
Allow mixing the loaded WAV file from stereo to mono.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
--- +++ @@ -14,7 +14,7 @@ samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) -def load_wav(filename, factor=(1 / (((2**15)) - 1))): +def load_wav(filename, factor=(1 / (((2**15)) - 1)), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and @@ -23,4 +23,12 @@ ''' fs, samples = wavfile.read(filename) samples = samples * factor + if mono_mix: + samples = to_mono(samples) return samples, fs + +def to_mono(samples): + if samples.ndim == 1: + return samples + else: + return samples.mean(axis=-1)
a4bdb7113dba8ed819d8454a1e8f2916ee33d9a6
dns/exception.py
dns/exception.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNS Exceptions.""" class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" pass class FormError(DNSException): """DNS message is malformed.""" pass class SyntaxError(DNSException): """Text input is malformed.""" pass class UnexpectedEnd(SyntaxError): """Raised if text input ends unexpectedly.""" pass class TooBig(DNSException): """The message is too big.""" pass class Timeout(DNSException): """The operation timed out.""" pass
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNS Exceptions.""" class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" def __init__(self, *args): if args: super(DNSException, self).__init__(*args) else: # doc string is better implicit message than empty string super(DNSException, self).__init__(self.__doc__) class FormError(DNSException): """DNS message is malformed.""" pass class SyntaxError(DNSException): """Text input is malformed.""" pass class UnexpectedEnd(SyntaxError): """Raised if text input ends unexpectedly.""" pass class TooBig(DNSException): """The message is too big.""" pass class Timeout(DNSException): """The operation timed out.""" pass
Support string representation for all DNSExceptions.
Support string representation for all DNSExceptions. Doc string is used in cases where more specific message was not provided during instantiation/raise.
Python
isc
rcorrieri/dnspython,leeclemens/dnspython,Abhayakara/dnspython,fjxhkj/dnspython,tow/dnspython,cluck/dnspython,tomlanyon/dnspython,preo/dnspython
--- +++ @@ -17,7 +17,12 @@ class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" - pass + def __init__(self, *args): + if args: + super(DNSException, self).__init__(*args) + else: + # doc string is better implicit message than empty string + super(DNSException, self).__init__(self.__doc__) class FormError(DNSException): """DNS message is malformed."""
ca350c19c068989f3261ea544e660ba14566c376
qr_code/qrcode/constants.py
qr_code/qrcode/constants.py
from datetime import datetime from qrcode import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H from qr_code.qrcode.image import SVG_FORMAT_NAME QR_CODE_GENERATION_VERSION_DATE = datetime(year=2018, month=3, day=15, hour=0) SIZE_DICT = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTION_DICT = {'L': ERROR_CORRECT_L, 'M': ERROR_CORRECT_M, 'Q': ERROR_CORRECT_Q, 'H': ERROR_CORRECT_H} DEFAULT_MODULE_SIZE = 'M' DEFAULT_BORDER_SIZE = 4 DEFAULT_VERSION = None DEFAULT_IMAGE_FORMAT = SVG_FORMAT_NAME DEFAULT_ERROR_CORRECTION = 'M' DEFAULT_CACHE_ENABLED = True DEFAULT_URL_SIGNATURE_ENABLED = True ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER = 'ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER' ALLOWS_EXTERNAL_REQUESTS = 'ALLOWS_EXTERNAL_REQUESTS' SIGNING_KEY = 'SIGNING_KEY' TOKEN_LENGTH = 'TOKEN_LENGTH' SIGNING_SALT = 'SIGNING_SALT'
from datetime import datetime from qrcode import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H from qr_code.qrcode.image import SVG_FORMAT_NAME QR_CODE_GENERATION_VERSION_DATE = datetime(year=2019, month=4, day=11, hour=15) SIZE_DICT = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTION_DICT = {'L': ERROR_CORRECT_L, 'M': ERROR_CORRECT_M, 'Q': ERROR_CORRECT_Q, 'H': ERROR_CORRECT_H} DEFAULT_MODULE_SIZE = 'M' DEFAULT_BORDER_SIZE = 4 DEFAULT_VERSION = None DEFAULT_IMAGE_FORMAT = SVG_FORMAT_NAME DEFAULT_ERROR_CORRECTION = 'M' DEFAULT_CACHE_ENABLED = True DEFAULT_URL_SIGNATURE_ENABLED = True ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER = 'ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER' ALLOWS_EXTERNAL_REQUESTS = 'ALLOWS_EXTERNAL_REQUESTS' SIGNING_KEY = 'SIGNING_KEY' TOKEN_LENGTH = 'TOKEN_LENGTH' SIGNING_SALT = 'SIGNING_SALT'
Update last modified date for HTTP 304 after migrating to qr_code 6.1.
Update last modified date for HTTP 304 after migrating to qr_code 6.1.
Python
bsd-3-clause
dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code
--- +++ @@ -4,7 +4,7 @@ from qr_code.qrcode.image import SVG_FORMAT_NAME -QR_CODE_GENERATION_VERSION_DATE = datetime(year=2018, month=3, day=15, hour=0) +QR_CODE_GENERATION_VERSION_DATE = datetime(year=2019, month=4, day=11, hour=15) SIZE_DICT = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTION_DICT = {'L': ERROR_CORRECT_L, 'M': ERROR_CORRECT_M, 'Q': ERROR_CORRECT_Q, 'H': ERROR_CORRECT_H} DEFAULT_MODULE_SIZE = 'M'
b3b85d3a481e4b2cf9df37666a9527ccf8a13bfc
build/fbcode_builder/specs/fbthrift.py
build/fbcode_builder/specs/fbthrift.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.fmt as fmt import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle import specs.zstd as zstd from shell_quoting import ShellQuoted def fbcode_builder_spec(builder): # This API should change rarely, so build the latest tag instead of master. builder.add_option( 'no1msd/mstch:git_hash', ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { 'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'), builder.cmake_install('no1msd/mstch'), builder.fb_github_cmake_install('fbthrift/thrift'), ], }
Migrate from Folly Format to fmt
Migrate from Folly Format to fmt Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size. Reviewed By: alandau Differential Revision: D14954926 fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
Python
unknown
phoad/rsocket-cpp,rsocket/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp,phoad/rsocket-cpp,phoad/rsocket-cpp,rsocket/rsocket-cpp,rsocket/rsocket-cpp,phoad/rsocket-cpp,ReactiveSocket/reactivesocket-cpp
--- +++ @@ -7,6 +7,7 @@ import specs.folly as folly import specs.fizz as fizz +import specs.fmt as fmt import specs.rsocket as rsocket import specs.sodium as sodium import specs.wangle as wangle @@ -22,7 +23,7 @@ ShellQuoted('$(git describe --abbrev=0 --tags)') ) return { - 'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd], + 'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd], 'steps': [ # This isn't a separete spec, since only fbthrift uses mstch. builder.github_project_workdir('no1msd/mstch', 'build'),
c3c95bcfda3af1bc88370dc5108aa7032bcdacff
setup.py
setup.py
# -*- coding: utf-8 -*- import os from setuptools import find_packages from setuptools import setup base_dir = os.path.dirname(__file__) setup( name='elastalert', version='0.0.72', description='Runs custom filters on Elasticsearch and alerts on matches', author='Quentin Long', author_email='qlo@yelp.com', setup_requires='setuptools', license='Copyright 2014 Yelp', entry_points={ 'console_scripts': ['elastalert-create-index=elastalert.create_index:main', 'elastalert-test-rule=elastalert.test_rule:main', 'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main', 'elastalert=elastalert.elastalert:main']}, packages=find_packages(), package_data={'elastalert': ['schema.yaml']}, install_requires=[ 'argparse', 'elasticsearch', 'jira==0.32', # jira.exceptions is missing from later versions 'jsonschema', 'mock', 'python-dateutil', 'PyStaticConfiguration', 'pyyaml', 'simplejson', 'boto', 'blist' ] )
# -*- coding: utf-8 -*- import os from setuptools import find_packages from setuptools import setup base_dir = os.path.dirname(__file__) setup( name='elastalert', version='0.0.72', description='Runs custom filters on Elasticsearch and alerts on matches', author='Quentin Long', author_email='qlo@yelp.com', setup_requires='setuptools', license='Copyright 2014 Yelp', entry_points={ 'console_scripts': ['elastalert-create-index=elastalert.create_index:main', 'elastalert-test-rule=elastalert.test_rule:main', 'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main', 'elastalert=elastalert.elastalert:main']}, packages=find_packages(), package_data={'elastalert': ['schema.yaml']}, install_requires=[ 'argparse', 'elasticsearch', 'jira==0.32', # jira.exceptions is missing from later versions 'jsonschema', 'mock', 'python-dateutil', 'PyStaticConfiguration', 'pyyaml', 'simplejson', 'boto', 'blist', 'croniter' ] )
Add croniter as an install dependency.
Add croniter as an install dependency.
Python
apache-2.0
dvopsway/elastalert,Yelp/elastalert,ltagliamonte/elastalert,rprabhat/elastalert,jetyang2005/elastalert,jetyang2005/elastalert,jetyang2005/elastalert,iamrudra/elastalert
--- +++ @@ -32,6 +32,7 @@ 'pyyaml', 'simplejson', 'boto', - 'blist' + 'blist', + 'croniter' ] )
592f43df660fe87e0fce30e390019ed0a031a5aa
setup.py
setup.py
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='simplekv', version='0.9.4.dev1', description=('A key-value storage for binary data, support many ' 'backends.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/simplekv', license='MIT', packages=find_packages(exclude=['test']), install_requires=['six'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='simplekv', version='0.9.4.dev1', description=('A key-value storage for binary data, support many ' 'backends.'), long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/simplekv', license='MIT', packages=find_packages(exclude=['test']), install_requires=[], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Remove dependency on six for simplekv.
Remove dependency on six for simplekv.
Python
mit
karteek/simplekv,fmarczin/simplekv,fmarczin/simplekv,mbr/simplekv,mbr/simplekv,karteek/simplekv
--- +++ @@ -20,7 +20,7 @@ url='http://github.com/mbr/simplekv', license='MIT', packages=find_packages(exclude=['test']), - install_requires=['six'], + install_requires=[], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3',
3dc90a8173dd3520fd4f335efe9adb77b9167f80
setup.py
setup.py
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
Fix data_files to install man and license documents
Setup: Fix data_files to install man and license documents
Python
isc
toddgaunt/imgfetch
--- +++ @@ -14,8 +14,8 @@ package_dir = {'danboorsync':'src'}, # Change these per distribution - data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), - ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], + data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), + ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync'
509abc7bf7fc73dcb06b1eb1738b2e3a3ed4d438
setup.py
setup.py
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/polygraph-python/polygraph', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'graphql-core>=1.0.1', ], extras_require={ 'dev': [ 'flake8', 'ipython', 'autopep8', 'isort', 'pudb==2017.1.2', 'twine==1.8.1', 'coverage', ], 'test': [ 'coverage', 'coveralls', ] } )
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/polygraph-python/polygraph', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'graphql-core>=1.0.1', ], extras_require={ 'dev': [ 'flake8', 'ipython', 'autopep8', 'isort', 'pudb==2017.1.2', 'twine==1.8.1', 'coverage', 'virtualenvwrapper', ], 'test': [ 'coverage', 'coveralls', ] } )
Add virtualenvwrapper to dev requirements
Add virtualenvwrapper to dev requirements
Python
mit
polygraph-python/polygraph
--- +++ @@ -21,6 +21,7 @@ 'pudb==2017.1.2', 'twine==1.8.1', 'coverage', + 'virtualenvwrapper', ], 'test': [ 'coverage',
738bab6b6df6ea0b7ac3b97ceadef8a50c90cf78
setup.py
setup.py
#! /usr/bin/env python from setuptools import setup, find_packages setup( name='armet', version='0.3.0-pre', description='Clean and modern framework for creating RESTful APIs.', author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/armet/python-armet', package_dir={'armet': 'src/armet'}, packages=find_packages('src'), install_requires=( 'six', # Python 2 and 3 normalization layer 'python-mimeparse' # For parsing accept and content-type headers ), extras_require={ 'test': ( 'nose', 'yanc', 'httplib2', 'flask', 'django' ) } )
#! /usr/bin/env python from setuptools import setup, find_packages setup( name='armet', version='0.3.0-pre', description='Clean and modern framework for creating RESTful APIs.', author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/armet/python-armet', package_dir={'armet': 'src/armet'}, packages=find_packages('src'), install_requires=( 'six', # Python 2 and 3 normalization layer 'python-mimeparse' # For parsing accept and content-type headers ), extras_require={ 'test': ( 'nose', 'yanc', 'httplib2', 'flask', 'django', 'wsgi_intercept' ) } )
Add wsgi_intercept to the dependencies list
Add wsgi_intercept to the dependencies list
Python
mit
armet/python-armet
--- +++ @@ -21,7 +21,8 @@ 'yanc', 'httplib2', 'flask', - 'django' + 'django', + 'wsgi_intercept' ) } )
4b933366d1a8e849ac8f07c9075e939dd4ed3f5f
setup.py
setup.py
from setuptools import setup setup( name='tangled.contrib', version='0.1a3.dev0', description='Tangled namespace for contributed packages', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.contrib', 'tangled.contrib.scaffolds', 'tangled.contrib.tests', ], include_package_data=True, install_requires=[ 'tangled>=0.1.dev0', ], extras_require={ 'dev': [ 'tangled[dev]', ], }, entry_points=""" [tangled.scaffolds] contrib = tangled.contrib.scaffolds:default contrib-core = tangled.contrib.scaffolds:core """, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], )
from setuptools import setup setup( name='tangled.contrib', version='0.1a3.dev0', description='Tangled namespace for contributed packages', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.contrib', 'tangled.contrib.scaffolds', 'tangled.contrib.tests', ], include_package_data=True, install_requires=[ 'tangled>=0.1a5', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a5', ], }, entry_points=""" [tangled.scaffolds] contrib = tangled.contrib.scaffolds:default contrib-core = tangled.contrib.scaffolds:core """, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], )
Make released version of tangled 0.1a5 the min
Make released version of tangled 0.1a5 the min
Python
mit
TangledWeb/tangled.contrib
--- +++ @@ -17,11 +17,11 @@ ], include_package_data=True, install_requires=[ - 'tangled>=0.1.dev0', + 'tangled>=0.1a5', ], extras_require={ 'dev': [ - 'tangled[dev]', + 'tangled[dev]>=0.1a5', ], }, entry_points="""
99359ed1485f9e5235f5b6c02f331a7e4d9d277b
setup.py
setup.py
#!/usr/bin/env python VERSION = "0.5.3" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
#!/usr/bin/env python VERSION = "0.5.4" from setuptools import setup, find_packages import sys classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' # Choose a version of ftfy to use depending on the version of Python if sys.version_info[0] < 3: FTFY_DEP = 'ftfy >= 4.3, < 5' else: FTFY_DEP = 'ftfy >= 5' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', FTFY_DEP ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
Choose a version of ftfy to use depending on the version of Python
Choose a version of ftfy to use depending on the version of Python
Python
mit
LuminosoInsight/luminoso-api-client-python
--- +++ @@ -1,7 +1,8 @@ #!/usr/bin/env python -VERSION = "0.5.3" +VERSION = "0.5.4" from setuptools import setup, find_packages +import sys classifiers = [ 'Intended Audience :: Developers', @@ -12,6 +13,14 @@ ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' + + +# Choose a version of ftfy to use depending on the version of Python +if sys.version_info[0] < 3: + FTFY_DEP = 'ftfy >= 4.3, < 5' +else: + FTFY_DEP = 'ftfy >= 5' + setup( name="luminoso-api", @@ -26,7 +35,7 @@ packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', - 'ftfy >= 3.3, < 5', + FTFY_DEP ], entry_points={ 'console_scripts': [
9ddb2df626f1fd355cad26f84b10527358ea6993
setup.py
setup.py
from setuptools import setup, find_packages setup( name='smartmin', version=__import__('smartmin').__version__, license="BSD", install_requires=[ "django>=1.7", "django-guardian==1.3", "django_compressor", "pytz", "xlrd", "xlwt", ], description="Scaffolding system for Django object management.", long_description=open('README.rst').read(), author='Nyaruka Ltd', author_email='code@nyaruka.com', url='http://github.com/nyaruka/smartmin', download_url='http://github.com/nyaruka/smartmin/downloads', include_package_data=True, packages=find_packages(), zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
from setuptools import setup, find_packages def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#") def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)] setup( name='smartmin', version=__import__('smartmin').__version__, license="BSD", install_requires=_read_requirements("requirements/base.txt"), tests_require=_read_requirements("requirements/tests.txt"), description="Scaffolding system for Django object management.", long_description=open('README.rst').read(), author='Nyaruka Ltd', author_email='code@nyaruka.com', url='http://github.com/nyaruka/smartmin', download_url='http://github.com/nyaruka/smartmin/downloads', include_package_data=True, packages=find_packages(), zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
Read requirements from file to reduce duplication
Read requirements from file to reduce duplication
Python
bsd-3-clause
caktus/smartmin,nyaruka/smartmin,caktus/smartmin,nyaruka/smartmin,nyaruka/smartmin,caktus/smartmin,caktus/smartmin
--- +++ @@ -1,18 +1,26 @@ from setuptools import setup, find_packages + + +def _is_requirement(line): + """Returns whether the line is a valid package requirement.""" + line = line.strip() + return line and not line.startswith("#") + + +def _read_requirements(filename): + """Parses a file for pip installation requirements.""" + with open(filename) as requirements_file: + contents = requirements_file.read() + return [line.strip() for line in contents.splitlines() if _is_requirement(line)] + setup( name='smartmin', version=__import__('smartmin').__version__, license="BSD", - install_requires=[ - "django>=1.7", - "django-guardian==1.3", - "django_compressor", - "pytz", - "xlrd", - "xlwt", - ], + install_requires=_read_requirements("requirements/base.txt"), + tests_require=_read_requirements("requirements/tests.txt"), description="Scaffolding system for Django object management.", long_description=open('README.rst').read(),
888ffba93f4b9ed9a889aebd9d3e4296b469579d
setup.py
setup.py
#!/usr/bin/env python2.6 try: from setuptools import setup except: from distutils.core import setup def getVersion(): import os packageSeedFile = os.path.join("lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = version.package, version = version.short(), description = "Pub Client and Service", long_description = "Pub key management service and client", author = "Oliver Gould", author_email = "ver@yahoo-inc.com", maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com", requires = ["jersey", "twisted", "twisted.conch", "pendrell(>=0.2.0)", ], packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ], scripts = ["bin/jget", "bin/pubc", ], package_dir = {"pub": "lib", }, package_data = {"twisted.plugins": ["pubs.py"], }, )
#!/usr/bin/env python2.6 try: from setuptools import setup except: from distutils.core import setup def getVersion(): import os packageSeedFile = os.path.join("lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = version.package, version = version.short(), description = "Pub Client and Service", long_description = "Pub key management service and client", author = "Oliver Gould", author_email = "ver@yahoo-inc.com", maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com", requires = ["jersey", "Twisted", "pendrell>=0.3.0", ], packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ], scripts = ["bin/jget", "bin/pubc", ], package_dir = {"pub": "lib", }, package_data = {"twisted.plugins": ["pubs.py"], }, )
Fix Twisted requirement (I think?)
Fix Twisted requirement (I think?) git-svn-id: 0754dbe6ae3ac1ca1635dae9a69e589ef5e7cc4d@61 8ed0a6ef-5846-dd11-a15a-00e9354ff7a0
Python
bsd-3-clause
olix0r/pub
--- +++ @@ -26,7 +26,7 @@ author = "Oliver Gould", author_email = "ver@yahoo-inc.com", maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com", - requires = ["jersey", "twisted", "twisted.conch", "pendrell(>=0.2.0)", ], + requires = ["jersey", "Twisted", "pendrell>=0.3.0", ], packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ], scripts = ["bin/jget", "bin/pubc", ], package_dir = {"pub": "lib", },
f94bc30004aa9977bac652d337f69069efc132bd
marmoset/pxe/__init__.py
marmoset/pxe/__init__.py
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
Implement better result output for pxe config file crete
Python
agpl-3.0
aibor/marmoset
--- +++ @@ -4,9 +4,13 @@ def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) - pxe_client.create(Label.find(args.label)) - msg = 'Created %s with password %s' - print(msg % (pxe_client.file_path(), pxe_client.password)) + used_options = pxe_client.create(Label.find(args.label)) + + msg = 'Created %s with following Options:' + + print(msg % pxe_client.file_path()) + for option in used_options: + print("\t%s" % option) def list(args):
26cc2332c2531ebde3e831d6513b93f2f021bc51
RaspberryPi/setup.py
RaspberryPi/setup.py
#!/usr/bin/env python3 from setuptools import setup packages = [ 'ardupi_weather', 'ardupi_weather.arduino', 'ardupi_weather.database', 'ardupi_weather.flaskfiles.app' ] extras = { 'rpi':['RPI.GPIO>=0.6.1'] } setup( name='ardupi_weather', url='https://github.com/jordivilaseca/Weather-station', license='Apache License, Version 2.0', author='Jordi Vilaseca', author_email='jordivilaseca@outlook.com', description='Weather station with Raspberry Pi and Arduino', long_description=open('../README.md').read(), packages=[str(l) for l in packages], zip_safe=False, include_package_data=True, extras_require=extras, install_requires=[ 'Flask>=0.10.1', 'pymongo>=3.2.2', 'PyYAML>=3.11', 'bson>=0.4.2', 'pyserial>=3.0.1' ], entry_points={ 'console_scripts': [ 'weather-station = ardupi_weather.station:main', 'weather-server = ardupi_weather.flaskapp:main' ], }, )
#!/usr/bin/env python3 from setuptools import setup packages = [ 'ardupi_weather', 'ardupi_weather.arduino', 'ardupi_weather.database', 'ardupi_weather.flaskfiles.app' ] extras = { 'rpi':['RPI.GPIO>=0.6.1'] } setup( name='ardupi_weather', url='https://github.com/jordivilaseca/Weather-station', license='Apache License, Version 2.0', author='Jordi Vilaseca', author_email='jordivilaseca@outlook.com', description='Weather station with Raspberry Pi and Arduino', long_description=open('../README.md').read(), packages=[str(l) for l in packages], zip_safe=False, include_package_data=True, extras_require=extras, install_requires=[ 'Flask>=0.10.1', 'pymongo>=3.2.2', 'PyYAML>=3.11', 'pyserial>=3.0.1' ], entry_points={ 'console_scripts': [ 'weather-station = ardupi_weather.station:main', 'weather-server = ardupi_weather.flaskapp:main' ], }, )
Remove bson of the required packages
Remove bson of the required packages
Python
mit
jordivilaseca/ardupi-weather,jordivilaseca/ardupi-weather,jordivilaseca/ardupi-weather
--- +++ @@ -29,7 +29,6 @@ 'Flask>=0.10.1', 'pymongo>=3.2.2', 'PyYAML>=3.11', - 'bson>=0.4.2', 'pyserial>=3.0.1' ], entry_points={
bfbc2bc38cbc7cbcd0afbb8d077fccf1925c0c16
gaphor/SysML/blocks/grouping.py
gaphor/SysML/blocks/grouping.py
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class NodeGroup(AbstractGroup): """ Add node to another node. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
from gaphor.diagram.grouping import AbstractGroup, Group from gaphor.SysML.blocks.block import BlockItem from gaphor.SysML.blocks.property import PropertyItem @Group.register(BlockItem, PropertyItem) class PropertyGroup(AbstractGroup): """ Add Property to a Block. """ def group(self): self.parent.subject.ownedAttribute = self.item.subject def ungroup(self): del self.parent.subject.ownedAttribute[self.item.subject]
Fix name for property/block group
Fix name for property/block group
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
--- +++ @@ -4,9 +4,9 @@ @Group.register(BlockItem, PropertyItem) -class NodeGroup(AbstractGroup): +class PropertyGroup(AbstractGroup): """ - Add node to another node. + Add Property to a Block. """ def group(self):
a48eb39dacba67b4c8638664c9df717837099c05
genthreads/actor.py
genthreads/actor.py
from multiprocessing import process class Actor(process.BaseProcess): def __init__(self): super(Actor, self).__init__() self._inbox = list() def send(self, value): self._inbox.append(value) @property def inbox(self): return self._inbox
from multiprocessing import Process class Actor(Process): def __init__(self): super(Actor, self).__init__() self._inbox = list() def send(self, value): self._inbox.append(value) @property def inbox(self): return self._inbox
Change BaseProcess to Process as a parent class for Actor
Change BaseProcess to Process as a parent class for Actor
Python
mit
f1sty/genthreads
--- +++ @@ -1,7 +1,7 @@ -from multiprocessing import process +from multiprocessing import Process -class Actor(process.BaseProcess): +class Actor(Process): def __init__(self): super(Actor, self).__init__() self._inbox = list()
5961a8e5f163d35f093e66a649917c7f36201d0a
pre_commit/logging_handler.py
pre_commit/logging_handler.py
from __future__ import unicode_literals import logging import sys from pre_commit import color LOG_LEVEL_COLORS = { 'DEBUG': '', 'INFO': '', 'WARNING': color.YELLOW, 'ERROR': color.RED, } class LoggingHandler(logging.Handler): def __init__(self, use_color, write=sys.stdout.write): logging.Handler.__init__(self) self.use_color = use_color self.__write = write def emit(self, record): self.__write( u'{0}{1}\n'.format( color.format_color( '[{0}]'.format(record.levelname), LOG_LEVEL_COLORS[record.levelname], self.use_color, ) + ' ', record.getMessage(), ) ) sys.stdout.flush()
from __future__ import unicode_literals import logging import sys from pre_commit import color LOG_LEVEL_COLORS = { 'DEBUG': '', 'INFO': '', 'WARNING': color.YELLOW, 'ERROR': color.RED, } class LoggingHandler(logging.Handler): def __init__(self, use_color, write=sys.stdout.write): super(LoggingHandler, self).__init__() self.use_color = use_color self.__write = write def emit(self, record): self.__write( u'{0}{1}\n'.format( color.format_color( '[{0}]'.format(record.levelname), LOG_LEVEL_COLORS[record.levelname], self.use_color, ) + ' ', record.getMessage(), ) ) sys.stdout.flush()
Use super() ('newstyle class' in 2.7+)
Use super() ('newstyle class' in 2.7+)
Python
mit
philipgian/pre-commit,philipgian/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,Lucas-C/pre-commit,philipgian/pre-commit,Lucas-C/pre-commit,Lucas-C/pre-commit,Lucas-C/pre-commit,philipgian/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,pre-commit/pre-commit,philipgian/pre-commit,pre-commit/pre-commit,Lucas-C/pre-commit,Lucas-C/pre-commit,philipgian/pre-commit
--- +++ @@ -16,7 +16,7 @@ class LoggingHandler(logging.Handler): def __init__(self, use_color, write=sys.stdout.write): - logging.Handler.__init__(self) + super(LoggingHandler, self).__init__() self.use_color = use_color self.__write = write
04f3003c8ac261edd862323624bbdba565b9e36c
download.py
download.py
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) jsondata = resp.read() data = json.loads(jsondata) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
Remove jsondata variable to simplify the code
Remove jsondata variable to simplify the code
Python
mit
bangbangbear/ximalayaDownloader
--- +++ @@ -13,8 +13,7 @@ for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) - jsondata = resp.read() - data = json.loads(jsondata) + data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local:
7d82f3accce0cf174fd7cf176d5c289ffc791647
ds_queue.py
ds_queue.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): queue = Queue() print('Is empty: {}'.format(queue.is_empty())) print('Enqueue "dog", 4 & 8.4') queue.enqueue('dog') queue.enqueue(4) queue.enqueue(8.4) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Dequeue: {}'.format(queue.dequeue())) print('Is empty: {}'.format(queue.is_empty())) print('Queue size: {}'.format(queue.size())) print('Show: {}'.format(queue.show())) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division class Queue(object): """Queue class.""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def peek(self): return self.items[-1] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def main(): q = Queue() print('Is empty: {}'.format(q.is_empty())) print('Enqueue "dog", 4 & 8.4') q.enqueue('dog') q.enqueue(4) q.enqueue(8.4) print(q.peek()) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Dequeue: {}'.format(q.dequeue())) print('Is empty: {}'.format(q.is_empty())) print('Queue size: {}'.format(q.size())) print('Show: {}'.format(q.show())) if __name__ == '__main__': main()
Revise Queue instance to q
Revise Queue instance to q
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -10,6 +10,9 @@ def is_empty(self): return self.items == [] + + def peek(self): + return self.items[-1] def enqueue(self, item): self.items.insert(0, item) @@ -25,23 +28,25 @@ def main(): - queue = Queue() + q = Queue() - print('Is empty: {}'.format(queue.is_empty())) + print('Is empty: {}'.format(q.is_empty())) print('Enqueue "dog", 4 & 8.4') - queue.enqueue('dog') - queue.enqueue(4) - queue.enqueue(8.4) - print('Is empty: {}'.format(queue.is_empty())) + q.enqueue('dog') + q.enqueue(4) + q.enqueue(8.4) + print(q.peek()) + print('Is empty: {}'.format(q.is_empty())) - print('Queue size: {}'.format(queue.size())) + print('Queue size: {}'.format(q.size())) - print('Dequeue: {}'.format(queue.dequeue())) - print('Is empty: {}'.format(queue.is_empty())) - print('Queue size: {}'.format(queue.size())) + print('Dequeue: {}'.format(q.dequeue())) + print('Is empty: {}'.format(q.is_empty())) + print('Queue size: {}'.format(q.size())) - print('Show: {}'.format(queue.show())) + print('Show: {}'.format(q.show())) + if __name__ == '__main__': main()
2916006bf7dc9a689a9ab5678d37a858d380345e
api/migrations/0002_migrate_legacy.py
api/migrations/0002_migrate_legacy.py
from django.apps import apps as global_apps from django.db import migrations from django.db.utils import OperationalError sql = ''' ''' reverse_sql = ''' ''' def forwards(app, schema_editor): models = app.all_models['api'] try: schema_editor.execute('alter table south_migrationhistory rename to legacy_south_migrationhistory;') print 'Found legacy application' for model in models: schema_editor.execute('drop table api_{0};'.format(model)) schema_editor.execute('alter table portal_{0} rename to api_{0};'.format(model)) except Exception as e: pass def backwards(app, schema_editor): models = app.all_models['api'] try: schema_editor.execute('alter table legacy_south_migrationhistory rename to south_migrationhistory;') print 'Found migrated application' for model in models: schema_editor.execute('alter table api_{0} rename to portal_{0};'.format(model)) except Exception as e: pass class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, backwards), ] dependencies = [ ('api', '0001_initial'), ]
from django.apps import apps as global_apps from django.db import migrations from django.db.utils import OperationalError from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PgSE sql = ''' ''' reverse_sql = ''' ''' def forwards(app, schema_editor): models = app.all_models['api'] if not isinstance(schema_editor, PgSE): print 'this migration is only guaranteed to work with Postgres!' return try: schema_editor.execute('alter table south_migrationhistory rename to legacy_south_migrationhistory;') print 'Found legacy application' for model in models: schema_editor.execute('drop table api_{0} cascade;'.format(model)) schema_editor.execute('alter table portal_{0} rename to api_{0};'.format(model)) schema_editor.execute('alter sequence portal_{0}_id_seq rename to api_{0}_id_seq;'.format(model)) except Exception as e: pass def backwards(app, schema_editor): models = app.all_models['api'] if not isinstance(schema_editor, PgSE): print 'this migration is only guaranteed to work with Postgres!' return try: schema_editor.execute('alter table legacy_south_migrationhistory rename to south_migrationhistory;') print 'Found migrated application' for model in models: schema_editor.execute('alter table api_{0} rename to portal_{0};'.format(model)) schema_editor.execute('alter sequence api_{0}_id_seq rename to portal_{0}_id_seq;'.format(model)) except Exception as e: pass class Migration(migrations.Migration): operations = [ migrations.RunPython(forwards, backwards), ] dependencies = [ ('api', '0001_initial'), ]
Update migration to check for Postgres as target
Update migration to check for Postgres as target
Python
bsd-2-clause
chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal,chop-dbhi/biorepo-portal
--- +++ @@ -1,6 +1,9 @@ from django.apps import apps as global_apps from django.db import migrations from django.db.utils import OperationalError + +from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PgSE + sql = ''' ''' @@ -11,22 +14,31 @@ def forwards(app, schema_editor): models = app.all_models['api'] + if not isinstance(schema_editor, PgSE): + print 'this migration is only guaranteed to work with Postgres!' + return try: schema_editor.execute('alter table south_migrationhistory rename to legacy_south_migrationhistory;') print 'Found legacy application' for model in models: - schema_editor.execute('drop table api_{0};'.format(model)) + schema_editor.execute('drop table api_{0} cascade;'.format(model)) schema_editor.execute('alter table portal_{0} rename to api_{0};'.format(model)) + schema_editor.execute('alter sequence portal_{0}_id_seq rename to api_{0}_id_seq;'.format(model)) + except Exception as e: pass def backwards(app, schema_editor): models = app.all_models['api'] + if not isinstance(schema_editor, PgSE): + print 'this migration is only guaranteed to work with Postgres!' + return try: schema_editor.execute('alter table legacy_south_migrationhistory rename to south_migrationhistory;') print 'Found migrated application' for model in models: schema_editor.execute('alter table api_{0} rename to portal_{0};'.format(model)) + schema_editor.execute('alter sequence api_{0}_id_seq rename to portal_{0}_id_seq;'.format(model)) except Exception as e: pass
f94347a734df84811b627e767a55dc99831e0076
src/models.py
src/models.py
from flask_sqlalchemy import Model from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey from sqlalchemy.orm import relationship class User(Model): __tablename__ = "user" ROLE_ADMIN = 0 ROLE_USER = 1 id = Column(Integer, primary_key=True) name = Column(Unicode(64), index=True) username = Column(Unicode(20), index=True) password_hash = Column(Unicode(120)) role = Column(Integer, default=ROLE_USER) postings = relationship("Posting", backref="user") class Posting(Model): __tablename__ = "posting" id = Column(Integer, primary_key=True) title = Column(Unicode(64), index=True) description = Column(1200) price = Column(Integer, default=100) user_id = ForeignKey("user.id", index=True)
from flask_sqlalchemy import Model from __init__ import db class User(Model): __tablename__ = "user" ROLE_ADMIN = 0 ROLE_USER = 1 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(64), index=True) username = db.Column(db.Unicode(20), index=True) password_hash = db.Column(db.Unicode(120)) role = db.Column(db.Integer, default=ROLE_USER) postings = db.relationship("Posting", backref="user") class Posting(Model): __tablename__ = "posting" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Unicode(64), index=True) description = db.Column(1200) price = db.Column(db.Integer, default=100) user_id = db.ForeignKey("user.id", index=True)
Use local database namespace instead of package.
Use local database namespace instead of package.
Python
mit
BrambleLLC/Artizanz,BrambleLLC/Artizanz,BrambleLLC/Artizanz
--- +++ @@ -1,26 +1,25 @@ from flask_sqlalchemy import Model -from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey -from sqlalchemy.orm import relationship +from __init__ import db class User(Model): __tablename__ = "user" ROLE_ADMIN = 0 ROLE_USER = 1 - id = Column(Integer, primary_key=True) - name = Column(Unicode(64), index=True) - username = Column(Unicode(20), index=True) - password_hash = Column(Unicode(120)) - role = Column(Integer, default=ROLE_USER) - postings = relationship("Posting", backref="user") + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.Unicode(64), index=True) + username = db.Column(db.Unicode(20), index=True) + password_hash = db.Column(db.Unicode(120)) + role = db.Column(db.Integer, default=ROLE_USER) + postings = db.relationship("Posting", backref="user") class Posting(Model): __tablename__ = "posting" - id = Column(Integer, primary_key=True) - title = Column(Unicode(64), index=True) - description = Column(1200) - price = Column(Integer, default=100) - user_id = ForeignKey("user.id", index=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.Unicode(64), index=True) + description = db.Column(1200) + price = db.Column(db.Integer, default=100) + user_id = db.ForeignKey("user.id", index=True)
12bb9882c1e2cc3f04b7bef30d4aaf8267793622
opps/images/tests/__init__.py
opps/images/tests/__init__.py
# -*- coding: utf-8 -*- from opps.images.tests.generate import *
# -*- coding: utf-8 -*- from opps.images.tests.generate import * from opps.images.tests.test_models import *
Add test_models on image test init
Add test_models on image test init
Python
mit
williamroot/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps
--- +++ @@ -1,2 +1,3 @@ # -*- coding: utf-8 -*- from opps.images.tests.generate import * +from opps.images.tests.test_models import *
4254dcf349e79d077b68fc8ba09cf74c0cb008e2
pyspglib/pyspglib/__init__.py
pyspglib/pyspglib/__init__.py
from spglib import get_version __version__ = "%d.%d.%d" % get_version()
from .spglib import get_version __version__ = "%d.%d.%d" % get_version()
Fix relative import for py3.
Fix relative import for py3.
Python
bsd-3-clause
atztogo/spglib,atztogo/spglib,jochym/spglib,atztogo/spglib,jochym/spglib,atztogo/spglib,jochym/spglib,jochym/spglib,atztogo/spglib
--- +++ @@ -1,3 +1,3 @@ -from spglib import get_version +from .spglib import get_version __version__ = "%d.%d.%d" % get_version()
7606689e5d83a6c3bfa71ede25e4b92978d94bd4
hdbscan/__init__.py
hdbscan/__init__.py
from .hdbscan_ import HDBSCAN, hdbscan from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
from .hdbscan_ import HDBSCAN, hdbscan from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage from .validity import validity_index
Add validity_index to default imports.
Add validity_index to default imports.
Python
bsd-3-clause
scikit-learn-contrib/hdbscan,scikit-learn-contrib/hdbscan,lmcinnes/hdbscan,lmcinnes/hdbscan
--- +++ @@ -1,2 +1,4 @@ from .hdbscan_ import HDBSCAN, hdbscan from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage +from .validity import validity_index +
decad2702eb87b750fbc55ccfad754c5ae1872d5
setup.py
setup.py
from setuptools import setup, find_packages setup( name='pythonwarrior', version='0.0.3', packages=find_packages(), scripts=['bin/pythonwarrior'], author="Richard Lee", author_email="rblee88@gmail.com", description=("Game written in Python for learning Python and AI - " "a Python port of ruby-warrior"), long_description=open('README.rst').read(), install_requires=['jinja2'], license="MIT", url="https://github.com/arbylee/python-warrior", keywords="python ruby warrior rubywarrior pythonwarrior", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha" ] )
from setuptools import setup, find_packages setup( name='pythonwarrior', version='0.0.3', packages=find_packages(), package_data={'pythonwarrior': ['templates/README']}, scripts=['bin/pythonwarrior'], author="Richard Lee", author_email="rblee88@gmail.com", description=("Game written in Python for learning Python and AI - " "a Python port of ruby-warrior"), long_description=open('README.rst').read(), install_requires=['jinja2'], license="MIT", url="https://github.com/arbylee/python-warrior", keywords="python ruby warrior rubywarrior pythonwarrior", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha" ] )
Add instructions README as package data
Add instructions README as package data
Python
mit
arbylee/python-warrior
--- +++ @@ -5,6 +5,7 @@ name='pythonwarrior', version='0.0.3', packages=find_packages(), + package_data={'pythonwarrior': ['templates/README']}, scripts=['bin/pythonwarrior'], author="Richard Lee", author_email="rblee88@gmail.com",
5ac3dab347aa3c828bd63632141959381cb08728
setup.py
setup.py
from setuptools import setup from setuptools import find_packages import versioneer # README # def readme(): with open('README.rst') as f: return f.read() setup(name='fair', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Python package to perform calculations with the FaIR simple climate model', long_description=readme(), keywords='simple climate model temperature response carbon cycle emissions forcing', url='https://github.com/OMS-NetZero/FAIR', author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen', author_email='c.j.smith1@leeds.ac.uk, richard.millar@physics.ox.ac.uk', license='Apache 2.0', packages=find_packages(exclude=['tests*','docs*']), package_data={'': ['*.csv']}, include_package_data=True, install_requires=[ 'matplotlib', 'numpy>=1.11.3', 'scipy>=0.19.0', 'pandas' ], zip_safe=False, extras_require={'docs': ['sphinx>=1.4', 'nbsphinx'], 'dev' : ['notebook', 'wheel', 'twine'], 'test': ['pytest>=4.0', 'nbval', 'pytest-cov', 'codecov']} )
from setuptools import setup from setuptools import find_packages import versioneer # README # def readme(): with open('README.rst') as f: return f.read() setup(name='fair', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Python package to perform calculations with the FaIR simple climate model', long_description=readme(), keywords='simple climate model temperature response carbon cycle emissions forcing', url='https://github.com/OMS-NetZero/FAIR', author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen', author_email='c.j.smith1@leeds.ac.uk', license='Apache 2.0', packages=find_packages(exclude=['tests*','docs*']), package_data={'': ['*.csv']}, include_package_data=True, install_requires=[ 'matplotlib', 'numpy>=1.11.3', 'scipy>=0.19.0', 'pandas' ], zip_safe=False, extras_require={'docs': ['sphinx>=1.4', 'nbsphinx'], 'dev' : ['notebook', 'wheel', 'twine'], 'test': ['pytest>=4.0', 'nbval', 'pytest-cov', 'codecov']} )
Fix author email for pypi packaging
Fix author email for pypi packaging
Python
apache-2.0
OMS-NetZero/FAIR
--- +++ @@ -15,7 +15,7 @@ keywords='simple climate model temperature response carbon cycle emissions forcing', url='https://github.com/OMS-NetZero/FAIR', author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen', - author_email='c.j.smith1@leeds.ac.uk, richard.millar@physics.ox.ac.uk', + author_email='c.j.smith1@leeds.ac.uk', license='Apache 2.0', packages=find_packages(exclude=['tests*','docs*']), package_data={'': ['*.csv']},
a4a50e2043bf49b867cc80d9b7d55333d6e0cffa
setup.py
setup.py
from setuptools import setup, find_packages setup( name = 'tentd', version = "0.0.0", author = 'James Ravenscroft', url = 'https://github.com/ravenscroftj/pytentd', description = 'An implementation of the http://tent.io server protocol', long_description = open('README.rst').read(), packages = find_packages(), install_requires = [ 'flask==0.9', 'Flask-SQLAlchemy==0.16' ], include_package_data = True, zip_safe = False, )
from setuptools import setup, find_packages setup( name = 'tentd', version = "0.0.0", author = 'James Ravenscroft', url = 'https://github.com/ravenscroftj/pytentd', description = 'An implementation of the http://tent.io server protocol', long_description = open('README.rst').read(), packages = find_packages(), install_requires = [ 'flask==0.9', 'Flask-SQLAlchemy==0.16', ], entry_points = { 'console_scripts': ['tentd = tentd:run'], }, include_package_data = True, zip_safe = False, )
Allow tentd to be run from the command line
Allow tentd to be run from the command line
Python
apache-2.0
pytent/pytentd
--- +++ @@ -13,9 +13,13 @@ packages = find_packages(), install_requires = [ 'flask==0.9', - 'Flask-SQLAlchemy==0.16' + 'Flask-SQLAlchemy==0.16', ], + entry_points = { + 'console_scripts': ['tentd = tentd:run'], + }, + include_package_data = True, zip_safe = False, )
a15fd8df979865a44f2699eb15f2825667cbcd7f
setup.py
setup.py
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.org', url='http://ckan.org/wiki/Extensions', license='mit', packages=find_packages(exclude=['tests']), namespace_packages=['ckanext', 'ckanext.qa'], include_package_data=True, zip_safe=False, install_requires=[ 'celery==2.4.2', 'kombu==2.1.3', 'kombu-sqlalchemy==1.1.0', 'SQLAlchemy>=0.6.6', 'requests==0.6.4', ], tests_require=[ 'nose', 'mock', ], entry_points=''' [paste.paster_command] qa=ckanext.qa.commands:QACommand [ckan.plugins] qa=ckanext.qa.plugin:QAPlugin [ckan.celery_task] tasks=ckanext.qa.celery_import:task_imports ''', )
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.org', url='http://ckan.org/wiki/Extensions', license='mit', packages=find_packages(exclude=['tests']), namespace_packages=['ckanext', 'ckanext.qa'], include_package_data=True, zip_safe=False, install_requires=[ 'celery==2.4.2', 'kombu==2.1.3', 'kombu-sqlalchemy==1.1.0', 'SQLAlchemy>=0.6.6', 'requests==0.14', ], tests_require=[ 'nose', 'mock', ], entry_points=''' [paste.paster_command] qa=ckanext.qa.commands:QACommand [ckan.plugins] qa=ckanext.qa.plugin:QAPlugin [ckan.celery_task] tasks=ckanext.qa.celery_import:task_imports ''', )
Use later version of requests, to match ckanext-archiver.
Use later version of requests, to match ckanext-archiver.
Python
mit
ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa
--- +++ @@ -21,7 +21,7 @@ 'kombu==2.1.3', 'kombu-sqlalchemy==1.1.0', 'SQLAlchemy>=0.6.6', - 'requests==0.6.4', + 'requests==0.14', ], tests_require=[ 'nose',
02d842623a5b17e62d1cbfc829b0023508cf7f25
setup.py
setup.py
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "team@pinaxproject.com" URL = "http://github.com/pinax/phileo" VERSION = "1.3" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=read("README.rst"), author=AUTHOR, author_email=AUTHOR_EMAIL, license="MIT", url=URL, packages=find_packages(), package_data={ "phileo": [ "templates/phileo/_like.html", "templates/phileo/_widget.html", "templates/phileo/_widget_brief.html" ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], test_suite="runtests.runtests", tests_require=[ ], zip_safe=False, )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "team@pinaxproject.com" URL = "http://github.com/pinax/phileo" VERSION = "1.3" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=read("README.rst"), author=AUTHOR, author_email=AUTHOR_EMAIL, license="MIT", url=URL, packages=find_packages(), package_data={ "phileo": [ "templates/phileo/_like.html", "templates/phileo/_widget.html", "templates/phileo/_widget_brief.html" ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Framework :: Django", ], test_suite="runtests.runtests", tests_require=[ ], zip_safe=False, )
Support both Python 2 and 3
Support both Python 2 and 3
Python
mit
rizumu/pinax-likes,jacobwegner/phileo,pinax/phileo,jacobwegner/phileo,pinax/phileo,rizumu/pinax-likes,pinax/pinax-likes
--- +++ @@ -43,6 +43,8 @@ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", "Framework :: Django", ], test_suite="runtests.runtests",
08bb3ffa6a82186557f5f7a1305b1039b7172305
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup import lib as asteval setup(name = 'asteval', version = asteval.__version__, author = 'Matthew Newville', author_email = 'newville@cars.uchicago.edu', url = 'http://github.com/newville/asteval', license = 'BSD', description = "Safe, minimalistic evaluator of python expression using ast module", package_dir = {'asteval': 'lib'}, packages = ['asteval'], )
#!/usr/bin/env python from setuptools import setup import lib as asteval setup(name = 'asteval', version = asteval.__version__, author = 'Matthew Newville', author_email = 'newville@cars.uchicago.edu', url = 'http://github.com/newville/asteval', license = 'BSD', description = "Safe, minimalistic evaluator of python expression using ast module", package_dir = {'asteval': 'lib'}, packages = ['asteval'], classifiers=[ 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
Add classifiers to show Python 3 support
Add classifiers to show Python 3 support
Python
mit
newville/asteval
--- +++ @@ -11,5 +11,18 @@ description = "Safe, minimalistic evaluator of python expression using ast module", package_dir = {'asteval': 'lib'}, packages = ['asteval'], + classifiers=[ + 'Intended Audience :: End Users/Desktop', + 'Intended Audience :: Developers', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: BSD License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + ], ) -
2bbe25ba8593569a530bbdfa7f6787395315ed4d
setup.py
setup.py
from setuptools import setup, find_packages def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#") def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)] # Don't import module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'librato_bg')) from version import VERSION setup( name='librato_bg', version=VERSION, license="BSD", install_requires=_read_requirements("requirements/base.txt"), tests_require=_read_requirements("requirements/tests.txt"), description="Background submitter for Librato events.", long_description=open('README.md').read(), author='Nyaruka Ltd', author_email='code@nyaruka.com', url='http://github.com/nyaruka/python-librato-bg', include_package_data=True, packages=find_packages(), zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
from setuptools import setup, find_packages import sys import os def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#") def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)] # Don't import module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'librato_bg')) from version import VERSION setup( name='librato_bg', version=VERSION, license="BSD", install_requires=_read_requirements("requirements/base.txt"), tests_require=_read_requirements("requirements/tests.txt"), description="Background submitter for Librato events.", long_description=open('README.md').read(), author='Nyaruka Ltd', author_email='code@nyaruka.com', url='http://github.com/nyaruka/python-librato-bg', include_package_data=True, packages=find_packages(), zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Add sys and os imports
Add sys and os imports
Python
mit
nyaruka/python-librato-bg
--- +++ @@ -1,4 +1,6 @@ from setuptools import setup, find_packages +import sys +import os def _is_requirement(line): """Returns whether the line is a valid package requirement."""
f8b52162748ccf62db881fad101e6a91ed014bd4
plugins/Hitman_Codename_47.py
plugins/Hitman_Codename_47.py
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
Add backuping config files for Hitman: Codename 47
Add backuping config files for Hitman: Codename 47
Python
mit
Pr0Ger/SGSB
--- +++ @@ -9,9 +9,11 @@ def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') + _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') + _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
4ce1742472fc636aebd176a33b5fa7a819713fe7
setup.py
setup.py
import re from setuptools import setup _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('lib/glyphConstruction.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "glyphConstruction __version__ not found" __version__ = found.group(1) setup( name='glyphConstruction', version=__version__, author='Frederik Berlaen', author_email='frederik@typemytpye.com', url='https://github.com/typemytype/GlyphConstruction', license='LICENSE.txt', description='Letter shape description language', long_description='Letter shape description language', install_requires=[], py_modules=["glyphConstruction"], package_dir={'': 'Lib'} )
import re from setuptools import setup _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('Lib/glyphConstruction.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "glyphConstruction __version__ not found" __version__ = found.group(1) setup( name='glyphConstruction', version=__version__, author='Frederik Berlaen', author_email='frederik@typemytpye.com', url='https://github.com/typemytype/GlyphConstruction', license='LICENSE.txt', description='Letter shape description language', long_description='Letter shape description language', install_requires=[], py_modules=["glyphConstruction"], package_dir={'': 'Lib'} )
Fix case of file path
Fix case of file path It is impossible to build/install this on Linux with this path broken because all file systems are case sensitive. I'll assume this only slipped by because it was only ever tested on Windows or another case insensitive filesystem.
Python
mit
typemytype/GlyphConstruction,moyogo/glyphconstruction,moyogo/glyphconstruction,typemytype/GlyphConstruction
--- +++ @@ -3,7 +3,7 @@ _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file -with open('lib/glyphConstruction.py', "r") as settings: +with open('Lib/glyphConstruction.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "glyphConstruction __version__ not found"
85542282162158e9e3d0ff339ee67d7809fb2a3c
src/models.py
src/models.py
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_website_table(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True)
from sqlalchemy import create_engine, Column, Float, Integer, String from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL import settings DeclarativeBase = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(URL(**settings.DATABASE)) def create_db_tables(engine): """""" DeclarativeBase.metadata.create_all(engine) class Websites(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True) class WebsitesContent(DeclarativeBase): """Sqlalchemy websites model""" __tablename__ = "websites_content" id = Column(Integer, primary_key=True) link = Column('link', String, nullable=False) words = Column('words', ARRAY(String), nullable=False)
Add model for storing words.
Add model for storing words.
Python
mit
piatra/ssl-project
--- +++ @@ -1,4 +1,5 @@ from sqlalchemy import create_engine, Column, Float, Integer, String +from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import URL @@ -13,9 +14,11 @@ """ return create_engine(URL(**settings.DATABASE)) -def create_website_table(engine): + +def create_db_tables(engine): """""" DeclarativeBase.metadata.create_all(engine) + class Websites(DeclarativeBase): """Sqlalchemy websites model""" @@ -25,3 +28,12 @@ link = Column('link', String, nullable=True) male_ratio = Column('male_ratio', Float, nullable=True) female_ratio = Column('female_ratio', Float, nullable=True) + + +class WebsitesContent(DeclarativeBase): + """Sqlalchemy websites model""" + __tablename__ = "websites_content" + + id = Column(Integer, primary_key=True) + link = Column('link', String, nullable=False) + words = Column('words', ARRAY(String), nullable=False)