commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
8dc822cf3577663cf817cd5d1ab537df3605752c | art_archive_api/models.py | art_archive_api/models.py | from application import db
class Artist(db.Model):
__tablename__ = 'artists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
birth_year = db.Column(db.Integer)
death_year = db.Column(db.Integer)
country = db.Column(db.String(45))
genre = db.Column(db.String(45))
images = db.relationship(
'Image',
backref='artist',
)
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer, primary_key=True)
image_url = db.Column(db.String(255))
title = db.Column(db.String(255))
year = db.Column(db.Integer)
artist_id = db.Column(
db.Integer,
db.ForeignKey('artists.id')
)
description = db.Column(db.String(255))
| from application import db
class Artist(db.Model):
__tablename__ = 'artists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
birth_year = db.Column(db.Integer)
death_year = db.Column(db.Integer)
country = db.Column(db.String(45))
genre = db.Column(db.String(45))
images = db.relationship(
'Image',
backref='artist',
)
def serialize(self):
return {
'id': self.id,
'name': self.name,
'birth_year': self.birth_year,
'death_year': self.death_year,
'country': self.country,
'genre': self.genre,
}
def serialize_with_images(self):
return {
'id': self.id,
'name': self.name,
'birth_year': self.birth_year,
'death_year': self.death_year,
'country': self.country,
'genre': self.genre,
"images" : [image.serialize() for image in self.images]
}
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer, primary_key=True)
image_url = db.Column(db.String(255))
title = db.Column(db.String(255))
year = db.Column(db.Integer)
artist_id = db.Column(
db.Integer,
db.ForeignKey('artists.id')
)
description = db.Column(db.String(255))
def serialize(self):
return {
'id': self.id,
'image_url': self.image_url,
'title': self.title,
'year': self.year,
'description': self.description,
} | UPDATE serialize method for json data | UPDATE serialize method for json data
| Python | mit | EunJung-Seo/art_archive |
26672e83ab1bd1a932d275dfd244fe20749e3b1e | tripleo_common/utils/safe_import.py | tripleo_common/utils/safe_import.py | # Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
from eventlet.green import subprocess
# Due to an eventlet issue subprocess is not being correctly patched
# on git module so it has to be done manually
git = eventlet.import_patched('git', ('subprocess', subprocess))
Repo = git.Repo
# git.refs is lazy loaded when there's a new commit, this needs to be
# patched as well.
eventlet.import_patched('git.refs')
| # Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from eventlet.green import subprocess
import eventlet.patcher as patcher
# Due to an eventlet issue subprocess is not being correctly patched
# on git.refs
patcher.inject('git.refs', None, ('subprocess', subprocess), )
# this has to be loaded after the inject.
import git # noqa: E402
Repo = git.Repo
| Make gitpython and eventlet work with eventlet 0.25.1 | Make gitpython and eventlet work with eventlet 0.25.1
Version 0.25 is having a bad interaction with python git.
that is due to the way that eventlet unloads some modules now.
Changed to use the inject method that supports what we need intead
of the imported_patched that was having the problem
Change-Id: I79894d4f711c64f536593fffcb6959df97c38838
Closes-bug: #1845181
| Python | apache-2.0 | openstack/tripleo-common,openstack/tripleo-common |
4ae3b77847eeefd07d83f863c6ec71d7fdf750cb | turbustat/tests/test_rfft_to_fft.py | turbustat/tests/test_rfft_to_fft.py |
from turbustat.statistics.rfft_to_fft import rfft_to_fft
from ._testing_data import dataset1
import numpy as np
import numpy.testing as npt
from unittest import TestCase
class testRFFT(TestCase):
"""docstring for testRFFT"""
def __init__(self):
self.dataset1 = dataset1
self.comp_rfft = rfft_to_fft(self.dataset1)
def rfft_to_rfft(self):
test_rfft = np.abs(np.fft.rfftn(self.dataset1))
shape2 = test_rfft.shape[-1]
npt.assert_allclose(test_rfft, self.comp_rfft[:, :, :shape2+1])
def fft_to_rfft(self):
test_fft = np.abs(np.fft.fftn(self.dataset1))
npt.assert_allclose(test_fft, self.comp_rfft)
|
import pytest
from ..statistics.rfft_to_fft import rfft_to_fft
from ._testing_data import dataset1
import numpy as np
import numpy.testing as npt
def test_rfft_to_rfft():
comp_rfft = rfft_to_fft(dataset1['moment0'][0])
test_rfft = np.abs(np.fft.rfftn(dataset1['moment0'][0]))
shape2 = test_rfft.shape[-1]
npt.assert_allclose(test_rfft, comp_rfft[:, :shape2])
def test_fft_to_rfft():
comp_rfft = rfft_to_fft(dataset1['moment0'][0])
test_fft = np.abs(np.fft.fftn(dataset1['moment0'][0]))
npt.assert_allclose(test_fft, comp_rfft)
| Fix and update the rfft tests | Fix and update the rfft tests
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat |
2d36b6fee7905e32aded8da7ffba68a5ec3c5d34 | dwitter/user/forms.py | dwitter/user/forms.py | from django.contrib.auth import get_user_model
from django.forms import ModelForm
class UserSettingsForm(ModelForm):
class Meta:
model = get_user_model()
fields = ('first_name',
'last_name',
'email',)
| from django.contrib.auth import get_user_model
from django.forms import ModelForm
class UserSettingsForm(ModelForm):
class Meta:
model = get_user_model()
fields = ('email',)
| Remove first_name and last_name from user settings | Remove first_name and last_name from user settings
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter |
7d9265cd3cb29606e37b296dde5af07099098228 | axes/tests/test_checks.py | axes/tests/test_checks.py | from django.core.checks import run_checks, Error
from django.test import override_settings
from axes.checks import Messages, Hints, Codes
from axes.conf import settings
from axes.tests.base import AxesTestCase
@override_settings(AXES_HANDLER='axes.handlers.cache.AxesCacheHandler')
class CacheCheckTestCase(AxesTestCase):
@override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}})
def test_cache_check(self):
errors = run_checks()
self.assertEqual([], errors)
@override_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}})
def test_cache_check_errors(self):
errors = run_checks()
error = Error(
msg=Messages.CACHE_INVALID,
hint=Hints.CACHE_INVALID,
obj=settings.CACHES,
id=Codes.CACHE_INVALID,
)
self.assertEqual([error], errors)
| from django.core.checks import run_checks, Error
from django.test import override_settings
from axes.checks import Messages, Hints, Codes
from axes.conf import settings
from axes.tests.base import AxesTestCase
class CacheCheckTestCase(AxesTestCase):
@override_settings(
AXES_HANDLER='axes.handlers.cache.AxesCacheHandler',
CACHES={'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}},
)
def test_cache_check(self):
errors = run_checks()
self.assertEqual([], errors)
@override_settings(
AXES_HANDLER='axes.handlers.cache.AxesCacheHandler',
CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}},
)
def test_cache_check_errors(self):
errors = run_checks()
error = Error(
msg=Messages.CACHE_INVALID,
hint=Hints.CACHE_INVALID,
obj=settings.CACHES,
id=Codes.CACHE_INVALID,
)
self.assertEqual([error], errors)
@override_settings(
AXES_HANDLER='axes.handlers.database.AxesDatabaseHandler',
CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}},
)
def test_cache_check_does_not_produce_check_errors_with_database_handler(self):
errors = run_checks()
self.assertEqual([], errors)
| Add check test for missing case branch | Add check test for missing case branch
Signed-off-by: Aleksi Häkli <[email protected]>
| Python | mit | jazzband/django-axes,django-pci/django-axes |
41368a5d45aa9568d8495a98399cb92398eeaa32 | eva/models/pixelcnn.py | eva/models/pixelcnn.py | from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def PixelCNN(input_shape, filters, blocks, softmax=False, build=True):
input_map = Input(shape=input_shape)
model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map)
model = PReLU()(model)
model = ResidualBlockList(model, filters, blocks)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(1, 1, 1)(model)
if not softmax:
model = Activation('sigmoid')(model)
else:
raise NotImplementedError()
if build:
model = Model(input=input_map, output=model)
model.compile(loss='binary_crossentropy',
optimizer=Nadam(),
metrics=['accuracy', 'fbeta_score', 'matthews_correlation'])
return model
| from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def PixelCNN(input_shape, filters, blocks, softmax=False, build=True):
input_map = Input(shape=input_shape)
model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map)
model = PReLU()(model)
model = ResidualBlockList(model, filters, blocks)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(1, 1, 1)(model)
if not softmax:
model = Activation('sigmoid')(model)
else:
raise NotImplementedError()
if build:
model = Model(input=input_map, output=model)
model.compile(loss='binary_crossentropy',
optimizer=Nadam(clipnorm=1., clipvalue=1.),
metrics=['accuracy', 'fbeta_score', 'matthews_correlation'])
return model
| Add gradient clipping value and norm | Add gradient clipping value and norm
| Python | apache-2.0 | israelg99/eva |
e8dc3b169d308e644efdebc25bcdc485aeb909ac | engines/empy_engine.py | engines/empy_engine.py | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, basedir=None, **kwargs):
"""Initialize Subsystem plus a possible base directory."""
em.Subsystem.__init__(self, **kwargs)
self.basedir = basedir
def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs)
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, dirname=None, **kwargs):
"""Initialize empy template."""
super(EmpyEngine, self).__init__(**kwargs)
if dirname is not None:
# FIXME: This is a really bad idea, as it works like a global.
# Blame EmPy.
em.theSubsystem = SubsystemWrapper(basedir=dirname)
self.template = template
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
return em.expand(self.template, mapping)
| #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, basedir=None, **kwargs):
"""Initialize Subsystem plus a possible base directory."""
em.Subsystem.__init__(self, **kwargs)
self.basedir = basedir
def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs)
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, dirname=None, **kwargs):
"""Initialize empy template."""
super(EmpyEngine, self).__init__(**kwargs)
if dirname is not None:
# FIXME: This is a really bad idea, as it works like a global.
# Blame EmPy.
em.theSubsystem = SubsystemWrapper(basedir=dirname)
self.output = StringIO()
self.interpreter = em.Interpreter(output=self.output)
self.template = template
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
self.output.truncate(0)
self.interpreter.string(self.template, locals=mapping)
return self.output.getvalue()
| Change empy engine to use Interpreter class. | Change empy engine to use Interpreter class.
| Python | mit | blubberdiblub/eztemplate |
e3a07917ddda0bd9eb3254145342a3938c8e24a0 | cptm/experiment_calculate_perspective_jsd.py | cptm/experiment_calculate_perspective_jsd.py | import logging
import argparse
import numpy as np
from utils.experiment import load_config, get_corpus
from utils.controversialissues import perspective_jsd_matrix
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
config = load_config(args.json)
corpus = get_corpus(config)
nTopics = config.get('nTopics')
perspectives = [p.name for p in corpus.perspectives]
perspective_jsd = perspective_jsd_matrix(config, nTopics, perspectives)
print perspective_jsd
print perspective_jsd.sum(axis=(2, 1))
np.save(config.get('outDir').format('perspective_jsd.npy'), perspective_jsd)
| import logging
import argparse
import numpy as np
from utils.experiment import load_config, get_corpus
from utils.controversialissues import perspective_jsd_matrix
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
config = load_config(args.json)
corpus = get_corpus(config)
nTopics = config.get('nTopics')
perspectives = [p.name for p in corpus.perspectives]
perspective_jsd = perspective_jsd_matrix(config, nTopics, perspectives)
print perspective_jsd
print perspective_jsd.sum(axis=(2, 1))
np.save(config.get('outDir').format('perspective_jsd_{}.npy'.format(nTopics)),
perspective_jsd)
| Add nTopics to persp. jsd calculation file name | Add nTopics to persp. jsd calculation file name
| Python | apache-2.0 | NLeSC/cptm,NLeSC/cptm |
85d1fa8a390e715f38ddf9f680acb4337a469a66 | cura/Settings/QualityAndUserProfilesModel.py | cura/Settings/QualityAndUserProfilesModel.py | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Settings.ContainerRegistry import ContainerRegistry
from cura.QualityManager import QualityManager
from cura.Settings.ProfilesModel import ProfilesModel
## QML Model for listing the current list of valid quality and quality changes profiles.
#
class QualityAndUserProfilesModel(ProfilesModel):
def __init__(self, parent = None):
super().__init__(parent)
## Fetch the list of containers to display.
#
# See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers().
def _fetchInstanceContainers(self):
# Fetch the list of qualities
quality_list = super()._fetchInstanceContainers()
# Fetch the list of quality changes.
quality_manager = QualityManager.getInstance()
application = Application.getInstance()
machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom())
if machine_definition.getMetaDataEntry("has_machine_quality"):
definition_id = machine_definition.getId()
else:
definition_id = "fdmprinter"
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
return quality_list + quality_changes_list
| # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Settings.ContainerRegistry import ContainerRegistry
from cura.QualityManager import QualityManager
from cura.Settings.ProfilesModel import ProfilesModel
## QML Model for listing the current list of valid quality and quality changes profiles.
#
class QualityAndUserProfilesModel(ProfilesModel):
def __init__(self, parent = None):
super().__init__(parent)
## Fetch the list of containers to display.
#
# See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers().
def _fetchInstanceContainers(self):
global_container_stack = Application.getInstance().getGlobalContainerStack()
if not global_container_stack:
return []
# Fetch the list of qualities
quality_list = super()._fetchInstanceContainers()
# Fetch the list of quality changes.
quality_manager = QualityManager.getInstance()
machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom())
if machine_definition.getMetaDataEntry("has_machine_quality"):
definition_id = machine_definition.getId()
else:
definition_id = "fdmprinter"
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
return quality_list + quality_changes_list
| Fix error on profiles page when there is no active machine | Fix error on profiles page when there is no active machine
| Python | agpl-3.0 | hmflash/Cura,Curahelper/Cura,Curahelper/Cura,fieldOfView/Cura,ynotstartups/Wanhao,hmflash/Cura,ynotstartups/Wanhao,fieldOfView/Cura |
5b819746a7cc768a461320c2e5de506bb477a641 | gitfs/mount.py | gitfs/mount.py | import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from router import Router
from views import IndexView, CurrentView, HistoryIndexView, HistoryView
mount_path = '/tmp/gitfs/mnt'
router = Router(remote_url='/home/zalman/dev/presslabs/test-repo.git',
repos_path='/tmp/gitfs/repos/',
mount_path=mount_path)
# TODO: replace regex with the strict one for the Historyview
# -> r'^/history/(?<date>(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))/',
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})', HistoryView)
router.register(r'^/history', HistoryIndexView)
router.register(r'^/current', CurrentView)
router.register(r'^/', IndexView)
from fuse import FUSE
FUSE(router, mount_path, foreground=True, nonempty=True)
| import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from router import Router
from views import IndexView, CurrentView, HistoryIndexView, HistoryView
mount_path = '/tmp/gitfs/mnt'
router = Router(remote_url='/home/zalman/dev/presslabs/test-repo.git',
repos_path='/tmp/gitfs/repos/',
mount_path=mount_path)
# TODO: replace regex with the strict one for the Historyview
# -> r'^/history/(?<date>(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))/',
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})/(?P<time>\d{2}:\d{2}:\d{2})-(?P<commit_sha1>[0-9a-f]{10})', HistoryView)
router.register(r'^/history/(?P<date>\d{4}-\d{1,2}-\d{1,2})', HistoryIndexView)
router.register(r'^/history', HistoryIndexView)
router.register(r'^/current', CurrentView)
router.register(r'^/', IndexView)
from fuse import FUSE
FUSE(router, mount_path, foreground=True, nonempty=True)
| Add regex for timestamp and sha. | Add regex for timestamp and sha.
| Python | apache-2.0 | ksmaheshkumar/gitfs,PressLabs/gitfs,bussiere/gitfs,rowhit/gitfs,PressLabs/gitfs |
5d7806179d455073e020bdc6e6d0e7492f4e1d9e | test/unit/Algorithms/OrdinaryPercolationTest.py | test/unit/Algorithms/OrdinaryPercolationTest.py | import OpenPNM as op
import scipy as sp
mgr = op.Base.Workspace()
mgr.loglevel = 60
class OrdinaryPercolationTest:
def setup_test(self):
self.net = op.Network.Cubic(shape=[5, 5, 5])
self.geo = op.Geometry.Toray090(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
self.phase = op.Phases.Water(network=self.net)
self.phys = op.Physics.Standard(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
self.OP = op.Algorithms.OrdinaryPercolation(network=self.net,
invading_phase=self.phase)
Ps = self.net.pores(labels=['bottom_boundary'])
self.OP.run(inlets=Ps)
self.OP.return_results(Pc=7000)
lpf = self.OP.evaluate_late_pore_filling(Pc=8000)
assert sp.size(lpf) == self.net.Np
| import OpenPNM as op
import scipy as sp
mgr = op.Base.Workspace()
mgr.loglevel = 60
class OrdinaryPercolationTest:
def setup_class(self):
self.net = op.Network.Cubic(shape=[5, 5, 5])
self.geo = op.Geometry.Toray090(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
self.phase = op.Phases.Water(network=self.net)
self.phys = op.Physics.Standard(network=self.net,
phase=self.phase,
pores=self.net.Ps,
throats=self.net.Ts)
self.OP1 = op.Algorithms.OrdinaryPercolation(network=self.net,
invading_phase=self.phase)
Ps = self.net.pores(labels=['bottom'])
self.OP1.run(inlets=Ps)
self.OP1.return_results(Pc=7000)
lpf = self.OP1.evaluate_late_pore_filling(Pc=8000)
assert sp.size(lpf) == self.net.Np
def test_site_percolation(self):
self.OP2 = op.Algorithms.OrdinaryPercolation(network=self.net,
invading_phase=self.phase,
percolation_type='site')
Ps = self.net.pores(labels=['bottom'])
self.OP2.run(inlets=Ps)
self.OP2.return_results(Pc=7000)
lpf = self.OP2.evaluate_late_pore_filling(Pc=8000)
assert sp.size(lpf) == self.net.Np
| Put a test on site percolation - probably needs some better tests on percolation thresholds maybe | Put a test on site percolation - probably needs some better tests on percolation thresholds maybe
| Python | mit | TomTranter/OpenPNM,PMEAL/OpenPNM |
b722fe0d5b84eeb5c9e7279679826ff5097bfd91 | contentdensity/textifai/urls.py | contentdensity/textifai/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^textinput', views.textinput, name='textinput'),
url(r'^featureoutput', views.featureoutput, name='featureoutput'),
url(r'^account', views.account, name='account'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^textinput', views.textinput, name='textinput'),
url(r'^featureoutput', views.featureoutput, name='featureoutput'),
url(r'^account', views.account, name='account'),
url(r'^general-insights$', views.general_insights, name='general-insights'),
]
| Add URL mapping for general-insights page | Add URL mapping for general-insights page
| Python | mit | CS326-important/space-deer,CS326-important/space-deer |
a85beb35d7296b0a8bd5a385b44fa13fb9f178ed | imgur-clean.py | imgur-clean.py | #!/usr/bin/env python3
"""
"imgur-album-downloader" is great, but it seems to download
albums twice, and appends their stupid ID to the end.
This script fixes both.
"""
import hashlib
import re
import os
import sys
IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)')
def get_hash(fn):
with open(fn, 'rb') as fh:
hashsum = hashlib.md5(fh.read()).digest()
return hashsum
if __name__ == '__main__':
if len(sys.argv) >= 2:
os.chdir(sys.argv[1])
sums = {}
for fn in os.listdir('.'):
match = IMGUR_FILENAME_REGEX.match(fn)
if match is None:
continue
new_fn = f'{match.group(1)}.{match.group(2)}'
if fn == new_fn:
continue
print(f"Renaming '{fn}' to '{new_fn}'")
os.rename(fn, new_fn)
hashsum = get_hash(new_fn)
files = sums.get(hashsum, [])
files.append(new_fn)
sums[hashsum] = files
for hashsum, files in sums.items():
if len(files) > 1:
files_quoted = [f"'{x}'" for x in files]
print(f"Found duplicates: {', '.join(files_quoted)}")
files.sort()
for fn in files[1:]:
os.remove(fn)
| #!/usr/bin/env python3
"""
"imgur-album-downloader" is great, but it seems to download
albums twice, and appends their stupid ID to the end.
This script fixes both.
"""
import re
import os
import sys
IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)')
if __name__ == '__main__':
if len(sys.argv) >= 2:
os.chdir(sys.argv[1])
ids = {}
for fn in os.listdir('.'):
match = IMGUR_FILENAME_REGEX.match(fn)
if match is None:
continue
new_fn = f'{match[1]}.{match[3]}'
if fn == new_fn:
continue
print(f"Renaming '{fn}' to '{new_fn}'")
os.rename(fn, new_fn)
id = match[2]
files = ids.get(id, [])
files.append(new_fn)
ids[id] = files
for _, files in ids.items():
if len(files) > 1:
files_quoted = ', '.join(f"'{fn}'" for fn in files)
print(f"Found duplicates: {files_quoted}")
files.sort()
for fn in files[1:]:
print(f"Removing {fn}")
os.remove(fn)
| Remove imgur duplicates based on ID. | Remove imgur duplicates based on ID.
| Python | mit | ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts |
6144ac22f7b07cb1bd322bb05391a530f128768f | tests/integration/fileserver/fileclient_test.py | tests/integration/fileserver/fileclient_test.py | # -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <[email protected]>`
'''
# Import Salt Testing libs
from salttesting.helpers import (ensure_in_syspath, destructiveTest)
from salttesting.mock import MagicMock, patch
ensure_in_syspath('../')
# Import salt libs
import integration
from salt import fileclient
# Import Python libs
import os
class FileClientTest(integration.ModuleCase):
def setUp(self):
self.file_client = fileclient.Client(self.master_opts)
def test_file_list_emptydirs(self):
'''
Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
'''
with self.assertRaises(NotImplementedError):
self.file_client.file_list_emptydirs()
def test_get_file(self):
'''
Ensure that the fileclient class won't allow a direct call to get_file()
'''
with self.assertRaises(NotImplementedError):
self.file_client.get_file(None)
def test_get_file_client(self):
with patch.dict(self.minion_opts, {'file_client': 'remote'}):
with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
ret = fileclient.get_file_client(self.minion_opts)
self.assertEqual('remote_client', ret)
if __name__ == '__main__':
from integration import run_tests
run_tests(FileClientTest)
| # -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <[email protected]>`
'''
# Import Salt Testing libs
from salttesting.unit import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../')
# Import salt libs
import integration
from salt import fileclient
@skipIf(NO_MOCK, NO_MOCK_REASON)
class FileClientTest(integration.ModuleCase):
def setUp(self):
self.file_client = fileclient.Client(self.master_opts)
def test_file_list_emptydirs(self):
'''
Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
'''
with self.assertRaises(NotImplementedError):
self.file_client.file_list_emptydirs()
def test_get_file(self):
'''
Ensure that the fileclient class won't allow a direct call to get_file()
'''
with self.assertRaises(NotImplementedError):
self.file_client.get_file(None)
def test_get_file_client(self):
with patch.dict(self.minion_opts, {'file_client': 'remote'}):
with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
ret = fileclient.get_file_client(self.minion_opts)
self.assertEqual('remote_client', ret)
if __name__ == '__main__':
from integration import run_tests
run_tests(FileClientTest)
| Remove unused imports & Skip if no mock available | Remove unused imports & Skip if no mock available
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
98bdb678a9092c5c19bc2b379cca74a2ed33c457 | libqtile/layout/subverttile.py | libqtile/layout/subverttile.py | from base import SubLayout, Rect
from sublayouts import HorizontalStack
from subtile import SubTile
class SubVertTile(SubTile):
arrangements = ["top", "bottom"]
def _init_sublayouts(self):
ratio = self.ratio
expand = self.expand
master_windows = self.master_windows
arrangement = self.arrangement
class MasterWindows(HorizontalStack):
def filter(self, client):
return self.index_of(client) < master_windows
def request_rectangle(self, r, windows):
return (r, Rect())
class SlaveWindows(HorizontalStack):
def filter(self, client):
return self.index_of(client) >= master_windows
def request_rectangle(self, r, windows):
if self.autohide and not windows:
return (Rect(), r)
else:
if arrangement == "top":
rmaster, rslave = r.split_horizontal(ratio=ratio)
else:
rslave, rmaster = r.split_horizontal(ratio=(1-ratio))
return (rslave, rmaster)
self.sublayouts.append(SlaveWindows(self.clientStack,
self.theme,
parent=self,
autohide=self.expand
)
)
self.sublayouts.append(MasterWindows(self.clientStack,
self.theme,
parent=self,
autohide=self.expand
)
)
| from base import SubLayout, Rect
from sublayouts import HorizontalStack
from subtile import SubTile
class SubVertTile(SubTile):
arrangements = ["top", "bottom"]
def _init_sublayouts(self):
class MasterWindows(HorizontalStack):
def filter(self, client):
return self.index_of(client) < self.parent.master_windows
def request_rectangle(self, r, windows):
return (r, Rect())
class SlaveWindows(HorizontalStack):
def filter(self, client):
return self.index_of(client) >= self.parent.master_windows
def request_rectangle(self, r, windows):
if self.autohide and not windows:
return (Rect(), r)
else:
if self.parent.arrangement == "top":
rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio)
else:
rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio))
return (rslave, rmaster)
self.sublayouts.append(SlaveWindows(self.clientStack,
self.theme,
parent=self,
autohide=self.expand
)
)
self.sublayouts.append(MasterWindows(self.clientStack,
self.theme,
parent=self,
autohide=self.expand
)
)
| Refactor SubVertTile - make sublayout use the parents' variables | Refactor SubVertTile - make sublayout use the parents' variables
| Python | mit | rxcomm/qtile,de-vri-es/qtile,EndPointCorp/qtile,zordsdavini/qtile,bavardage/qtile,nxnfufunezn/qtile,encukou/qtile,andrewyoung1991/qtile,ramnes/qtile,himaaaatti/qtile,de-vri-es/qtile,frostidaho/qtile,encukou/qtile,andrewyoung1991/qtile,w1ndy/qtile,frostidaho/qtile,nxnfufunezn/qtile,StephenBarnes/qtile,farebord/qtile,kopchik/qtile,rxcomm/qtile,jdowner/qtile,flacjacket/qtile,w1ndy/qtile,cortesi/qtile,aniruddhkanojia/qtile,qtile/qtile,himaaaatti/qtile,ramnes/qtile,xplv/qtile,flacjacket/qtile,soulchainer/qtile,kynikos/qtile,dequis/qtile,cortesi/qtile,jdowner/qtile,kseistrup/qtile,kiniou/qtile,apinsard/qtile,kiniou/qtile,kynikos/qtile,qtile/qtile,kopchik/qtile,kseistrup/qtile,tych0/qtile,tych0/qtile,apinsard/qtile,xplv/qtile,zordsdavini/qtile,soulchainer/qtile,dequis/qtile,farebord/qtile,aniruddhkanojia/qtile,EndPointCorp/qtile,StephenBarnes/qtile |
224abf5e0e8d5e7bad7a86c622b711e997e8ae10 | pyconcz_2016/team/models.py | pyconcz_2016/team/models.py | from django.db import models
class Organizer(models.Model):
full_name = models.CharField(max_length=200)
email = models.EmailField(
default='', blank=True,
help_text="This is private")
twitter = models.CharField(max_length=255, blank=True)
github = models.CharField(max_length=255, blank=True)
photo = models.ImageField(upload_to='team/pyconcz2016/')
published = models.BooleanField(default=False)
| from django.db import models
class Organizer(models.Model):
full_name = models.CharField(max_length=200)
email = models.EmailField(
default='', blank=True,
help_text="This is private")
twitter = models.CharField(max_length=255, blank=True)
github = models.CharField(max_length=255, blank=True)
photo = models.ImageField(upload_to='team/pyconcz2016/')
published = models.BooleanField(default=False)
def __str__(self):
return self.full_name
| Add string representation of organizer object | Add string representation of organizer object
| Python | mit | pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016 |
260291135a43e7bf6e34a600f4291da9ab5d870e | tendrl/commons/flows/import_cluster/__init__.py | tendrl/commons/flows/import_cluster/__init__.py | import json
import etcd
from tendrl.commons import flows
from tendrl.commons.flows.exceptions import FlowExecutionFailedError
class ImportCluster(flows.BaseFlow):
def __init__(self, *args, **kwargs):
super(ImportCluster, self).__init__(*args, **kwargs)
def run(self):
integration_id = self.parameters['TendrlContext.integration_id']
if "Node[]" not in self.parameters:
try:
integration_id_index_key = \
"indexes/tags/tendrl/integration/%s" % integration_id
_node_ids = NS._int.client.read(
integration_id_index_key).value
self.parameters["Node[]"] = json.loads(_node_ids)
except etcd.EtcdKeyNotFound:
raise FlowExecutionFailedError("Cluster with "
"integration_id "
"(%s) not found, cannot "
"import" % integration_id)
super(ImportCluster, self).run()
| import json
import etcd
from tendrl.commons import flows
from tendrl.commons.flows.exceptions import FlowExecutionFailedError
class ImportCluster(flows.BaseFlow):
def __init__(self, *args, **kwargs):
super(ImportCluster, self).__init__(*args, **kwargs)
def run(self):
integration_id = self.parameters['TendrlContext.integration_id']
if "Node[]" not in self.parameters:
try:
integration_id_index_key = \
"indexes/tags/tendrl/integration/%s" % integration_id
_node_ids = NS._int.client.read(
integration_id_index_key).value
self.parameters["Node[]"] = json.loads(_node_ids)
except etcd.EtcdKeyNotFound:
raise FlowExecutionFailedError("Cluster with "
"integration_id "
"(%s) not found, cannot "
"import" % integration_id)
else:
# TODO(shtripat) ceph-installer is auto detected and
# provisioner/$integration_id
# tag is set , below is not required for ceph
current_tags = list(NS.node_context.tags)
new_tags = ['provisioner/%s' % integration_id]
new_tags += current_tags
NS.node_context.tags = list(set(new_tags))
if NS.node_context.tags != current_tags:
NS.node_context.save()
_cluster = NS.tendrl.objects.Cluster(integration_id=NS.tendrl_context.integration_id).load()
_cluster.enable_volume_profiling = self.parameters['Cluster.enable_volume_profiling']
_cluster.save()
super(ImportCluster, self).run()
| Fix wongly tagged provisioner node | Fix wongly tagged provisioner node
tendrl-bug-id: Tendrl/commons/issues#698 | Python | lgpl-2.1 | Tendrl/commons,r0h4n/commons |
9a6b06d4a69bf5a7fb59d93000dc2aba02035957 | tests/test_helpers.py | tests/test_helpers.py | import unittest
from contextlib import redirect_stdout
from conllu import print_tree
from conllu.tree_helpers import TreeNode
from io import StringIO
class TestPrintTree(unittest.TestCase):
def test_print_empty_list(self):
result = self._capture_print(print_tree, [])
self.assertEqual(result, "")
def test_print_simple_treenode(self):
node = TreeNode(data={"id": "X", "deprel": "Y"}, children={})
result = self._capture_print(print_tree, node)
self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n")
def test_print_list_of_nodes(self):
node = TreeNode(data={"id": "X", "deprel": "Y"}, children={})
nodes = [node, node]
result = self._capture_print(print_tree, nodes)
self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2)
def _capture_print(self, func, args):
f = StringIO()
with redirect_stdout(f):
func(args)
return f.getvalue()
| import unittest
from conllu import print_tree
from conllu.tree_helpers import TreeNode
from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
class TestPrintTree(unittest.TestCase):
def test_print_empty_list(self):
result = self._capture_print(print_tree, [])
self.assertEqual(result, "")
def test_print_simple_treenode(self):
node = TreeNode(data={"id": "X", "deprel": "Y"}, children={})
result = self._capture_print(print_tree, node)
self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n")
def test_print_list_of_nodes(self):
node = TreeNode(data={"id": "X", "deprel": "Y"}, children={})
nodes = [node, node]
result = self._capture_print(print_tree, nodes)
self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2)
def _capture_print(self, func, args):
f = StringIO()
with redirect_stdout(f):
func(args)
return f.getvalue()
| Fix redirect_stdout not available in python2. | Fix redirect_stdout not available in python2.
| Python | mit | EmilStenstrom/conllu |
8b0302544bfb09d8abf9630db9a1dcc7e47add39 | massa/domain.py | massa/domain.py | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
)
def define_tables(metadata):
Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('note', String(140), nullable=True),
Column('date_measured', Date(), nullable=False),
)
class Db(object):
def __init__(self, engine):
self._meta = MetaData(engine)
define_tables(self._meta)
def make_tables(self):
self._meta.create_all()
def drop_tables(self):
self._meta.drop_all()
@property
def measurement(self):
return self._meta.tables['measurement']
class MeasurementService(object):
def __init__(self, table):
self._table = table
def find_all(self):
s = self._table.select()
return s.execute()
def create(self, **kwargs):
i = self._table.insert()
i.execute(**kwargs)
| # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
)
def define_tables(metadata):
Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('note', String(140), nullable=True),
Column('date_measured', Date(), nullable=False),
)
class Db(object):
def __init__(self, engine):
self._meta = MetaData(engine)
define_tables(self._meta)
def make_tables(self):
self._meta.create_all()
def drop_tables(self):
self._meta.drop_all()
@property
def measurement(self):
return self._meta.tables['measurement']
class MeasurementService(object):
def __init__(self, table):
self._table = table
def find_all(self):
s = self._table.select()
items = []
for item in s.execute():
items.append(self.make_exposable(item))
return items
def create(self, **kwargs):
i = self._table.insert()
i.execute(**kwargs)
def make_exposable(self, measurement):
return {
'id': measurement.id,
'weight': float(measurement.weight),
'code': measurement.code,
}
| Make measurements exposable before returning. | Make measurements exposable before returning. | Python | mit | jaapverloop/massa |
43e8dc72304c7647dae9323cbce73e7bc78ecf7d | src/idea/tests/smoke_tests.py | src/idea/tests/smoke_tests.py | import os
from django.utils import timezone
from django_webtest import WebTest
from exam.decorators import fixture
from exam.cases import Exam
from django.core.urlresolvers import reverse
class SmokeTest(Exam, WebTest):
csrf_checks = False
fixtures = ['state']
@fixture
def user(self):
try:
from collab.django_factories import UserF
return UserF(username="[email protected]", person__title='')
except ImportError:
from django.contrib.auth.models import User
user = User()
user.username = "[email protected]"
user.first_name = 'first'
user.last_name = 'last'
user.email = '"[email protected]"'
user.password = 'pbkdf2_sha256$10000$ggAKkiHobFL8$xQzwPeHNX1vWr9uNmZ/gKbd17uLGZVM8QNcgmaIEAUs='
user.is_staff = False
user.is_active = True
user.is_superuser = False
user.last_login = timezone.now()
user.date_joined = timezone.now()
user.save()
return user
def get(self, url):
return self.app.get(url, user=self.user)
def test_idea_home(self):
page = self.get(reverse('idea:idea_list'))
self.assertEquals(200, page.status_code)
| import os
from django.utils import timezone
from django_webtest import WebTest
from exam.decorators import fixture
from exam.cases import Exam
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class SmokeTest(Exam, WebTest):
csrf_checks = False
fixtures = ['state', 'core-test-fixtures']
@fixture
def user(self):
user = User.objects.get(username="[email protected]")
return user
def get(self, url):
return self.app.get(url, user=self.user)
def test_idea_home(self):
page = self.get(reverse('idea:idea_list'))
self.assertEquals(200, page.status_code)
| Use fixtures for smoke tests | Use fixtures for smoke tests
| Python | cc0-1.0 | cfpb/idea-box,cfpb/idea-box,cfpb/idea-box |
9e7ab78fd1cea466a4811b9244b096a87d34c100 | django_assets/__init__.py | django_assets/__init__.py | # Make a couple frequently used things available right here.
from webassets.bundle import Bundle
from django_assets.env import register
__all__ = ('Bundle', 'register')
__version__ = (0, 11)
__webassets_version__ = ('0.11',)
from django_assets import filter
| # Make a couple frequently used things available right here.
from webassets.bundle import Bundle
from django_assets.env import register
__all__ = ('Bundle', 'register')
__version__ = (0, 11)
__webassets_version__ = ('>=0.11',)
from django_assets import filter
| Define webassets dependency as minimum version. | Define webassets dependency as minimum version.
Close #58.
| Python | bsd-2-clause | ridfrustum/django-assets,adamchainz/django-assets,jaddison/django-assets,mcfletch/django-assets |
76fa14f61811cd38f2c91851a648fa88f6142b15 | django_evolution/utils.py | django_evolution/utils.py | from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
print unicode(statement)
def execute_sql(cursor, sql):
"""
Execute a list of SQL statements on the provided cursor, unrolling
parameters as required
"""
for statement in sql:
if isinstance(statement, tuple):
if not statement[0].startswith('--'):
cursor.execute(*statement)
else:
if not statement.startswith('--'):
try:
cursor.execute(statement)
except:
print statement
print sql
raise Exception(statement)
| from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
print unicode(statement)
def execute_sql(cursor, sql):
"""
Execute a list of SQL statements on the provided cursor, unrolling
parameters as required
"""
for statement in sql:
if isinstance(statement, tuple):
if not statement[0].startswith('--'):
cursor.execute(*statement)
else:
if not statement.startswith('--'):
cursor.execute(statement)
| Revert a debugging change that slipped in. | Revert a debugging change that slipped in.
git-svn-id: 48f3d5eb0141859d8d7d81547b6bd7b3dde885f8@186 8655a95f-0638-0410-abc2-2f1ed958ef3d
| Python | bsd-3-clause | clones/django-evolution |
afddc5aeb2c9a28a4bf7314ee50ca8775494268a | misc/decode-mirax-stitching.py | misc/decode-mirax-stitching.py | #!/usr/bin/python
import struct, sys, os
f = open(sys.argv[1])
HEADER_OFFSET = 296
f.seek(HEADER_OFFSET)
while True:
x1 = struct.unpack("<h", f.read(2))[0]
x2 = struct.unpack("<h", f.read(2))[0]
y1 = struct.unpack("<h", f.read(2))[0]
y2 = struct.unpack("<h", f.read(2))[0]
zz = f.read(1)
print '%10s %10s %10s %10s %s' % (x1, x2, y1, y2, zz)
| #!/usr/bin/python
import struct, sys, os
f = open(sys.argv[1])
HEADER_OFFSET = 296
f.seek(HEADER_OFFSET)
while True:
x = struct.unpack("<i", f.read(4))[0]
y = struct.unpack("<i", f.read(4))[0]
zz = f.read(1)
print '%10s %10s' % (x, y)
| Update stitching script to ints again | Update stitching script to ints again
| Python | lgpl-2.1 | openslide/openslide,openslide/openslide,openslide/openslide,openslide/openslide |
621ae7f7ff7d4b81af192ded1beec193748cfd90 | rest_framework_ember/renderers.py | rest_framework_ember/renderers.py | import copy
from rest_framework import renderers
from rest_framework_ember.utils import get_resource_name
class JSONRenderer(renderers.JSONRenderer):
"""
Render a JSON response the way Ember Data wants it. Such as:
{
"company": {
"id": 1,
"name": "nGen Works",
"slug": "ngen-works",
"date_created": "2014-03-13 16:33:37"
}
}
"""
def render(self, data, accepted_media_type=None, renderer_context=None):
view = renderer_context.get('view')
resource_name = get_resource_name(view)
try:
data_copy = copy.copy(data)
content = data_copy.pop('results')
data = {resource_name : content, "meta" : data_copy}
except (TypeError, KeyError, AttributeError) as e:
data = {resource_name : data}
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
| import copy
from rest_framework import renderers
from rest_framework_ember.utils import get_resource_name
class JSONRenderer(renderers.JSONRenderer):
"""
Render a JSON response the way Ember Data wants it. Such as:
{
"company": {
"id": 1,
"name": "nGen Works",
"slug": "ngen-works",
"date_created": "2014-03-13 16:33:37"
}
}
"""
def render(self, data, accepted_media_type=None, renderer_context=None):
view = renderer_context.get('view')
resource_name = get_resource_name(view)
if resource_name == False:
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
try:
data_copy = copy.copy(data)
content = data_copy.pop('results')
data = {resource_name : content, "meta" : data_copy}
except (TypeError, KeyError, AttributeError) as e:
data = {resource_name : data}
return super(JSONRenderer, self).render(
data, accepted_media_type, renderer_context)
| Return data when ``resource_name`` == False | Return data when ``resource_name`` == False
| Python | bsd-2-clause | django-json-api/django-rest-framework-json-api,aquavitae/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,coUrbanize/rest_framework_ember,abdulhaq-e/django-rest-framework-json-api,pattisdr/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,leo-naeka/rest_framework_ember,lukaslundgren/django-rest-framework-json-api,grapo/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,kaldras/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api |
5b2451ee653873b8fb166d291954c72a165af368 | moderate/overlapping_rectangles/over_rect.py | moderate/overlapping_rectangles/over_rect.py | import sys
def over_rect(line):
line = line.rstrip()
if line:
line = line.split(',')
rect_a = [int(item) for item in line[:4]]
rect_b = [int(item) for item in line[4:]]
return (rect_a[0] <= rect_b[0] <= rect_a[2] and
(rect_a[3] <= rect_b[1] <= rect_a[1] or
rect_a[3] <= rect_b[3] <= rect_a[1])) or \
(rect_b[0] <= rect_a[0] <= rect_b[2] and
(rect_b[3] <= rect_a[1] <= rect_b[1] or
rect_b[3] <= rect_a[3] <= rect_b[1]))
if __name__ == '__main__':
with open(sys.argv[1], 'rt') as f:
for line in f:
print over_rect(line)
| import sys
def over_rect(line):
line = line.rstrip()
if line:
xula, yula, xlra, ylra, xulb, yulb, xlrb, ylrb = (int(i) for i
in line.split(','))
h_overlap = True
v_overlap = True
if xlrb < xula or xulb > xlra:
h_overlap = False
if yulb < ylra or ylrb > yula:
v_overlap = False
return h_overlap and v_overlap
if __name__ == '__main__':
with open(sys.argv[1], 'rt') as f:
for line in f:
print over_rect(line)
| Complete solution for overlapping rectangles | Complete solution for overlapping rectangles
| Python | mit | MikeDelaney/CodeEval |
2a5cc23be491fa3f42fe039b421ad436a94d59c2 | corehq/messaging/smsbackends/smsgh/views.py | corehq/messaging/smsbackends/smsgh/views.py | from corehq.apps.sms.api import incoming
from corehq.apps.sms.views import IncomingBackendView
from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend
from django.http import HttpResponse, HttpResponseBadRequest
class SMSGHIncomingView(IncomingBackendView):
urlname = 'smsgh_sms_in'
def get(self, request, api_key, *args, **kwargs):
msg = request.GET.get('msg', None)
snr = request.GET.get('snr', None)
# We don't have a place to put this right now, but leaving it here
# so we remember the parameter name in case we need it later
to = request.GET.get('to', None)
if not msg or not snr:
return HttpResponseBadRequest("ERROR: Missing msg or snr")
incoming(snr, msg, SQLSMSGHBackend.get_api_id())
return HttpResponse("")
def post(self, request, api_key, *args, **kwargs):
return self.get(request, api_key, *args, **kwargs)
| from corehq.apps.sms.api import incoming
from corehq.apps.sms.views import NewIncomingBackendView
from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend
from django.http import HttpResponse, HttpResponseBadRequest
class SMSGHIncomingView(NewIncomingBackendView):
urlname = 'smsgh_sms_in'
@property
def backend_class(self):
return SQLSMSGHBackend
def get(self, request, api_key, *args, **kwargs):
msg = request.GET.get('msg', None)
snr = request.GET.get('snr', None)
# We don't have a place to put this right now, but leaving it here
# so we remember the parameter name in case we need it later
to = request.GET.get('to', None)
if not msg or not snr:
return HttpResponseBadRequest("ERROR: Missing msg or snr")
incoming(snr, msg, SQLSMSGHBackend.get_api_id(), domain_scope=self.domain)
return HttpResponse("")
def post(self, request, api_key, *args, **kwargs):
return self.get(request, api_key, *args, **kwargs)
| Update SMSGH Backend view to be NewIncomingBackendView | Update SMSGH Backend view to be NewIncomingBackendView
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
1779970872afd457336334231bef3c8629dcd375 | gem/tests/test_profiles.py | gem/tests/test_profiles.py | from molo.core.tests.base import MoloTestCaseMixin
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class GemRegistrationViewTest(TestCase, MoloTestCaseMixin):
def setUp(self):
self.client = Client()
self.mk_main()
def test_user_info_displaying_after_registration(self):
self.user = User.objects.create_user(
username='tester',
email='[email protected]',
password='tester')
self.user.profile.gender = 'female'
self.user.profile.alias = 'useralias'
self.user.profile.save()
self.client.login(username='tester', password='tester')
response = self.client.get(reverse('edit_my_profile'))
print response
self.assertContains(response, 'useralias')
self.assertNotContains(response, '<option value="f">female</option>')
| from molo.core.tests.base import MoloTestCaseMixin
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class GemRegistrationViewTest(TestCase, MoloTestCaseMixin):
def setUp(self):
self.client = Client()
self.mk_main()
def test_user_info_displaying_after_registration(self):
self.user = User.objects.create_user(
username='tester',
email='[email protected]',
password='tester')
self.client.login(username='tester', password='tester')
response = self.client.get(reverse('edit_my_profile'))
self.assertNotContains(response, 'useralias')
self.assertContains(response, '<option value="f">female</option>')
self.user.gem_profile.gender = 'f'
self.user.profile.alias = 'useralias'
self.user.gem_profile.save()
self.user.profile.save()
response = self.client.get(reverse('edit_my_profile'))
self.assertContains(response, 'useralias')
self.assertNotContains(response, '<option value="f">female</option>')
| Update tests and fix the failing test | Update tests and fix the failing test
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem |
2880e0b8c38af68cfb17bbcc112f1a40b6a03a11 | cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py | cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py | # Copyright (c) 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Boolean, Column, MetaData, String, Table, text
def upgrade(migrate_engine):
"""Add replication info to clusters table."""
meta = MetaData()
meta.bind = migrate_engine
clusters = Table('clusters', meta, autoload=True)
replication_status = Column('replication_status', String(length=36),
default="not-capable")
active_backend_id = Column('active_backend_id', String(length=255))
frozen = Column('frozen', Boolean, nullable=False, default=False,
server_default=text('false'))
clusters.create_column(replication_status)
clusters.create_column(frozen)
clusters.create_column(active_backend_id)
| # Copyright (c) 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Boolean, Column, MetaData, String, Table
from sqlalchemy.sql import expression
def upgrade(migrate_engine):
"""Add replication info to clusters table."""
meta = MetaData()
meta.bind = migrate_engine
clusters = Table('clusters', meta, autoload=True)
replication_status = Column('replication_status', String(length=36),
default="not-capable")
active_backend_id = Column('active_backend_id', String(length=255))
frozen = Column('frozen', Boolean, nullable=False, default=False,
server_default=expression.false())
clusters.create_column(replication_status)
clusters.create_column(frozen)
clusters.create_column(active_backend_id)
| Fix cannot add a column with non-constant default | Fix cannot add a column with non-constant default
With newer versions of sqlite tests are failing
on sqlite3.OperationalError : Cannot add a column with
non-constant default. In SQL queries is boolean without
apostrophes which causes sqlite3 error. This fix is
solving this issue by replacing text('false') to
expression.false() from sqlalchemy.sql which is
working correct.
Change-Id: Ia96255a2a61994a18b21acc235931ad03a8501ea
Closes-Bug: #1773123
| Python | apache-2.0 | openstack/cinder,mahak/cinder,mahak/cinder,openstack/cinder |
7173d3cf67bfd9a3b01f42c0832ce299c090f1d6 | opendebates/tests/test_context_processors.py | opendebates/tests/test_context_processors.py | from django.core.cache import cache
from django.test import TestCase
from opendebates.context_processors import global_vars
from opendebates.models import NUMBER_OF_VOTES_CACHE_ENTRY
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, 2)
context = global_vars(None)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
| from django.test import TestCase
from mock import patch
from opendebates.context_processors import global_vars
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
with patch('opendebates.utils.cache') as mock_cache:
mock_cache.get.return_value = 2
context = global_vars(None)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
| Fix new test to work without cache | Fix new test to work without cache
| Python | apache-2.0 | ejucovy/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates |
3bddeade05ca5ddc799733baa1545aa2b8b68060 | hoomd/tune/custom_tuner.py | hoomd/tune/custom_tuner.py | from hoomd import _hoomd
from hoomd.custom import (
_CustomOperation, _InternalCustomOperation, Action)
from hoomd.operation import _Tuner
class _TunerProperty:
@property
def updater(self):
return self._action
@updater.setter
def updater(self, updater):
if isinstance(updater, Action):
self._action = updater
else:
raise ValueError(
"updater must be an instance of hoomd.custom.Action")
class CustomTuner(_CustomOperation, _TunerProperty, _Tuner):
"""Tuner wrapper for `hoomd.custom.Action` objects.
For usage see `hoomd.custom._CustomOperation`.
"""
_cpp_list_name = 'tuners'
_cpp_class_name = 'PythonTuner'
def attach(self, simulation):
self._cpp_obj = getattr(_hoomd, self._cpp_class_name)(
simulation.state._cpp_sys_def, self.trigger, self._action)
super().attach(simulation)
self._action.attach(simulation)
class _InternalCustomTuner(
_InternalCustomOperation, _TunerProperty, _Tuner):
_cpp_list_name = 'tuners'
_cpp_class_name = 'PythonTuner'
| from hoomd import _hoomd
from hoomd.operation import _Operation
from hoomd.custom import (
_CustomOperation, _InternalCustomOperation, Action)
from hoomd.operation import _Tuner
class _TunerProperty:
@property
def tuner(self):
return self._action
@tuner.setter
def tuner(self, tuner):
if isinstance(tuner, Action):
self._action = tuner
else:
raise ValueError(
"updater must be an instance of hoomd.custom.Action")
class CustomTuner(_CustomOperation, _TunerProperty, _Tuner):
"""Tuner wrapper for `hoomd.custom.Action` objects.
For usage see `hoomd.custom._CustomOperation`.
"""
_cpp_list_name = 'tuners'
_cpp_class_name = 'PythonTuner'
def attach(self, simulation):
self._cpp_obj = getattr(_hoomd, self._cpp_class_name)(
simulation.state._cpp_sys_def, self.trigger, self._action)
self._action.attach(simulation)
_Operation.attach(self, simulation)
class _InternalCustomTuner(
_InternalCustomOperation, _TunerProperty, _Tuner):
_cpp_list_name = 'tuners'
_cpp_class_name = 'PythonTuner'
def attach(self, simulation):
self._cpp_obj = getattr(_hoomd, self._cpp_class_name)(
simulation.state._cpp_sys_def, self.trigger, self._action)
self._action.attach(simulation)
_Operation.attach(self, simulation)
| Fix attaching on custom tuners | Fix attaching on custom tuners
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue |
074c83285bba8a8805bf35dec9893771220b1715 | foodsaving/users/stats.py | foodsaving/users/stats.py | from django.contrib.auth import get_user_model
from django.db.models import Count
from foodsaving.groups.models import GroupMembership
from foodsaving.webhooks.models import EmailEvent
def get_users_stats():
User = get_user_model()
active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct()
active_membership_count = GroupMembership.objects.active().count()
active_users_count = active_users.count()
fields = {
'active_count':
active_users_count,
'active_unverified_count':
active_users.filter(mail_verified=False).count(),
'active_ignored_email_count':
active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(),
'active_with_location_count':
active_users.exclude(latitude=None).exclude(longitude=None).count(),
'active_with_mobile_number_count':
active_users.exclude(mobile_number='').count(),
'active_with_description_count':
active_users.exclude(description='').count(),
'active_with_photo_count':
active_users.exclude(photo='').count(),
'active_memberships_per_active_user_avg':
active_membership_count / active_users_count,
'no_membership_count':
User.objects.annotate(groups_count=Count('groupmembership')).filter(groups_count=0, deleted=False).count(),
'deleted_count':
User.objects.filter(deleted=True).count(),
}
return fields
| from django.contrib.auth import get_user_model
from foodsaving.groups.models import GroupMembership
from foodsaving.webhooks.models import EmailEvent
def get_users_stats():
User = get_user_model()
active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct()
active_membership_count = GroupMembership.objects.active().count()
active_users_count = active_users.count()
fields = {
'active_count': active_users_count,
'active_unverified_count': active_users.filter(mail_verified=False).count(),
'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(),
'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(),
'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(),
'active_with_description_count': active_users.exclude(description='').count(),
'active_with_photo_count': active_users.exclude(photo='').count(),
'active_memberships_per_active_user_avg': active_membership_count / active_users_count,
'no_membership_count': User.objects.filter(groupmembership=None, deleted=False).count(),
'deleted_count': User.objects.filter(deleted=True).count(),
}
return fields
| Use slightly better approach to count users without groups | Use slightly better approach to count users without groups
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core |
48ab9fa0e54103a08fec54d8a4d4870dc701d918 | genes/systemd/commands.py | genes/systemd/commands.py | #!/usr/bin/env python
from subprocess import Popen
from typing import List
def systemctl(*args: List[str]):
Popen(['systemctl'] + list(args))
def start(service: str):
systemctl('start', service)
def stop(service: str):
systemctl('stop', service)
def restart(service: str):
systemctl('restart', service)
def reload(service: str):
systemctl('reload', service)
| #!/usr/bin/env python
from subprocess import Popen
from typing import Tuple
def systemctl(*args: Tuple[str, ...]) -> None:
Popen(['systemctl'] + list(args))
def disable(*services: Tuple[str, ...]) -> None:
return systemctl('disable', *services)
def enable(*services: Tuple[str, ...]) -> None:
return systemctl('enable', *services)
def start(*services: Tuple[str, ...]) -> None:
return systemctl('start', *services)
def stop(*services: Tuple[str, ...]) -> None:
return systemctl('stop', *services)
def reload(*services: Tuple[str, ...]) -> None:
return systemctl('reload', *services)
def restart(services: Tuple[str, ...]) -> None:
return systemctl('restart', *services)
| Add more functions, improve type checking | Add more functions, improve type checking
| Python | mit | hatchery/genepool,hatchery/Genepool2 |
7355a5cb7014d6494e40322736a2887369d47262 | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLogger('fedmsg')
def trigger_upload(compose_id, url, push_notifications):
upload_pool = multiprocessing.pool.ThreadPool(processes=4)
compose_meta = {'compose_id': compose_id}
fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta)
def get_args():
parser = argparse.ArgumentParser(
description="Trigger a manual upload process with the "
"specified raw.xz URL")
parser.add_argument(
"-u", "--url", type=str, help=".raw.xz URL", required=True)
parser.add_argument(
"-c", "--compose-id", type=str, help="compose id of the .raw.xz file",
required=True)
parser.add_argument(
"-p", "--push-notifications",
help="Bool to check if we need to push fedmsg notifications",
action="store_true", required=False)
args = parser.parse_args()
return args.url, args.compose_id, args.push_notifications
def main():
url, compose_id, push_notifications = get_args()
trigger_upload(url, compose_id, push_notifications)
if __name__ == '__main__':
main()
| #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLogger('fedmsg')
def trigger_upload(compose_id, url, push_notifications):
upload_pool = multiprocessing.pool.ThreadPool(processes=4)
compose_meta = {'compose_id': compose_id}
fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta,
push_notifications=push_notifications)
def get_args():
parser = argparse.ArgumentParser(
description="Trigger a manual upload process with the "
"specified raw.xz URL")
parser.add_argument(
"-u", "--url", type=str, help=".raw.xz URL", required=True)
parser.add_argument(
"-c", "--compose-id", type=str, help="compose id of the .raw.xz file",
required=True)
parser.add_argument(
"-p", "--push-notifications",
help="Bool to check if we need to push fedmsg notifications",
action="store_true", required=False)
args = parser.parse_args()
return args.url, args.compose_id, args.push_notifications
def main():
url, compose_id, push_notifications = get_args()
trigger_upload(url, compose_id, push_notifications)
if __name__ == '__main__':
main()
| Add the missing push_notifications args | services.ec2: Add the missing push_notifications args
Signed-off-by: Sayan Chowdhury <[email protected]>
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg |
a5f3c2c027588a72a9861a72cfa975d2f3e24bea | acme/acmelab/acmelab.py | acme/acmelab/acmelab.py | """ The Acme Lab application. """
# Standard library imports.
from logging import DEBUG
# Enthought library imports.
from enthought.envisage.ui.workbench.api import WorkbenchApplication
from enthought.pyface.api import AboutDialog, ImageResource, SplashScreen
class Acmelab(WorkbenchApplication):
""" The Acme Lab application. """
#### 'IApplication' interface #############################################
# The application's globally unique Id.
id = 'acme.acmelab'
#### 'WorkbenchApplication' interface #####################################
# Branding information.
#
# The icon used on window title bars etc.
icon = ImageResource('acmelab.ico')
# The name of the application (also used on window title bars etc).
name = 'Acme Lab'
###########################################################################
# 'WorkbenchApplication' interface.
###########################################################################
def _about_dialog_default(self):
""" Trait initializer. """
about_dialog = AboutDialog(
parent = self.workbench.active_window.control,
image = ImageResource('about')
)
return about_dialog
def _splash_screen_default(self):
""" Trait initializer. """
splash_screen = SplashScreen(
image = ImageResource('splash'),
show_log_messages = True,
log_level = DEBUG
)
return splash_screen
#### EOF ######################################################################
| """ The Acme Lab application. """
# Standard library imports.
from logging import DEBUG
# Enthought library imports.
from enthought.envisage.ui.workbench.api import WorkbenchApplication
from enthought.pyface.api import AboutDialog, ImageResource, SplashScreen
class Acmelab(WorkbenchApplication):
""" The Acme Lab application. """
#### 'IApplication' interface #############################################
# The application's globally unique Id.
id = 'acme.acmelab'
#### 'WorkbenchApplication' interface #####################################
# Branding information.
#
# The icon used on window title bars etc.
icon = ImageResource('acmelab.ico')
# The name of the application (also used on window title bars etc).
name = 'Hermes2D GUI'
###########################################################################
# 'WorkbenchApplication' interface.
###########################################################################
def _about_dialog_default(self):
""" Trait initializer. """
about_dialog = AboutDialog(
parent = self.workbench.active_window.control,
image = ImageResource('about')
)
return about_dialog
def _splash_screen_default(self):
""" Trait initializer. """
splash_screen = SplashScreen(
image = ImageResource('splash'),
show_log_messages = True,
log_level = DEBUG
)
return splash_screen
#### EOF ######################################################################
| Rename it to Hermes2D GUI | Rename it to Hermes2D GUI
| Python | bsd-3-clause | certik/hermes-gui |
2c006d4fd1a823eba2cec933671a43182f0c10f5 | src/dynmen/__init__.py | src/dynmen/__init__.py | # -*- coding: utf-8 -*-
"""
dynmen - A simple python interface to dynamic menus like dmenu or rofi
import dynmen
menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30'])
output = menu({'a': 1, 'b': 2, 'c': 3})
You can make the menu non-blocking by setting:
menu.process_mode = 'futures'
Please see the repository for more examples:
https://github.com/frostidaho/dynmen
"""
from .menu import Menu, MenuError
del menu
def new_dmenu(**kwargs):
from .dmenu import DMenu
return DMenu(**kwargs)
def new_rofi(**kwargs):
from .rofi import Rofi
return Rofi(**kwargs)
| # -*- coding: utf-8 -*-
"""
dynmen - A simple python interface to dynamic menus like dmenu or rofi
import dynmen
menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30'])
output = menu({'a': 1, 'b': 2, 'c': 3})
You can make the menu non-blocking by setting:
menu.process_mode = 'futures'
Please see the repository for more examples:
https://github.com/frostidaho/dynmen
"""
from .menu import Menu, MenuError, MenuResult
del menu
def new_dmenu(**kwargs):
from .dmenu import DMenu
return DMenu(**kwargs)
def new_rofi(**kwargs):
from .rofi import Rofi
return Rofi(**kwargs)
| Add MenuResult to the top-level namespace | Add MenuResult to the top-level namespace
| Python | mit | frostidaho/dynmen |
95b03703e82aecf0c7e942551c0dc37f1f74936c | src/tenyksscripts/scripts/urbandictionary.py | src/tenyksscripts/scripts/urbandictionary.py | import requests
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
def run(data, settings):
if data['payload'] == 'urban dictionary me':
r = requests.get('http://www.urbandictionary.com/random.php')
soup = BeautifulSoup(r.text,
convertEntities=BeautifulSoup.HTML_ENTITIES)
# The word is inner text of the child span of the td with class 'word'
word = soup.findAll('td', attrs={'class': 'word'})[0].findChild().text
# Definitions are just innertext of divs with class definition
definition_divs = soup.findAll('div', attrs={'class': 'definition'})
# BS doesn't unescape hex html encoded characaters, need HTMLParser
parser = HTMLParser()
definitions = [ parser.unescape(div.text) for div in definition_divs ]
# Just use the first definition
return '{0} - {1}'.format(word, definitions[0])
| import requests
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
def run(data, settings):
if data['payload'] == 'urban dictionary me':
req = requests.get('http://www.urbandictionary.com/random.php')
soup = BeautifulSoup(req.text,
convertEntities=BeautifulSoup.HTML_ENTITIES)
# The word is inner text of the child span of the td with class 'word'
word = soup.findAll('td', attrs={'class': 'word'})[0].findChild().text
# Definitions are just innertext of divs with class definition
definition_divs = soup.findAll('div', attrs={'class': 'definition'})
# BS doesn't unescape hex html encoded characaters, need HTMLParser
parser = HTMLParser()
definitions = [ parser.unescape(div.text) for div in definition_divs ]
# Just use the first definition
return '{0} - {1}'.format(word, definitions[0])
| Fix single char variable name | Fix single char variable name
| Python | mit | kyleterry/tenyks-contrib,cblgh/tenyks-contrib,colby/tenyks-contrib |
1dc1be8c5f705ff97d6b83171327fa5d1c59a385 | src/utils/management/commands/run_upgrade.py | src/utils/management/commands/run_upgrade.py | from importlib import import_module
from django.core.management.base import BaseCommand
from django.utils import translation
class Command(BaseCommand):
"""
Upgrades Janeway
"""
help = "Upgrades an install from one version to another."
def add_arguments(self, parser):
"""Adds arguments to Django's management command-line parser.
:param parser: the parser to which the required arguments will be added
:return: None
"""
parser.add_argument('upgrade_module')
def handle(self, *args, **options):
translation.activate('en')
upgrade_module_name = options.get('upgrade_module')
upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name)
try:
upgrade_module = import_module(upgrade_module_path)
upgrade_module.execute()
except ImportError as e:
print('There was an error running the requested upgrade: ')
print(e)
| import os
from importlib import import_module
from django.core.management.base import BaseCommand
from django.utils import translation
from django.conf import settings
def get_modules():
path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade')
root, dirs, files = next(os.walk(path))
return files
class Command(BaseCommand):
"""
Upgrades Janeway
"""
help = "Upgrades an install from one version to another."
def add_arguments(self, parser):
"""Adds arguments to Django's management command-line parser.
:param parser: the parser to which the required arguments will be added
:return: None
"""
parser.add_argument('--path', required=False)
def handle(self, *args, **options):
if not options.get('path'):
print('No upgrade selected. Available upgrade paths: ')
for file in get_modules():
module_name = file.split('.')[0]
print('- {module_name}'.format(module_name=module_name))
print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`')
else:
translation.activate('en')
upgrade_module_name = options.get('path')
upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name)
try:
upgrade_module = import_module(upgrade_module_path)
upgrade_module.execute()
except ImportError as e:
print('There was an error running the requested upgrade: ')
print(e)
| Upgrade path is now not required, help text is output if no path supp. | Upgrade path is now not required, help text is output if no path supp.
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway |
c8483dd1cd40db8b9628f19c9ba664165708a8ab | project/urls.py | project/urls.py | from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
#url(r'^google/', include('project.google.urls')),
url(r'^project/', include('project.projects.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^jsi18n/(?P<packages>\S+?)/$',
'django.views.i18n.javascript_catalog'),
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'),
url(r'^$', 'project.views.index'),
# Media serving
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True},
name='media',
),
)
| from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
url(r'^google/', include('djangoogle.urls')),
url(r'^project/', include('project.projects.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^jsi18n/(?P<packages>\S+?)/$',
'django.views.i18n.javascript_catalog'),
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'),
url(r'^$', 'project.views.index'),
# Media serving
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True},
name='media',
),
)
| Make photos and videos accessible | Make photos and videos accessible
| Python | bsd-2-clause | anjos/website,anjos/website |
78d0fce5f9dd973e288a90bd58040060406cb962 | blinkylib/blinkytape.py | blinkylib/blinkytape.py | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 57600, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
| import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
| Change BlinkyTape baud to 115200 | Change BlinkyTape baud to 115200
| Python | mit | jonspeicher/blinkyfun |
11323a28d90ed59f32d1120224c2f63bdbed0564 | learning/stock/ethstock.py | learning/stock/ethstock.py | import io
import random
import numpy as np
import pandas as pd
import sklearn
import requests
def gettingData():
url = "https://www.coingecko.com/price_charts/export/279/eur.csv"
content = requests.get(url).content
data = pd.read_csv(io.StringIO(content.decode('utf-8')))
return data
def preprocessing(data):
#customize index
data.snapped_at[0].split()[0]
data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0])
data.set_index('snapped_at', inplace=True)
data.index = pd.to_datetime(data.index)
def main():
data = gettingData()
print("Retrieved data:")
print(data.tail())
if __name__ == "__main__":
main()
| import io
import random
import numpy as np
import pandas as pd
import sklearn
import requests
def gettingData():
url = "https://www.coingecko.com/price_charts/export/279/eur.csv"
content = requests.get(url).content
data = pd.read_csv(io.StringIO(content.decode('utf-8')))
return data
def preprocessing(data):
#customize index
data.snapped_at[0].split()[0]
data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0])
data.set_index('snapped_at', inplace=True)
data.index = pd.to_datetime(data.index)
'''
In some cases there is no sample for a certain date.
'''
#Generate all the possible days and use them to reindex
start = data.index[data.index.argmin()]
end = data.index[data.index.argmax()]
index_complete = pd.date_range(start, end)
data = data.reindex(index_complete)
#Fill the blanks with the mean between the previous and the day after
print("\nLooking if the index is complete...")
for idx in data.index:
dayloc = data.index.get_loc(idx)
day = data.loc[idx]
if day.hasnans:
#updating
rg = slice(dayloc-1, dayloc+2)
data.loc[idx] = data.iloc[rg].mean()
print("Day <{}> updated with the mean".format(idx))
def main():
data = gettingData()
print("\nRetrieved data:")
print(data.tail())
preprocessing(data)
if __name__ == "__main__":
main()
| Index is completed if there is no sample for a date | Index is completed if there is no sample for a date
| Python | mit | samuxiii/prototypes,samuxiii/prototypes |
4934d3488321126fb73d236f00f37fe152f05476 | rbm2m/config.py | rbm2m/config.py | # -*- coding: utf-8 -*-
import os
def get_app_env():
return os.environ.get('RBM2M_ENV', 'Production')
class Config(object):
APP_ENV = get_app_env()
DEBUG = False
TESTING = False
DATABASE_URI = 'mysql://rbm2m:rbm2m@localhost/dbm2m'
REDIS_URI = 'redis://@localhost:6379/0'
class ProductionConfig(Config):
DATABASE_URI = os.environ.get('RBM2M_DATABASE_URI')
REDIS_URI = os.environ.get('RBM2M_REDIS_URI')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
| # -*- coding: utf-8 -*-
import os
def get_app_env():
return os.environ.get('RBM2M_ENV', 'Production')
class Config(object):
APP_ENV = get_app_env()
DEBUG = False
TESTING = False
# TODO: ?charset=utf8
DATABASE_URI = 'mysql://rbm2m:rbm2m@localhost/rbm2m'
REDIS_URI = 'redis://@localhost:6379/0'
class ProductionConfig(Config):
DATABASE_URI = os.environ.get('RBM2M_DATABASE_URI')
REDIS_URI = os.environ.get('RBM2M_REDIS_URI')
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
DATABASE_URI = 'mysql://rbm2m:rbm2m@localhost/rbm2m_test'
| Add test database and some notes | Add test database and some notes
| Python | apache-2.0 | notapresent/rbm2m,notapresent/rbm2m |
e494e38b28fbafc70a1e5315a780d64e315113b4 | more/chameleon/main.py | more/chameleon/main.py | import morepath
import chameleon
class ChameleonApp(morepath.App):
pass
@ChameleonApp.setting_section(section='chameleon')
def get_setting_section():
return {
'auto_reload': False
}
@ChameleonApp.template_engine(extension='.pt')
def get_chameleon_render(path, original_render, settings):
config = {'auto_reload': settings.chameleon.auto_reload}
template = chameleon.PageTemplateFile(path, **config)
def render(content, request):
variables = {'request': request}
variables.update(content)
return original_render(template.render(**variables), request)
return render
| import morepath
import chameleon
class ChameleonApp(morepath.App):
pass
@ChameleonApp.setting_section(section='chameleon')
def get_setting_section():
return {'auto_reload': False}
@ChameleonApp.template_engine(extension='.pt')
def get_chameleon_render(path, original_render, settings):
config = settings.chameleon.__dict__
template = chameleon.PageTemplateFile(path, **config)
def render(content, request):
variables = {'request': request}
variables.update(content)
return original_render(template.render(**variables), request)
return render
| Make the way chameleon settings are defined more generic; any Chameleon setting can now be in the chameleon config section. | Make the way chameleon settings are defined more generic; any
Chameleon setting can now be in the chameleon config section.
| Python | bsd-3-clause | morepath/more.chameleon |
b88abd98834529f1342d69e2e91b79efd68e5e8d | backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py | backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py | from django.utils.deprecation import MiddlewareMixin
class FakeShibbolethMiddleWare(MiddlewareMixin):
def process_request(self, request):
if request.POST.get("convert-post-headers") == "1":
for key in request.POST:
request.META[key] = request.POST[key]
| from django.utils.deprecation import MiddlewareMixin
class FakeShibbolethMiddleWare(MiddlewareMixin):
def process_request(self, request):
if request.POST.get("convert-post-headers") == "1":
for key in request.POST:
request.META[key] = request.POST[key]
if request.GET.get("convert-get-headers") == "1":
for key in request.GET:
http_key = key.upper()
http_key.replace("-", "_")
http_key = "HTTP_" + http_key
request.META[http_key] = request.GET[key]
| Add get parameter parsing for fakeshibboleth auto mode | Add get parameter parsing for fakeshibboleth auto mode
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi |
4752f704596613bbb80a649b275c79ce156b32ec | python/libgdf_cffi/__init__.py | python/libgdf_cffi/__init__.py | from __future__ import absolute_import
import os, sys
from .wrapper import _libgdf_wrapper
from .wrapper import GDFError # re-exported
try:
from .libgdf_cffi import ffi
except ImportError:
pass
else:
def _get_lib_name():
if os.name == 'posix':
# TODO this will need to be changed when packaged for distribution
if sys.platform == 'darwin':
return './libgdf.dylib'
else:
return './libgdf.so'
raise NotImplementedError('OS {} not supported'.format(os.name))
libgdf_api = ffi.dlopen(_get_lib_name())
libgdf = _libgdf_wrapper(ffi, libgdf_api)
del _libgdf_wrapper
| from __future__ import absolute_import
import os
import sys
from .wrapper import _libgdf_wrapper
from .wrapper import GDFError # re-exported
try:
from .libgdf_cffi import ffi
except ImportError:
pass
else:
def _get_lib_name():
if os.name == 'posix':
# TODO this will need to be changed when packaged for distribution
if sys.platform == 'darwin':
path = 'libgdf.dylib'
else:
path = 'libgdf.so'
else:
raise NotImplementedError('OS {} not supported'.format(os.name))
# Prefer local version of the library if it exists
localpath = os.path.join('.', path)
if os.path.isfile(localpath):
return localpath
else:
return path
libgdf_api = ffi.dlopen(_get_lib_name())
libgdf = _libgdf_wrapper(ffi, libgdf_api)
del _libgdf_wrapper
| Fix library not found on linux | Fix library not found on linux
| Python | apache-2.0 | gpuopenanalytics/libgdf,gpuopenanalytics/libgdf,gpuopenanalytics/libgdf,gpuopenanalytics/libgdf |
88e839144f4a1dac1468e03f5cd506841caadc84 | django_schedulermanager/management/commands/schedulejob.py | django_schedulermanager/management/commands/schedulejob.py | from django.core.management.base import BaseCommand
from django_schedulermanager.manager import manager
class Command(BaseCommand):
help = 'Schedules a job'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('jobs_name', nargs='+')
def handle(self, *args, **options):
jobs_to_schedule = options['jobs_name']
for job in jobs_to_schedule:
if job not in manager:
self.stdout.write(
'Unable to find job {}. Avalable jobs: {}'.format(job, ','.join([job for job, _ in manager.jobs.items()]))
)
continue
if manager.is_scheduled(job):
self.stdout.write('Job {} already started'.format(job))
continue
job_options = manager.get_options(job)
# TODO: Implement settings override
manager.schedule(job, job_options)
self.stdout.write(self.style.SUCCESS('Successfully scheduled job {}!'.format(job)))
| from django.core.management.base import BaseCommand
from django_schedulermanager.manager import manager
class Command(BaseCommand):
help = 'Schedules a job'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('jobs_name', nargs='+')
def handle(self, *args, **options):
jobs_to_schedule = options['jobs_name']
for job in jobs_to_schedule:
if job not in manager:
self.stdout.write(
'Unable to find job {}. Available jobs: {}'.format(job, ','.join(manager.jobs.keys()))
)
continue
if manager.is_scheduled(job):
self.stdout.write('Job {} already started'.format(job))
continue
job_options = manager.get_options(job)
# TODO: Implement settings override
manager.schedule(job, job_options)
self.stdout.write(self.style.SUCCESS('Successfully scheduled job {}!'.format(job)))
| Fix typo in 'job not found message' and jobs list output code | Fix typo in 'job not found message' and jobs list output code
| Python | mit | marcoacierno/django-schedulermanager |
2ba9eaba0bcb229055db09147f1cb654190badbf | notebooks/style_helpers.py | notebooks/style_helpers.py | import brewer2mpl
import itertools
from cycler import cycler
cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False)
color_cycle = cycler('color', cmap.hex_colors)
marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v'])
markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12])
style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle)
cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False)
color_cycle = cycler('color', ['black', '#88CCDD', '#c73027'])
marker_cycle = cycler('marker', [' ', ' ', ' '])
markersize_cycle = cycler('markersize', [8, 8, 8])
fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full'])
linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid'])
linewidth_cycle = cycler('linewidth', [2, 2.25, 2])
style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)
| import brewer2mpl
from cycler import cycler
N = 5
cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False)
color_cycle = cycler('color', cmap.hex_colors)
marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v'])
markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12])
style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N]
cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False)
color_cycle = cycler('color', ['black', '#88CCDD', '#c73027'])
marker_cycle = cycler('marker', [' ', ' ', ' '])
markersize_cycle = cycler('markersize', [8, 8, 8])
fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full'])
linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid'])
linewidth_cycle = cycler('linewidth', [2, 2.25, 2])
style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
| Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles. | Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
| Python | mit | maxalbert/paper-supplement-nanoparticle-sensing |
39b8cb70ffd6be60c6d757ecd4703a3a0ca2a415 | dbaas/workflow/steps/build_database.py | dbaas/workflow/steps/build_database.py | # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']:
return False
LOG.info("Creating Database...")
database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra'])
workflow_dict['database'] = database
database.team = workflow_dict['team']
if 'project' in workflow_dict:
database.project = workflow_dict['project']
database.description = workflow_dict['description']
database.save()
return True
except Exception, e:
print e
return False
def undo(self, workflow_dict):
try:
LOG.info("Destroying the database....")
workflow_dict['database'].delete()
return True
except Exception, e:
print e
return False
| # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
import datetime
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']:
return False
LOG.info("Creating Database...")
database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra'])
LOG.info("Database %s created!" % database)
workflow_dict['database'] = database
LOG.info("Updating database team")
database.team = workflow_dict['team']
if 'project' in workflow_dict:
LOG.info("Updating database project")
database.project = workflow_dict['project']
LOG.info("Updating database description")
database.description = workflow_dict['description']
database.save()
return True
except Exception, e:
print e
return False
def undo(self, workflow_dict):
try:
if not 'database' in workflow_dict:
return False
LOG.info("Destroying the database....")
if not workflow_dict['database'].is_in_quarantine:
LOG.info("Putting Database in quarentine...")
database = workflow_dict['database']
database.is_in_quarantine= True
database.quarantine_dt = datetime.datetime.now().date()
database.save()
database.delete()
return True
except Exception, e:
print e
return False
| Improve logs and change delete pos | Improve logs and change delete pos
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
099ae768056a4ab160179be89c8750a2bfc06b2c | pyeda/test/test_bdd.py | pyeda/test/test_bdd.py | """
Test binary decision diagrams
"""
| """
Test binary decision diagrams
"""
from pyeda.bdd import expr2bdd
from pyeda.expr import var
a, b, c = map(var, 'abc')
def test_expr2bdd():
f = a * b + a * c + b * c
bdd_f = expr2bdd(f)
assert bdd_f.root == a.var
assert bdd_f.low.root == b.var
assert bdd_f.high.root == b.var
assert bdd_f.low.low.root == 0
assert bdd_f.low.high.root == c.var
assert bdd_f.high.low.root == c.var
assert bdd_f.high.high.root == 1
assert bdd_f.low.high.low.root == 0
assert bdd_f.high.low.high.root == 1
| Implement expr2bdd function and unique table | Implement expr2bdd function and unique table
| Python | bsd-2-clause | GtTmy/pyeda,sschnug/pyeda,sschnug/pyeda,karissa/pyeda,sschnug/pyeda,GtTmy/pyeda,karissa/pyeda,pombredanne/pyeda,pombredanne/pyeda,GtTmy/pyeda,cjdrake/pyeda,pombredanne/pyeda,cjdrake/pyeda,karissa/pyeda,cjdrake/pyeda |
019d33092226d1ff8fe36897c03d25ddd48e34b1 | serve.py | serve.py | """
Flask server app.
"""
import datetime as dt
import sys
import flask
import sqlalchemy as sa
import coils
import tables
import mapping
app = flask.Flask(__name__)
# Load configuration file.
CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg'
config = coils.Config(CONFIG)
@app.route('/')
def index():
"""Render the index page."""
return flask.render_template('index.html')
@app.route('/info')
def info():
"""Return JSON of server info."""
# Connect to database engine.
engine = sa.create_engine(
'mysql://{}:{}@{}/{}'.format(
config['username'], config['password'],
config['host'], config['db_name']))
Session = sa.orm.sessionmaker(bind=engine)
session = Session()
now = dt.datetime.now()
datum = session.query(mapping.Datum).\
filter(mapping.Datum.name=='size')[0]
return flask.jsonify(server_time=now, db_size=datum.value)
if __name__ == '__main__':
app.run()
| """
Flask server app.
"""
import datetime as dt
import sys
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import coils
import mapping
# Load configuration file.
CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg'
config = coils.Config(CONFIG)
# Initialize Flask and SQLAlchemy.
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format(
config['username'], config['password'],
config['host'], config['db_name'])
db = SQLAlchemy(app)
@app.route('/')
def index():
"""Render the index page."""
return flask.render_template('index.html')
@app.route('/info')
def info():
"""Return JSON of server info."""
now = dt.datetime.now()
datum = db.session.query(mapping.Datum).\
filter(mapping.Datum.name=='size')[0]
return flask.jsonify(server_time=now, db_size=datum.value)
if __name__ == '__main__':
app.run()
| Use SQLAlchemy extension in Flask app. | Use SQLAlchemy extension in Flask app.
| Python | mit | vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit |
d1c93d46f4d9f5a21ca97c0825add06406569fc7 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'django-orderable',
version = '1.0.1',
description = 'Model ordering for the Django administration site.',
author = 'Ted Kaemming',
author_email = '[email protected]',
url = 'http://www.github.com/tkaemming/django-orderable/',
packages = find_packages('src'),
package_dir = {'': 'src'},
package_data = {
'orderable': [
'templates/orderable/change_list.html',
'templates/orderable/edit_inline/stacked.html',
'templates/orderable/edit_inline/tabular.html',
'templates/orderable/orderable.js',
]
},
install_requires = ['setuptools'],
zip_safe = False
) | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'django-orderable',
version = '1.0.1',
description = 'Model ordering for the Django administration site.',
author = 'Ted Kaemming',
author_email = '[email protected]',
url = 'http://www.github.com/tkaemming/django-orderable/',
packages = find_packages('src'),
package_dir = {'': 'src'},
package_data = {
'orderable': [
'templates/orderable/change_list.html',
'templates/orderable/edit_inline/stacked.html',
'templates/orderable/edit_inline/tabular.html',
'templates/orderable/orderable.js',
'locale/*/LC_MESSAGES/django.*',
]
},
install_requires = ['setuptools'],
zip_safe = False
) | Make sure to ship translations with sdists. | Make sure to ship translations with sdists.
| Python | mit | tkaemming/django-orderable,tkaemming/django-orderable,tkaemming/django-orderable |
877c2e1c453386b3fa4d249f3a76a7e345c97d23 | setup.py | setup.py | from setuptools import setup
VERSION = '0.2.9'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='[email protected]',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='[email protected]',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| Change project maturity level and bump to 0.3 | Change project maturity level and bump to 0.3
| Python | mit | filwaitman/jinja2-standalone-compiler |
4dc8316d1f5378db974437e462df12d697d126ea | setup.py | setup.py | import os
from setuptools import setup
version = '0.2dev'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CHANGES.txt').read(),
])
setup(
name = "compare",
version = version,
description = "Alternative syntax for comparing/asserting expressions in Python. Supports pluggable matchers for custom comparisons.",
long_description = long_description,
author = "Rudy Lattae",
author_email = "[email protected]",
url = 'https://github.com/rudylattae/compare',
license = "Simplified BSD",
keywords = ['python', 'compare', 'matcher', 'to be', 'to equal', 'assert', 'test equality', 'specification', 'BDD', 'TDD'],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
],
py_modules = ['compare'],
zip_safe = False
) | import os
from setuptools import setup
version = '0.2b'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CHANGES.txt').read(),
])
setup(
name = "compare",
version = version,
description = "Alternative syntax for comparing/asserting expressions in Python. Supports pluggable matchers for custom comparisons.",
long_description = long_description,
author = "Rudy Lattae",
author_email = "[email protected]",
url = 'https://github.com/rudylattae/compare',
license = "Simplified BSD",
keywords = ['python', 'compare', 'matcher', 'to be', 'to equal', 'assert', 'test equality', 'specification', 'BDD', 'TDD'],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
],
py_modules = ['compare'],
zip_safe = False
) | Mark project as beta release | Mark project as beta release
| Python | bsd-3-clause | rudylattae/compare,rudylattae/compare |
a1ed05089c983f3347b5164fffe4030d75b9453d | setup.py | setup.py | import setuptools
import pathlib
setuptools.setup(
name='crafter',
version='0.17.0',
description='Open world survival game for reinforcement learning.',
url='http://github.com/danijar/crafter',
long_description=pathlib.Path('README.md').read_text(),
long_description_content_type='text/markdown',
packages=['crafter'],
package_data={'crafter': ['assets/*']},
entry_points={'console_scripts': ['crafter=crafter.run_gui:main']},
install_requires=[
'numpy', 'imageio', 'pillow', 'opensimplex', 'ruamel.yaml'],
extras_require={'gui': ['pygame']},
classifiers=[
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Topic :: Games/Entertainment',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| import setuptools
import pathlib
setuptools.setup(
name='crafter',
version='0.18.0',
description='Open world survival game for reinforcement learning.',
url='http://github.com/danijar/crafter',
long_description=pathlib.Path('README.md').read_text(),
long_description_content_type='text/markdown',
packages=['crafter'],
package_data={'crafter': ['data.yaml', 'assets/*']},
entry_points={'console_scripts': ['crafter=crafter.run_gui:main']},
install_requires=[
'numpy', 'imageio', 'pillow', 'opensimplex', 'ruamel.yaml'],
extras_require={'gui': ['pygame']},
classifiers=[
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Topic :: Games/Entertainment',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
)
| Include data file in package. | Include data file in package.
| Python | mit | danijar/crafter |
3e083c4ed6f6ebd6739d10a639939c8a290aebc9 | setup.py | setup.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TracTicketGuidelines'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| Change package name before publishing to PyPI | Change package name before publishing to PyPI
| Python | bsd-3-clause | trac-hacks/TicketGuidelinesPlugin |
642b2f2782bb57d64f2a5ed3f0e5c99614b8b9eb | setup.py | setup.py | from setuptools import setup, find_packages
requirements = [
'GitPython == 1.0.1',
'docker-py >= 1.7.0',
'requests ==2.7.0'
]
setup_requirements = [
'flake8'
]
setup(
name='docker-release',
version='0.3-SNAPSHOT',
description='Tool for releasing docker images.',
author='Grzegorz Kokosinski',
author_email='g.kokosinski a) gmail.com',
keywords='docker image release',
url='https://github.com/kokosing/docker_release',
packages=find_packages(),
package_dir={'docker_release': 'docker_release'},
install_requires=requirements,
setup_requires=setup_requirements,
entry_points={'console_scripts': ['docker-release = docker_release.main:main']}
)
| from setuptools import setup, find_packages
requirements = [
'GitPython == 1.0.1',
'docker-py >= 1.7.0',
'requests ==2.7.0'
]
setup_requirements = [
'flake8'
]
description = """
Tool for releasing docker images. It is useful when your docker image files
are under continuous development and you want to have a
convenient way to release (publish) them.
This utility supports:
- tagging git repository when a docker image gets released
- tagging docker image with a git hash commit
- incrementing docker image version (tag)
- updating 'latest' tag in the docker hub
"""
setup(
name='docker-release',
version='0.3-SNAPSHOT',
description=description,
author='Grzegorz Kokosinski',
author_email='g.kokosinski a) gmail.com',
keywords='docker image release',
url='https://github.com/kokosing/docker-release',
packages=find_packages(),
package_dir={'docker_release': 'docker_release'},
install_requires=requirements,
setup_requires=setup_requirements,
entry_points={'console_scripts': ['docker-release = docker_release.main:main']}
)
| Fix project description for pypi | Fix project description for pypi
| Python | apache-2.0 | kokosing/docker-release,kokosing/docker-release |
be8c0bf0000e10a8e33581dddd70ea5cec84ddeb | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.2',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.2.2',
]
setup(
name='chalice',
version='0.5.0',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='[email protected]',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import sys
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.2',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.2.2',
]
if sys.version_info < (3, 0):
raise RuntimeError("chalice requires only Python 2.7")
setup(
name='chalice',
version='0.5.0',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='[email protected]',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
],
)
| Check if runtime is Python2 | Check if runtime is Python2
| Python | apache-2.0 | freaker2k7/chalice,awslabs/chalice |
e74e1d9d4dbd50b37d17b4827332cb4256eb7245 | setup.py | setup.py | import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="SynapseHomeServer",
version="0.1",
packages=find_packages(exclude=["tests"]),
description="Reference Synapse Home Server",
install_requires=[
"syutil==0.0.1",
"Twisted>=14.0.0",
"service_identity>=1.0.0",
"pyasn1",
"pynacl",
"daemonize",
"py-bcrypt",
],
dependency_links=[
"git+ssh://[email protected]/tng/syutil.git#egg=syutil-0.0.1",
],
setup_requires=[
"setuptools_trial",
"setuptools>=1.0.0", # Needs setuptools that supports git+ssh. It's not obvious when support for this was introduced.
"mock"
],
include_package_data=True,
long_description=read("README.rst"),
entry_points="""
[console_scripts]
synapse-homeserver=synapse.app.homeserver:run
"""
)
| import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="SynapseHomeServer",
version="0.1",
packages=find_packages(exclude=["tests"]),
description="Reference Synapse Home Server",
install_requires=[
"syutil==0.0.1",
"Twisted>=14.0.0",
"service_identity>=1.0.0",
"pyasn1",
"pynacl",
"daemonize",
"py-bcrypt",
],
dependency_links=[
"git+ssh://[email protected]:matrix-org/syutil.git#egg=syutil-0.0.1",
],
setup_requires=[
"setuptools_trial",
"setuptools>=1.0.0", # Needs setuptools that supports git+ssh. It's not obvious when support for this was introduced.
"mock"
],
include_package_data=True,
long_description=read("README.rst"),
entry_points="""
[console_scripts]
synapse-homeserver=synapse.app.homeserver:run
"""
)
| Change syutil dependency link to point at github. | Change syutil dependency link to point at github.
| Python | apache-2.0 | matrix-org/synapse,illicitonion/synapse,matrix-org/synapse,howethomas/synapse,iot-factory/synapse,TribeMedia/synapse,rzr/synapse,matrix-org/synapse,TribeMedia/synapse,iot-factory/synapse,illicitonion/synapse,TribeMedia/synapse,matrix-org/synapse,rzr/synapse,rzr/synapse,howethomas/synapse,matrix-org/synapse,howethomas/synapse,rzr/synapse,illicitonion/synapse,rzr/synapse,howethomas/synapse,iot-factory/synapse,TribeMedia/synapse,matrix-org/synapse,illicitonion/synapse,iot-factory/synapse,TribeMedia/synapse,howethomas/synapse,illicitonion/synapse,iot-factory/synapse |
3de79ecba9a9bbef39cf324cc5dc62f703767cc3 | setup.py | setup.py | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='django-afip',
version='0.8.0',
description='AFIP integration for django',
author='Hugo Osvaldo Barrera',
author_email='[email protected]',
url='https://gitlab.com/hobarrera/django-afip',
license='ISC',
packages=find_packages(),
include_package_data=True,
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').read().splitlines()[:-1] +
['suds-py3==1.0.0.0'],
dependency_links=(
'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0',
),
use_scm_version={'version_scheme': 'post-release'},
setup_requires=['setuptools_scm'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='django-afip',
version='0.8.0',
description='AFIP integration for django',
author='Hugo Osvaldo Barrera',
author_email='[email protected]',
url='https://gitlab.com/hobarrera/django-afip',
license='ISC',
packages=find_packages(),
include_package_data=True,
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').read().splitlines()[:-1] +
['suds-py3==1.0.0.0'],
dependency_links=(
'git+https://github.com/hobarrera/suds-py3.git#egg=suds-py3-1.0.0.0',
),
use_scm_version={'version_scheme': 'post-release'},
setup_requires=['setuptools_scm'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| Change author_email to my own email | Change author_email to my own email
My personal email is definitely the one that'll keep working in the long
run.
| Python | isc | hobarrera/django-afip,hobarrera/django-afip |
16e4e3155733ad8c90312414cc975315ad8566d3 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
long_description = open(
os.path.join(
os.path.dirname(__file__),
'README.rst'
)
).read()
setup(
name='ptpython',
author='Jonathan Slenders',
version='0.36',
url='https://github.com/jonathanslenders/ptpython',
description='Python REPL build on top of prompt_toolkit',
long_description=long_description,
packages=find_packages('.'),
install_requires = [
'docopt',
'jedi>=0.9.0',
'prompt_toolkit>=1.0.0,<2.0.0',
'pygments',
],
entry_points={
'console_scripts': [
'ptpython = ptpython.entry_points.run_ptpython:run',
'ptipython = ptpython.entry_points.run_ptipython:run',
'ptpython%s = ptpython.entry_points.run_ptpython:run' % sys.version_info[0],
'ptpython%s.%s = ptpython.entry_points.run_ptpython:run' % sys.version_info[:2],
'ptipython%s = ptpython.entry_points.run_ptipython:run' % sys.version_info[0],
'ptipython%s.%s = ptpython.entry_points.run_ptipython:run' % sys.version_info[:2],
]
},
extra_require={
'ptipython': ['ipython'] # For ptipython, we need to have IPython
}
)
| #!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
long_description = open(
os.path.join(
os.path.dirname(__file__),
'README.rst'
)
).read()
setup(
name='ptpython',
author='Jonathan Slenders',
version='0.36',
url='https://github.com/jonathanslenders/ptpython',
description='Python REPL build on top of prompt_toolkit',
long_description=long_description,
packages=find_packages('.'),
install_requires = [
'docopt',
'jedi>=0.9.0',
'prompt_toolkit>=1.0.0,<2.0.0',
'pygments',
],
entry_points={
'console_scripts': [
'ptpython = ptpython.entry_points.run_ptpython:run',
'ptipython = ptpython.entry_points.run_ptipython:run',
'ptpython%s = ptpython.entry_points.run_ptpython:run' % sys.version_info[0],
'ptipython%s = ptpython.entry_points.run_ptipython:run' % sys.version_info[0],
]
},
extra_require={
'ptipython': ['ipython'] # For ptipython, we need to have IPython
}
)
| Remove minor python version in entry point. | Remove minor python version in entry point.
| Python | bsd-3-clause | jonathanslenders/ptpython |
09e6c915e668c0b41eca75e3105ebac6f8bfcf58 | setup.py | setup.py | import os
from distutils.core import setup
from sphinx.setup_command import BuildDoc
import django_assets
def find_packages(root):
# so we don't depend on setuptools; from the Storm ORM setup.py
packages = []
for directory, subdirectories, files in os.walk(root):
if '__init__.py' in files:
packages.append(directory.replace(os.sep, '.'))
return packages
setup(
name = 'django-assets',
version=".".join(map(str, django_assets.__version__)),
description = 'Media asset management for the Django web framework.',
long_description = 'Merges, minifies and compresses Javascript and '
'CSS files, supporting a variety of different filters, including '
'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting '
'in CSS files.',
author = 'Michael Elsdoerfer',
author_email = '[email protected]',
license = 'BSD',
url = 'http://launchpad.net/django-assets',
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
],
packages = find_packages('django_assets'),
cmdclass={'build_sphinx': BuildDoc},
)
| import os
from distutils.core import setup
try:
from sphinx.setup_command import BuildDoc
cmdclass = {'build_sphinx': BuildDoc}
except ImportError:
print "Sphinx not installed--needed to build documentation"
# default cmdclass to None to avoid
cmdclass = {}
import django_assets
def find_packages(root):
# so we don't depend on setuptools; from the Storm ORM setup.py
packages = []
for directory, subdirectories, files in os.walk(root):
if '__init__.py' in files:
packages.append(directory.replace(os.sep, '.'))
return packages
setup(
name = 'django-assets',
version=".".join(map(str, django_assets.__version__)),
description = 'Media asset management for the Django web framework.',
long_description = 'Merges, minifies and compresses Javascript and '
'CSS files, supporting a variety of different filters, including '
'YUI, jsmin, jspacker or CSS tidy. Also supports URL rewriting '
'in CSS files.',
author = 'Michael Elsdoerfer',
author_email = '[email protected]',
license = 'BSD',
url = 'http://launchpad.net/django-assets',
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
],
packages = find_packages('django_assets'),
cmdclass=cmdclass,
)
| Allow the package to be built without Sphinx being required. | Allow the package to be built without Sphinx being required.
| Python | bsd-2-clause | glorpen/webassets,glorpen/webassets,0x1997/webassets,rs/webassets,aconrad/webassets,JDeuce/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,aconrad/webassets,wijerasa/webassets,john2x/webassets,aconrad/webassets,heynemann/webassets,0x1997/webassets,glorpen/webassets,john2x/webassets,wijerasa/webassets,scorphus/webassets,florianjacob/webassets,heynemann/webassets,JDeuce/webassets |
797da1bd335c0d8237ff4ee4785fe7aca76f0b84 | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
test_suite='pusher_tests',
)
| # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='pusher',
version='1.2.0',
description='A Python library to interract with the Pusher API',
url='https://github.com/pusher/pusher-http-python',
author='Pusher',
author_email='[email protected]',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
],
keywords='pusher rest realtime websockets service',
license='MIT',
packages=[
'pusher'
],
install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'],
tests_require=['nose', 'mock', 'HTTPretty'],
extras_require={
'aiohttp': ["aiohttp>=0.9.0"],
'tornado': ['tornado>=4.0.0']
},
package_data={
'pusher': ['cacert.pem']
},
test_suite='pusher_tests',
)
| Include cacert.pem as part of the package | Include cacert.pem as part of the package
| Python | mit | hkjallbring/pusher-http-python,pusher/pusher-http-python |
43a8a83014c2d77b37615f28e695fa861350d0bf | setup.py | setup.py | import re
from setuptools import find_packages, setup
with open('netsgiro/__init__.py') as fh:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read()))
with open('README.rst') as fh:
long_description = fh.read()
setup(
name='netsgiro',
version=metadata['version'],
description='File parsers for Nets AvtaleGiro and OCR Giro',
long_description=long_description,
url='https://github.com/otovo/python-netsgiro',
author='Otovo AS',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='avtalegiro ocr giro',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[
],
extras_require={
'dev': [
'check-manifest',
'flake8',
'flake8-import-order',
'mypy',
'pytest',
'pytest-xdist',
'tox',
],
},
)
| import re
from setuptools import find_packages, setup
with open('netsgiro/__init__.py') as fh:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read()))
with open('README.rst') as fh:
long_description = fh.read()
setup(
name='netsgiro',
version=metadata['version'],
description='File parsers for Nets AvtaleGiro and OCR Giro',
long_description=long_description,
url='https://github.com/otovo/python-netsgiro',
author='Otovo AS',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='avtalegiro ocr giro',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[
'attrs',
'typing', # Needed for Python 3.4
],
extras_require={
'dev': [
'check-manifest',
'flake8',
'flake8-import-order',
'mypy',
'pytest',
'pytest-xdist',
'tox',
],
},
)
| Add attrs and typing to deps | Add attrs and typing to deps
| Python | apache-2.0 | otovo/python-netsgiro |
f2d29dc5bf44581dd1850b2be70fc5ae4b5fac35 | setup.py | setup.py | # encoding: utf-8
"""
setup
~~~~~
:copyright: 2014 by Daniel Neuhäuser
:license: BSD, see LICENSE.rst for details
"""
from setuptools import setup
setup(
name='oore',
description='Object-Oriented Regular Expressions',
version='0.1.1',
author='Daniel Neuhäuser',
author_email='[email protected]',
url='https://github.com/DasIch/oore',
py_modules=['oore'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'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',
]
)
| # encoding: utf-8
"""
setup
~~~~~
:copyright: 2014 by Daniel Neuhäuser
:license: BSD, see LICENSE.rst for details
"""
from setuptools import setup
with open('README.rst', 'r') as readme:
long_description = readme.read()
setup(
name='oore',
description='Object-Oriented Regular Expressions',
long_description=long_description,
version='0.1.1',
author='Daniel Neuhäuser',
author_email='[email protected]',
url='https://github.com/DasIch/oore',
py_modules=['oore'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'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',
]
)
| Use README as long_description for PyPI | Use README as long_description for PyPI
| Python | bsd-3-clause | DasIch/oore |
e3f273509ada5632cc7110f62caebcdb982307da | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "Bringing sanitiy to world of messed-up data",
long_description=open('README.md').read(),
author = "Aaron Swartz",
author_email = "[email protected]",
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
| from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "Bringing sanitiy to world of messed-up data",
long_description=open('README.md').read(),
author = "Aaron Swartz",
author_email = "[email protected]",
maintainer='Alireza Savand',
maintainer_email='[email protected]',
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
| Add @Alir3z4 as maintainer info | Add @Alir3z4 as maintainer info
| Python | bsd-2-clause | Alir3z4/python-sanitize |
0b1bcf6305f808f3ed1b862a1673e774dce67879 | setup.py | setup.py | from distutils.core import setup
setup(
name = 'depedit',
packages = ['depedit'],
version = '2.1.2',
description = 'A simple configurable tool for manipulating dependency trees',
author = 'Amir Zeldes',
author_email = '[email protected]',
url = 'https://github.com/amir-zeldes/depedit',
license='Apache License, Version 2.0',
download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2',
keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'],
classifiers = ['Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent'],
) | from distutils.core import setup
setup(
name = 'depedit',
packages = ['depedit'],
version = '2.1.2',
description = 'A simple configurable tool for manipulating dependency trees',
author = 'Amir Zeldes',
author_email = '[email protected]',
url = 'https://github.com/amir-zeldes/depedit',
install_requires=["six"],
license='Apache License, Version 2.0',
download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2',
keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'],
classifiers = ['Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent'],
)
| Add six as a requirement | Add six as a requirement
| Python | apache-2.0 | amir-zeldes/DepEdit |
5c5e49797358e7020d409adf74209c0647050465 | setup.py | setup.py | from distutils.core import setup
setup(name='fuzzywuzzy',
version='0.2',
description='Fuzzy string matching in python',
author='Adam Cohen',
author_email='[email protected]',
url='https://github.com/seatgeek/fuzzywuzzy/',
packages=['fuzzywuzzy'])
| from distutils.core import setup
setup(name='fuzzywuzzy',
version='0.2',
description='Fuzzy string matching in python',
author='Adam Cohen',
author_email='[email protected]',
url='https://github.com/seatgeek/fuzzywuzzy/',
packages=['fuzzywuzzy'],
classifiers=(
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3'
)
)
| Add classifiers for python versions | Add classifiers for python versions | Python | mit | jayhetee/fuzzywuzzy,salilnavgire/fuzzywuzzy,beni55/fuzzywuzzy,beni55/fuzzywuzzy,blakejennings/fuzzywuzzy,shalecraig/fuzzywuzzy,pombredanne/fuzzywuzzy,salilnavgire/fuzzywuzzy,pombredanne/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,medecau/fuzzywuzzy,zhahaoyu/fuzzywuzzy,zhahaoyu/fuzzywuzzy,jayhetee/fuzzywuzzy,shalecraig/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,blakejennings/fuzzywuzzy |
e5fe2994b05ffbb5abca5641ae75114da315e888 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
from setuptools import setup
from lora import VERSION
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
if sys.argv[-1] == 'tag':
os.system("git tag -a v{} -m 'tagging v{}'".format(VERSION, VERSION))
os.system('git push && git push --tags')
sys.exit()
setup(
name='python-lora',
version=VERSION,
description='Decrypt LoRa payloads',
url='https://github.com/jieter/python-lora',
author='Jan Pieter Waagmeester',
author_email='[email protected]',
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='LoRa decrypt',
packages=['lora'],
install_requires=[
'cryptography==1.5.2'
],
)
| #!/usr/bin/env python
import os
import sys
from setuptools import setup
from lora import VERSION
package_name = 'python-lora'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist')
os.system('twine upload -r pypi dist/%s-%s.tar.gz' % (package_name, VERSION))
sys.exit()
if sys.argv[-1] == 'tag':
os.system("git tag -a v{} -m 'tagging v{}'".format(VERSION, VERSION))
os.system('git push && git push --tags')
sys.exit()
setup(
name='python-lora',
version=VERSION,
description='Decrypt LoRa payloads',
url='https://github.com/jieter/python-lora',
author='Jan Pieter Waagmeester',
author_email='[email protected]',
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='LoRa decrypt',
packages=['lora'],
install_requires=[
'cryptography==1.5.2'
],
)
| Use twine to upload package | Use twine to upload package
| Python | mit | jieter/python-lora |
2c1caf83f99161ef2f1d17c50a1d3006d9834ecd | hotness/repository.py | hotness/repository.py | import logging
import subprocess
from hotness.cache import cache
log = logging.getLogger('fedmsg')
def get_version(package_name, yumconfig):
nvr_dict = build_nvr_dict(yumconfig)
return nvr_dict[package_name]
@cache.cache_on_arguments()
def build_nvr_dict(yumconfig):
cmdline = ["/usr/bin/repoquery",
"--config", yumconfig,
"--quiet",
"--archlist=src",
"--all",
"--qf",
"%{name}\t%{version}\t%{release}"]
log.info("Running %r" % ' '.join(cmdline))
repoquery = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
(stdout, stderr) = repoquery.communicate()
log.debug("Done with repoquery.")
if stderr:
log.warn(stderr)
new_nvr_dict = {}
for line in stdout.split("\n"):
line = line.strip()
if line:
name, version, release = line.split("\t")
new_nvr_dict[name] = (version, release)
return new_nvr_dict
| import logging
import subprocess
from hotness.cache import cache
log = logging.getLogger('fedmsg')
def get_version(package_name, yumconfig):
nvr_dict = build_nvr_dict(yumconfig)
return nvr_dict[package_name]
@cache.cache_on_arguments()
def build_nvr_dict(yumconfig):
cmdline = ["/usr/bin/repoquery",
"--config", yumconfig,
"--quiet",
#"--archlist=src",
"--all",
"--qf",
"%{name}\t%{version}\t%{release}"]
log.info("Running %r" % ' '.join(cmdline))
repoquery = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
(stdout, stderr) = repoquery.communicate()
log.debug("Done with repoquery.")
if stderr:
log.warn(stderr)
new_nvr_dict = {}
for line in stdout.split("\n"):
line = line.strip()
if line:
name, version, release = line.split("\t")
new_nvr_dict[name] = (version, release)
return new_nvr_dict
| Drop explicit archlist for now. | Drop explicit archlist for now.
| Python | lgpl-2.1 | fedora-infra/the-new-hotness,fedora-infra/the-new-hotness |
a34ce610a6f961158e15769f02926aeed6321e58 | setup.py | setup.py | #!/usr/bin/env python
#
# The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008,
# derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy
# Wardley. All Rights Reserved.
#
# The file "LICENSE" at the top level of this source distribution describes
# the terms under which this file may be distributed.
#
from distutils.core import setup
setup(name = 'Template-Python',
version = '0.1',
description = 'Python port of the Template Toolkit',
author = 'Sean McAfee',
author_email = '[email protected]',
url = 'http://template-toolkit.org/python/',
packages = ['template', 'template.plugin', 'template.namespace'],
package_dir = { 'template.plugin': 'template/plugin', 'template.namespace': 'template/namespace' },
)
| #!/usr/bin/env python
#
# The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008,
# derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy
# Wardley. All Rights Reserved.
#
# The file "LICENSE" at the top level of this source distribution describes
# the terms under which this file may be distributed.
#
from distutils.core import setup
setup(name = 'Template-Python',
version = '0.1.post1',
description = 'Python port of the Template Toolkit',
author = 'Sean McAfee',
author_email = '[email protected]',
url = 'http://template-toolkit.org/python/',
packages = ['template', 'template.plugin', 'template.namespace'],
package_dir = { 'template.plugin': 'template/plugin', 'template.namespace': 'template/namespace' },
)
| Bump version to 0.1.post1 to re-release on PyPi correctly packaged | Bump version to 0.1.post1 to re-release on PyPi correctly packaged
| Python | artistic-2.0 | gsnedders/Template-Python,gsnedders/Template-Python |
8581cf8d2e2d38dcc5ca0bcb8821d9f5c60b00ac | setup.py | setup.py | from distutils.core import setup
from Cython.Build import cythonize
setup(
name="gfspy",
packages=["gtfspy"],
version="0.1",
description="Python package for analyzing public transport timetables",
author="Rainer Kujala",
author_email="[email protected]",
url="https://github.com/CxAalto/gtfspy",
download_url="https://github.com/CxAalto/gtfspy/archive/0.1.tar.gz",
ext_modules=cythonize("gtfspy/routing/*.pyx"),
keywords = ['transit', 'routing' 'gtfs', 'public transport', 'analysis', 'visualization'], # arbitrary keywords
)
| from distutils.core import setup
from Cython.Build import cythonize
setup(
name="gfspy",
packages=["gtfspy"],
version="0.1",
description="Python package for analyzing public transport timetables",
author="Rainer Kujala",
author_email="[email protected]",
url="https://github.com/CxAalto/gtfspy",
download_url="https://github.com/CxAalto/gtfspy/archive/0.2.tar.gz",
ext_modules=cythonize("gtfspy/routing/*.pyx"),
keywords = ['transit', 'routing' 'gtfs', 'public transport', 'analysis', 'visualization'], # arbitrary keywords
)
| Change version back to 0.1 | Change version back to 0.1
| Python | mit | CxAalto/gtfspy,CxAalto/gtfspy |
eb08a3fa792e3ead859358d4038cedbd6b08d8c4 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = ''
with open('koordinates/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='koordinates',
packages=['koordinates',],
version=version
description='koordinates is a Python client library for a number of Koordinates web APIs',
long_description=readme + '\n\n' + history
author='Richard Shea',
author_email='[email protected]',
url='https://github.com/koordinates/python-client',
download_url = 'https://github.com/koordinates/python-client/tarball/0.1',
keywords='koordinates api',
license = 'BSD',
classifiers=[],
test_suite='tests',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import re
import os
from codecs import open
version = ''
with open('koordinates/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='koordinates',
packages=['koordinates',],
version=version,
description='koordinates is a Python client library for a number of Koordinates web APIs',
long_description=readme + '\n\n' + history,
author='Richard Shea',
author_email='[email protected]',
url='https://github.com/koordinates/python-client',
download_url = 'https://github.com/koordinates/python-client/tarball/0.1',
keywords='koordinates api',
license = 'BSD',
classifiers=[],
test_suite='tests',
)
| Resolve import error introduced in last commit. | Resolve import error introduced in last commit.
| Python | bsd-3-clause | koordinates/python-client,koordinates/python-client |
f61d2368998a45dfda99d65d097fed5fb43ad061 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-uglifyjs',
version='0.1',
url='https://github.com/gears/gears-uglifyjs',
license='ISC',
author='Mike Yumatov',
author_email='[email protected]',
description='UglifyJS compressor for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-uglifyjs',
version='0.1',
url='https://github.com/gears/gears-uglifyjs',
license='ISC',
author='Mike Yumatov',
author_email='[email protected]',
description='UglifyJS compressor for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
],
)
| Remove Python 2.5 support, add support for Python 3.2 | Remove Python 2.5 support, add support for Python 3.2
| Python | isc | gears/gears-uglifyjs,gears/gears-uglifyjs |
6c89e9a2eb6c429f9faf8f8fdbb7360239b15a61 | setup.py | setup.py | from setuptools import setup, find_packages
import io
# List all of your Python package dependencies in the
# requirements.txt file
def readfile(filename, split=False):
with io.open(filename, encoding="utf-8") as stream:
if split:
return stream.read().split("\n")
return stream.read()
readme = readfile("README.rst", split=True)[3:] # skip title
requires = readfile("requirements.txt", split=True)
software_licence = readfile("LICENSE")
setup(
name='opencmiss.utils',
version='0.1.1',
description='OpenCMISS Utilities for Python.',
long_description='\n'.join(readme) + software_licence,
classifiers=[],
author='Hugh Sorby',
author_email='',
url='',
license='APACHE',
packages=find_packages(exclude=['ez_setup',]),
namespace_packages=['opencmiss'],
include_package_data=True,
zip_safe=False,
install_requires=requires,
)
| from setuptools import setup, find_packages
import io
# List all of your Python package dependencies in the
# requirements.txt file
def readfile(filename, split=False):
with io.open(filename, encoding="utf-8") as stream:
if split:
return stream.read().split("\n")
return stream.read()
readme = readfile("README.rst", split=True)[3:] # skip title
requires = readfile("requirements.txt", split=True)
software_licence = readfile("LICENSE")
setup(
name='opencmiss.utils',
version='0.1.1',
description='OpenCMISS Utilities for Python.',
long_description='\n'.join(readme) + software_licence,
classifiers=[],
author='Hugh Sorby',
author_email='',
url='',
license='APACHE',
packages=find_packages(exclude=['ez_setup',]),
include_package_data=True,
zip_safe=False,
install_requires=requires,
)
| Remove namespace_packages argument which works with declare_namespace. | Remove namespace_packages argument which works with declare_namespace. | Python | apache-2.0 | OpenCMISS-Bindings/opencmiss.utils |
d041ab4a09da6a2181e1b14f3d0f323ed9c29c6f | applications/templatetags/applications_tags.py | applications/templatetags/applications_tags.py | # -*- encoding: utf-8 -*-
from django import template
from applications.models import Score
register = template.Library()
@register.filter
def scored_by_user(value, arg):
try:
score = Score.objects.get(application=value, user=arg)
return True if score.score else False
except Score.DoesNotExist:
return False
@register.simple_tag
def display_sorting_arrow(name, current_order):
is_reversed = False
if '-{}'.format(name) == current_order:
is_reversed = True
if is_reversed:
return '<a href="?order={}">▼</a>'.format(name)
else:
return '<a href="?order=-{}">▲</a>'.format(name)
| # -*- encoding: utf-8 -*-
from django import template
register = template.Library()
@register.filter
def scored_by_user(application, user):
return application.is_scored_by_user(user)
@register.simple_tag
def display_sorting_arrow(name, current_order):
is_reversed = False
if '-{}'.format(name) == current_order:
is_reversed = True
if is_reversed:
return '<a href="?order={}">▼</a>'.format(name)
else:
return '<a href="?order=-{}">▲</a>'.format(name)
| Make scored_by_user filter call model method | Make scored_by_user filter call model method
Ref #113
| Python | bsd-3-clause | DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls |
eee5008d5e8f7ae29405491962d3adb1af375e44 | setup.py | setup.py | from setuptools import setup, find_packages
import unittest
import doctest
# Read in the version number
exec(open('src/nash/version.py', 'r').read())
requirements = ["numpy==1.11.2"]
def test_suite():
"""Discover all tests in the tests dir"""
test_loader = unittest.TestLoader()
# Read in unit tests
test_suite = test_loader.discover('tests')
# Read in doctests from README
test_suite.addTests(doctest.DocFileSuite('README.md',
optionflags=doctest.ELLIPSIS))
return test_suite
setup(
name='nashpy',
version=__version__,
install_requires=requirements,
author='Vince Knight, James Campbell',
author_email=('[email protected]'),
packages=find_packages('src'),
package_dir={"": "src"},
test_suite='setup.test_suite',
url='',
license='The MIT License (MIT)',
description='A library to compute equilibria of 2 player normal form games',
)
| from setuptools import setup, find_packages
import unittest
import doctest
# Read in the version number
exec(open('src/nash/version.py', 'r').read())
requirements = ["numpy==1.11.2"]
test_requirements = ['hypothesis>=3.6.0']
def test_suite():
"""Discover all tests in the tests dir"""
test_loader = unittest.TestLoader()
# Read in unit tests
test_suite = test_loader.discover('tests')
# Read in doctests from README
test_suite.addTests(doctest.DocFileSuite('README.md',
optionflags=doctest.ELLIPSIS))
return test_suite
setup(
name='nashpy',
version=__version__,
install_requires=requirements,
tests_require=test_requirements,
author='Vince Knight, James Campbell',
author_email=('[email protected]'),
packages=find_packages('src'),
package_dir={"": "src"},
test_suite='setup.test_suite',
url='',
license='The MIT License (MIT)',
description='A library to compute equilibria of 2 player normal form games',
)
| Add hypothesis as test requirement. | Add hypothesis as test requirement.
| Python | mit | drvinceknight/Nashpy |
efe28fd251a399229156d1a0a1d2abf96dc288fe | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='Scrapper',
version='0.9.5',
url='https://github.com/Alkemic/scrapper',
license='MIT',
author='Daniel Alkemic Czuba',
author_email='[email protected]',
description='Scrapper is small, Python web scraping library',
py_modules=['scrapper'],
keywords='scrapper,scraping,webscraping',
install_requires=[
'lxml == 3.6.1',
'requests == 2.5.1',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='Scrapper',
version='0.9.5',
url='https://github.com/Alkemic/scrapper',
license='MIT',
author='Daniel Alkemic Czuba',
author_email='[email protected]',
description='Scrapper is small, Python web scraping library',
py_modules=['scrapper'],
keywords='scrapper,scraping,webscraping',
install_requires=[
'lxml == 3.6.1',
'requests == 2.20.0',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| Bump requests from 2.5.1 to 2.20.0 | Bump requests from 2.5.1 to 2.20.0
Bumps [requests](https://github.com/requests/requests) from 2.5.1 to 2.20.0.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/compare/v2.5.1...v2.20.0)
Signed-off-by: dependabot[bot] <[email protected]> | Python | mit | Alkemic/scrapper,Alkemic/scrapper |
ad761908537b63c2d262f69a75e7b221f84e8647 | ca_on_school_boards_english_public/__init__.py | ca_on_school_boards_english_public/__init__.py | from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = 'Ontario English Public School Board boundary"'
name = 'Ontario English Public School Boards'
url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html'
def get_organizations(self):
organization = Organization(self.name, classification=self.classification)
for division in Division.get(self.division_id).children('school_district'):
organization.add_post(role='Representative', label=division.name, division_id=division.id)
yield organization
| from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = 'Ontario English Public School Board boundary"'
name = 'Ontario English Public School Boards'
url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html'
def get_organizations(self):
organization = Organization(self.name, classification=self.classification)
for division in Division.get(self.division_id).children('school_district'):
for i in range (0, 15): # XXX made-up number
organization.add_post(role='Representative (seat {})'.format(i), label=division.name, division_id=division.id)
yield organization
| Add stub for multiple posts in school boards | Add stub for multiple posts in school boards
| Python | mit | opencivicdata/scrapers-ca,opencivicdata/scrapers-ca |
4bf218a843c61886c910504a47cbc86c8a4982ae | bulbs/content/management/commands/migrate_to_ia.py | bulbs/content/management/commands/migrate_to_ia.py | from django.core.management.base import BaseCommand
from bulbs.content.models import Content, FeatureType
from bulbs.content.tasks import post_to_instant_articles_api
import timezone
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('feature', nargs="+", type=str)
def handle(self, *args, **options):
feature_types = FeatureType.objects.all()
feature = options['feature'][0]
if feature:
feature_types.objects.filter(slug=feature)
for ft in feature_types:
if ft.instant_article:
# All published content belonging to feature type
content = Content.objects.filter(
feature_type=ft,
published__isnull=False,
published__lte=timezone.now())
for c in content:
post_to_instant_articles_api.delay(c.id)
| from django.core.management.base import BaseCommand
from bulbs.content.models import Content, FeatureType
from bulbs.content.tasks import post_to_instant_articles_api
import timezone
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('feature', nargs="+", type=str)
def handle(self, *args, **options):
feature_types = FeatureType.objects.all(instant_article=True)
feature = options['feature'][0]
if feature:
feature_types = feature_types.objects.filter(slug=feature)
for ft in feature_types:
# All published content belonging to feature type
content = Content.objects.filter(
feature_type=ft,
published__isnull=False,
published__lte=timezone.now())
for c in content:
post_to_instant_articles_api.delay(c.id)
| Fix migrate to ia script | Fix migrate to ia script
| Python | mit | theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs |
9343dbfa0d822cdf2f00deab8b18cf4d2e809063 | services/display_routes.py | services/display_routes.py | # -*- coding: utf-8 -*-
from database.database_access import get_dao
from gtfslib.model import Route
from gtfsplugins import decret_2015_1610
from database.database_access import get_dao
def get_routes(agency_id):
dao = get_dao(agency_id)
parsedRoutes = list()
for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS):
parsedRoute = dict()
parsedRoute["name"] = route.route_long_name
parsedRoutes.append(parsedRoute)
return parsedRoutes
| # -*- coding: utf-8 -*-
from database.database_access import get_dao
from gtfslib.model import Route
from services.check_urban import check_urban_category
def get_routes(agency_id):
dao = get_dao(agency_id)
parsedRoutes = list()
for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS):
print(route)
parsedRoute = dict()
parsedRoute["id"] = route.route_id
parsedRoute["name"] = route.route_long_name
parsedRoute["category"] = check_urban_category(route.trips)
parsedRoutes.append(parsedRoute)
return parsedRoutes
| Add id & category to routes list | Add id & category to routes list
| Python | mit | LoveXanome/urbanbus-rest,LoveXanome/urbanbus-rest |
3b83b8715e03b9096f9ae5611019fec4e52ca937 | tests.py | tests.py | from os.path import isdir
import pytest
from filesystem_tree import FilesystemTree
@pytest.yield_fixture
def fs():
fs = FilesystemTree()
yield fs
fs.remove()
def test_it_can_be_instantiated():
assert FilesystemTree().__class__.__name__ == 'FilesystemTree'
def test_args_go_to_mk_not_root():
fs = FilesystemTree('foo', 'bar')
assert fs.root != 'foo'
def test_it_makes_a_directory(fs):
assert isdir(fs.root)
def test_remove_removes(fs):
assert isdir(fs.root)
fs.remove()
assert not isdir(fs.root)
| import os
from os.path import isdir
import pytest
from filesystem_tree import FilesystemTree
@pytest.yield_fixture
def fs():
fs = FilesystemTree()
yield fs
fs.remove()
def test_it_can_be_instantiated():
assert FilesystemTree().__class__.__name__ == 'FilesystemTree'
def test_args_go_to_mk_not_root():
fs = FilesystemTree('foo', 'bar')
assert fs.root != 'foo'
def test_it_makes_a_directory(fs):
assert isdir(fs.root)
def test_resolve_resolves(fs):
path = fs.resolve('some/dir')
assert path == os.path.realpath(os.sep.join([fs.root, 'some', 'dir']))
def test_mk_makes_a_dir(fs):
fs.mk('some/dir')
assert isdir(fs.resolve('some/dir'))
def test_remove_removes(fs):
assert isdir(fs.root)
fs.remove()
assert not isdir(fs.root)
| Add an initial test each for resolve and mk | Add an initial test each for resolve and mk
| Python | mit | gratipay/filesystem_tree.py,gratipay/filesystem_tree.py |
8a75cc4626bd38faeec102aea894d4e7ac08646c | viewer_examples/viewers/collection_viewer.py | viewer_examples/viewers/collection_viewer.py | """
=====================
CollectionViewer demo
=====================
Demo of CollectionViewer for viewing collections of images. This demo uses
successively darker versions of the same image to fake an image collection.
You can scroll through images with the slider, or you can interact with the
viewer using your keyboard:
left/right arrows
Previous/next image in collection.
number keys, 0--9
0% to 90% of collection. For example, "5" goes to the image in the
middle (i.e. 50%) of the collection.
home/end keys
First/last image in collection.
"""
import numpy as np
from skimage import data
from skimage.viewer import CollectionViewer
from skimage.transform import build_gaussian_pyramid
img = data.lena()
img_collection = tuple(build_gaussian_pyramid(img))
view = CollectionViewer(img_collection)
view.show()
| """
=====================
CollectionViewer demo
=====================
Demo of CollectionViewer for viewing collections of images. This demo uses
the different layers of the gaussian pyramid as image collection.
You can scroll through images with the slider, or you can interact with the
viewer using your keyboard:
left/right arrows
Previous/next image in collection.
number keys, 0--9
0% to 90% of collection. For example, "5" goes to the image in the
middle (i.e. 50%) of the collection.
home/end keys
First/last image in collection.
"""
import numpy as np
from skimage import data
from skimage.viewer import CollectionViewer
from skimage.transform import build_gaussian_pyramid
img = data.lena()
img_collection = tuple(build_gaussian_pyramid(img))
view = CollectionViewer(img_collection)
view.show()
| Update description of collection viewer example | Update description of collection viewer example
| Python | bsd-3-clause | almarklein/scikit-image,juliusbierk/scikit-image,paalge/scikit-image,Hiyorimi/scikit-image,chriscrosscutler/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,paalge/scikit-image,warmspringwinds/scikit-image,chriscrosscutler/scikit-image,bennlich/scikit-image,warmspringwinds/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,ajaybhat/scikit-image,emon10005/scikit-image,pratapvardhan/scikit-image,newville/scikit-image,chintak/scikit-image,SamHames/scikit-image,emon10005/scikit-image,rjeli/scikit-image,SamHames/scikit-image,SamHames/scikit-image,Britefury/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,bsipocz/scikit-image,michaelpacer/scikit-image,blink1073/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,oew1v07/scikit-image,dpshelio/scikit-image,michaelpacer/scikit-image,bsipocz/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,newville/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,paalge/scikit-image,rjeli/scikit-image,keflavich/scikit-image,blink1073/scikit-image,almarklein/scikit-image,Midafi/scikit-image,dpshelio/scikit-image,jwiggins/scikit-image,michaelaye/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,Britefury/scikit-image,robintw/scikit-image,GaZ3ll3/scikit-image,youprofit/scikit-image,chintak/scikit-image,almarklein/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,keflavich/scikit-image,juliusbierk/scikit-image,GaZ3ll3/scikit-image,robintw/scikit-image,almarklein/scikit-image |
f93fcd5cee878c201dd1be2102a2a9433a63c4b5 | scripts/set-artist-streamable.py | scripts/set-artist-streamable.py | #!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree
class SetArtistStreamable:
def __init__(self):
self.conn = ordbms.connect ("dbname='librefm'")
self.cursor = self.conn.cursor()
def updateAll(self):
"""Sets artists streamable property if they have streamable tracks already in the database"""
self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1")
for artist in self.cursor.fetchall():
name = artist[0]
print "marking %s as streamable... " % name
self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,))
print "Applying changes... ",
self.conn.commit()
print "done."
if __name__ == '__main__':
sas = SetArtistStreamable()
sas.updateAll()
| #!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree
class SetArtistStreamable:
def __init__(self):
self.conn = ordbms.connect ("dbname='librefm'")
self.cursor = self.conn.cursor()
def updateAll(self):
"""Sets artists streamable property if they have streamable tracks already in the database"""
self.cursor.execute("SELECT DISTINCT(artist.name) FROM artist INNER JOIN track on artist.name=artist_name WHERE track.streamable = 1")
for artist in self.cursor.fetchall():
name = artist[0]
print "marking %s as streamable... " % name
self.cursor.execute("UPDATE artist SET streamable = 1 WHERE name = %s", (name,))
self.conn.commit()
if __name__ == '__main__':
sas = SetArtistStreamable()
sas.updateAll()
| Make streamable artist updates as they happen, rather than commiting at the end of all artists | Make streamable artist updates as they happen, rather than commiting at the end of all artists
| Python | agpl-3.0 | foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm |
564d2eedf6e2b62152869c60bf1f3ba18287d8c0 | fullcalendar/templatetags/fullcalendar.py | fullcalendar/templatetags/fullcalendar.py | from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
| from django import template
from django.utils import timezone
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
@register.simple_tag
def occurrence_duration(occurrence):
start = timezone.localtime(occurrence.start_time)
end = timezone.localtime(occurrence.end_time)
result = start.strftime('%A, %d %B %Y %H:%M')
if (start.day == end.day and start.month == end.month and
start.year == end.year):
result += ' - {:%H:%M}'.format(end)
else:
result += ' - {:%A, %d %B %Y %H:%M}'.format(end)
return result
| Add extra tag which displays the occurrence duration in a smart way | Add extra tag which displays the occurrence duration in a smart way
| Python | mit | jonge-democraten/mezzanine-fullcalendar |
74577faa2468a0b944cef3c88c9b8a82a4881ff1 | query/views.py | query/views.py | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
def results(request, query):
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
return render(request, 'query/index.html', {
'title': 'Results',
'error': error,
'form': form,
'result': dumps(result)
})
| """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from json import dumps
from .forms import QueryForm
def index(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse(
'query:results',
args=(form['query'].value(),)
))
else:
form = QueryForm()
return render(request, 'query/index.html', {
'title': 'Query',
'form': form
})
@cache_page(86400)
def results(request, query):
title = 'Results'
error = None
result = {}
form = QueryForm(initial={"query": query})
try:
ip = ipwhois.IPWhois(query)
result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True)
title = ip.address_str
except (ValueError, ipwhois.exceptions.IPDefinedError) as e:
error = e
title = 'Error'
return render(request, 'query/index.html', {
'title': title,
'error': error,
'form': form,
'result': dumps(result)
})
| Change results page title to include query (or "Error" on error). | Change results page title to include query (or "Error" on error).
| Python | mit | cdubz/rdap-explorer,cdubz/rdap-explorer |
27f47ef27654dfa9c68bb90d3b8fae2e3a281396 | pitchfork/__init__.py | pitchfork/__init__.py | # Copyright 2014 Dave Kludt
#
# 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 flask import Flask, g
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp
from inspect import getmembers, isfunction
import context_functions
import views
import template_filters
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(manage_bp, url_prefix='/manage')
app.register_blueprint(engine_bp, url_prefix='/engine')
# Setup DB based on the app name
mongo, db = HapPyMongo(config)
custom_filters = {
name: function for name, function in getmembers(template_filters)
if isfunction(function)
}
app.jinja_env.filters.update(custom_filters)
app.context_processor(context_functions.utility_processor)
views.ProductsView.register(app)
views.MiscView.register(app)
@app.before_request
def before_request():
g.db = db
| # Copyright 2014 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import setup_application
app, db = setup_application.create_app()
| Move out app setup to setup file to finish cleaning up the init file | Move out app setup to setup file to finish cleaning up the init file
| Python | apache-2.0 | rackerlabs/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork |
63cb8dc1449f6cab87bd7910276d0e06dfd0b228 | rasdoor/app.py | rasdoor/app.py | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
| from flask import Flask, abort, request
app = Flask(__name__)
VERIFY_TOKEN = 'temp_token_to_replace_with_secret'
@app.route('/')
def hello_world():
return 'Hello World'
@app.route('/webhook/facebook_messenger', methods=['GET', 'POST'])
def facebook_webhook():
if request.method == 'POST':
body = request.get_json()
if body['object'] == 'page':
for entry in body['entry']:
print(entry['messaging'][0])
return 'EVENT_RECEIVED'
abort(404)
else:
mode = request.args.get('hub.mode')
token = request.args.get('hub.verify_token')
challenge = request.args.get('hub.challenge')
if mode == 'subscribe' and token == VERIFY_TOKEN:
return challenge
abort(403)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
| Set up basic webhook for Messenger | Set up basic webhook for Messenger
| Python | mit | jabagawee/playing-with-kubernetes |
16d6dd0ba2b5218d211c25e3e197d65fe163b09a | helusers/providers/helsinki_oidc/views.py | helusers/providers/helsinki_oidc/views.py | import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView
)
from .provider import HelsinkiOIDCProvider
class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter):
provider_id = HelsinkiOIDCProvider.id
access_token_url = 'https://api.hel.fi/sso-test/openid/token/'
authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/'
profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
assert resp.status_code == 200
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
| import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView
)
from .provider import HelsinkiOIDCProvider
class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter):
provider_id = HelsinkiOIDCProvider.id
access_token_url = 'https://api.hel.fi/sso/openid/token/'
authorize_url = 'https://api.hel.fi/sso/openid/authorize/'
profile_url = 'https://api.hel.fi/sso/openid/userinfo/'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
assert resp.status_code == 200
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
| Fix broken Helsinki OIDC provider links | Fix broken Helsinki OIDC provider links
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers |
5dc9f2f376b5ac918c1872e1270a782a9ef45ac9 | panoptes_aggregation/extractors/workflow_extractor_config.py | panoptes_aggregation/extractors/workflow_extractor_config.py | def workflow_extractor_config(tasks):
extractor_config = {}
for task_key, task in tasks.items():
if task['type'] == 'drawing':
tools_config = {}
for tdx, tool in enumerate(task['tools']):
if ((tool['type'] == 'polygon') and
(len(tool['details']) > 0) and
(tool['details'][0]['type'] == 'text')):
# this is very ugly but I can't think of a better way to auto detect this
tools_config.setdefault('poly_line_text_extractor'.format(tool['type']), []).append(tdx)
else:
tools_config.setdefault('{0}_extractor'.format(tool['type']), []).append(tdx)
extractor_config[task_key] = tools_config
elif task['type'] in ['single', 'multiple']:
extractor_config[task_key] = 'question_extractor'
elif task['type'] == 'survey':
extractor_config[task_key] = 'survey_extractor'
return extractor_config
| def workflow_extractor_config(tasks):
extractor_config = {}
for task_key, task in tasks.items():
if task['type'] == 'drawing':
tools_config = {}
for tdx, tool in enumerate(task['tools']):
if ((tool['type'] == 'polygon') and
(len(tool['details']) == 1) and
(tool['details'][0]['type'] == 'text')):
# this is very ugly but I can't think of a better way to auto detect this
tools_config.setdefault('poly_line_text_extractor'.format(tool['type']), []).append(tdx)
else:
tools_config.setdefault('{0}_extractor'.format(tool['type']), []).append(tdx)
extractor_config[task_key] = tools_config
elif task['type'] in ['single', 'multiple']:
extractor_config[task_key] = 'question_extractor'
elif task['type'] == 'survey':
extractor_config[task_key] = 'survey_extractor'
return extractor_config
| Make sure that auto-detected task only has one sub-task | Make sure that auto-detected task only has one sub-task
Be more restrictive with the workflow auto detect for the poly-line-text
tool.
| Python | apache-2.0 | CKrawczyk/python-reducers-for-caesar |
3e280e64874d1a68b6bc5fc91a8b6b28968b74e3 | meinberlin/apps/dashboard2/contents.py | meinberlin/apps/dashboard2/contents.py | class DashboardContents:
_registry = {}
content = DashboardContents()
| class DashboardContents:
_registry = {'project': {}, 'module': {}}
def __getitem__(self, identifier):
component = self._registry['project'].get(identifier, None)
if not component:
component = self._registry['module'].get(identifier)
return component
def __contains__(self, identifier):
return (identifier in self._registry['project'] or
identifier in self._registry['module'])
def register_project(self, component):
self._registry['project'][component.identifier] = component
def register_module(self, component):
self._registry['module'][component.identifier] = component
def get_project_components(self):
return self._registry['project'].items()
def get_module_components(self):
return self._registry['module'].items()
content = DashboardContents()
| Store project and module componentes separately | Store project and module componentes separately
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
46ee9dad4030c8628d951abb84a667c7398dd834 | src/coordinators/models.py | src/coordinators/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from locations.models import District
class Coordinator(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_manager = models.BooleanField()
district = models.ForeignKey(District, verbose_name=_('District'),
blank=True, null=True)
def filter_by_district(qs, user, lookup):
# superusers and managers see everything
if (user.is_superuser
or hasattr(user, 'coordinator') and user.coordinator.is_manager):
return qs
# don't show anything to unconfigured users
if not hasattr(user, 'coordinator') or not user.coordinator.district:
return qs.none()
kwargs = {
lookup: user.coordinator.district
}
return qs.filter(**kwargs)
| from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from locations.models import District
class Coordinator(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_manager = models.BooleanField()
district = models.ForeignKey(District, verbose_name=_('District'),
blank=True, null=True)
def filter_by_district(qs, user, lookup):
# superusers and managers see everything
if (user.is_superuser
or hasattr(user, 'coordinator') and user.coordinator.is_manager):
return qs
# don't show anything to unconfigured users
if not hasattr(user, 'coordinator') or not user.coordinator.district:
return qs.none()
kwargs = {
lookup: user.coordinator.district
}
return qs.filter(**kwargs).distinct()
| Fix error when multiple objects were returned for coordinators in admin | Fix error when multiple objects were returned for coordinators in admin
| Python | mit | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign |
72796a97a24c512cf43fd9559d6e6b47d2f72e72 | preferences/models.py | preferences/models.py | import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
from django.contrib.auth.models import User
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
| import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
| Allow address to be null | Allow address to be null
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
d7c41853277c1df53192b2f879f47f75f3c62fd5 | server/covmanager/urls.py | server/covmanager/urls.py | from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
) | from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
urlpatterns = patterns('',
url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
url(r'^repositories/', views.repositories, name="repositories"),
url(r'^collections/$', views.collections, name="collections"),
url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"),
url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"),
url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"),
url(r'^rest/', include(router.urls)),
)
| Add redirect for / to collections | [CovManager] Add redirect for / to collections
| Python | mpl-2.0 | MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager |
9940a61cd7dbe9b66dcd4c7e07f967e53d2951d4 | pybossa/auth/token.py | pybossa/auth/token.py | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from flask.ext.login import current_user
def create(token=None):
return False
def read(token=None):
return not current_user.is_anonymous()
def update(token=None):
return False
def delete(token=None):
return False
| # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from flask.ext.login import current_user
def create(token=None):
return False
def read(token=None):
return not current_user.is_anonymous()
def update(token):
return False
def delete(token):
return False
| Change signature to match other resources auth functions | Change signature to match other resources auth functions
| Python | agpl-3.0 | geotagx/pybossa,jean/pybossa,stefanhahmann/pybossa,harihpr/tweetclickers,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,Scifabric/pybossa,geotagx/pybossa,jean/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,OpenNewsLabs/pybossa,inteligencia-coletiva-lsd/pybossa,PyBossa/pybossa |
6fe48fc7499327d27f69204b7f8ec927fc975177 | python/lexPythonMQ.py | python/lexPythonMQ.py | #!/usr/bin/python
import tokenize;
import zmq;
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://lo:32132")
while True:
# Wait for next request from client
message = socket.recv() | #!/usr/bin/python
import re, sys, tokenize, zmq;
from StringIO import StringIO
def err(msg):
sys.err.write(str(msg) + '\n')
class LexPyMQ(object):
def __init__(self):
self.zctx = zmq.Context()
self.socket = self.zctx.socket(zmq.REP)
def run(self):
self.socket.bind("tcp://lo:32132")
while True:
msg = self.socket.recv_json(0)
# there are definitely new lines in the code
if not msg.get('python'):
err('received non-python code')
code = msg.get('body', '')
self.socket.send_json(tokenize.generate_tokens(StringIO(code)))
if __name__ == '__main__':
LexPyMQ().run()
| Implement python lexer ZMQ service. | Implement python lexer ZMQ service.
| Python | agpl-3.0 | orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/estimate-charm,naturalness/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork |
778cb1a9f9fbb7e260d9a17f07d412d4fa12930a | ubigeo/forms.py | ubigeo/forms.py | from django import forms
from .models import Department, Province, District
class DepartmentForm(forms.Form):
department = forms.ModelChoiceField(
queryset=Department.objects
)
class ProvinceForm(DepartmentForm):
province = forms.ModelChoiceField(
queryset=Province.objects.none()
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.is_bound:
department = self._get_field_value('department')
if department:
self.fields['province'].queryset = Province.objects.filter(
parent=department
)
def _get_field_value(self, name):
field = self.fields[name]
value = field.widget.value_from_datadict(
self.data,
self.files,
self.add_prefix(name)
)
try:
return field.clean(value)
except:
return None
class DistrictForm(ProvinceForm):
district = forms.ModelChoiceField(
queryset=District.objects.none()
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.is_bound:
province = self._get_field_value('province')
if province:
self.fields['district'].queryset = District.objects.filter(
parent=province
)
UbigeoForm = DistrictForm
| from django import forms
from .models import Department, Province, District
class DepartmentForm(forms.Form):
department = forms.ModelChoiceField(
queryset=Department.objects.all()
)
class ProvinceForm(DepartmentForm):
province = forms.ModelChoiceField(
queryset=Province.objects.none()
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.is_bound:
department = self._get_field_value('department')
if department:
self.fields['province'].queryset = Province.objects.filter(
parent=department
)
def _get_field_value(self, name):
field = self.fields[name]
value = field.widget.value_from_datadict(
self.data,
self.files,
self.add_prefix(name)
)
try:
return field.clean(value)
except:
return None
class DistrictForm(ProvinceForm):
district = forms.ModelChoiceField(
queryset=District.objects.none()
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.is_bound:
province = self._get_field_value('province')
if province:
self.fields['district'].queryset = District.objects.filter(
parent=province
)
UbigeoForm = DistrictForm
| Add "all" to the queryset in DepartmentForm | Add "all" to the queryset in DepartmentForm
| Python | mit | snahor/django-ubigeo |
15de2fe886c52f0900deeb519f944d22bb5c6db4 | mysite/project/views.py | mysite/project/views.py | from mysite.search.models import Project
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
def project(request, project__name = None):
p = Project.objects.get(name=project__name)
return render_to_response('project/project.html',
{
'the_user': request.user,
'project': p,
'contributors': p.get_contributors()
}
)
| from mysite.search.models import Project
import django.template
import mysite.base.decorators
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
@mysite.base.decorators.view
def project(request, project__name = None):
p = Project.objects.get(name=project__name)
return (request,
'project/project.html',
{
'project': p,
'contributors': p.get_contributors()
},
)
| Use the @view decorator to ensure that the project page gets user data. | Use the @view decorator to ensure that the project page gets user data.
| Python | agpl-3.0 | onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,sudheesh001/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,SnappleCap/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,sudheesh001/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,Changaco/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,campbe13/openhatch,mzdaniel/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,onceuponatimeforever/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,heeraj123/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,moijes12/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,Changaco/oh-mainline,moijes12/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,willingc/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,moijes12/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline |
d2a040618a1e816b97f60aa66f5b4c9ab4a3e6b9 | refmanage/fs_utils.py | refmanage/fs_utils.py | # -*- coding: utf-8 -*-
| # -*- coding: utf-8 -*-
import os
import glob
import pathlib2 as pathlib
def handle_files_args(paths_args):
"""
Handle files arguments from command line
This method takes a list of strings representing paths passed to the cli. It expands the path arguments and creates a list of pathlib.Path objects which unambiguously point to the files indicated by the command line arguments.
:param list paths_args: Paths to files.
"""
for paths_arg in paths_args:
# Handle paths implicitly rooted at user home dir
paths_arg = os.path.expanduser(paths_arg)
# Expand wildcards
paths_arg = glob.glob(paths_arg)
# Create list of pathlib.Path objects
paths = [pathlib.Path(path_arg) for path_arg in paths_arg]
return paths
| Add method to handle files args from cli | Add method to handle files args from cli
| Python | mit | jrsmith3/refmanage |
fa14c040e6483087f5b2c78bc1a7aeee9ad2274a | Instanssi/kompomaatti/misc/time_formatting.py | Instanssi/kompomaatti/misc/time_formatting.py | # -*- coding: utf-8 -*-
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
| # -*- coding: utf-8 -*-
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end)
return compo
def competition_times_formatter(competition):
competition.start_time = awesometime.format_single(competition.start)
competition.participation_end_time = awesometime.format_single(competition.participation_end)
return competition
| Add time formatter for competitions | kompomaatti: Add time formatter for competitions
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org |
ae78bd758c690e28abaae2c07e8a3890e76044e0 | pylearn2/scripts/papers/maxout/tests/test_mnist.py | pylearn2/scripts/papers/maxout/tests/test_mnist.py | import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.main_loop()
| import os
import numpy as np
import pylearn2
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.termination_criteria import EpochCounter
from pylearn2.utils.serial import load_train_file
def test_mnist():
"""
Test the mnist.yaml file from the dropout
paper on random input
"""
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
random_X = np.random.rand(10, 784)
random_y = np.random.randint(0, 10, (10, 1))
train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10)
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.algorithm._set_monitoring_dataset(train.dataset)
train.main_loop()
| Allow papers/maxout to be tested without MNIST data | Allow papers/maxout to be tested without MNIST data
| Python | bsd-3-clause | KennethPierce/pylearnk,KennethPierce/pylearnk,Refefer/pylearn2,JesseLivezey/plankton,goodfeli/pylearn2,theoryno3/pylearn2,alexjc/pylearn2,pkainz/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,alexjc/pylearn2,kastnerkyle/pylearn2,ddboline/pylearn2,se4u/pylearn2,hantek/pylearn2,jeremyfix/pylearn2,nouiz/pylearn2,abergeron/pylearn2,sandeepkbhat/pylearn2,chrish42/pylearn,msingh172/pylearn2,caidongyun/pylearn2,fulmicoton/pylearn2,Refefer/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,mclaughlin6464/pylearn2,hantek/pylearn2,sandeepkbhat/pylearn2,fyffyt/pylearn2,bartvm/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,se4u/pylearn2,mkraemer67/pylearn2,TNick/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,hyqneuron/pylearn2-maxsom,woozzu/pylearn2,CIFASIS/pylearn2,pombredanne/pylearn2,fishcorn/pylearn2,JesseLivezey/pylearn2,ashhher3/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,lisa-lab/pylearn2,pombredanne/pylearn2,daemonmaker/pylearn2,ddboline/pylearn2,junbochen/pylearn2,JesseLivezey/plankton,hantek/pylearn2,msingh172/pylearn2,ashhher3/pylearn2,ddboline/pylearn2,matrogers/pylearn2,abergeron/pylearn2,ashhher3/pylearn2,shiquanwang/pylearn2,goodfeli/pylearn2,pombredanne/pylearn2,nouiz/pylearn2,nouiz/pylearn2,matrogers/pylearn2,cosmoharrigan/pylearn2,kastnerkyle/pylearn2,shiquanwang/pylearn2,kose-y/pylearn2,aalmah/pylearn2,abergeron/pylearn2,junbochen/pylearn2,w1kke/pylearn2,fyffyt/pylearn2,daemonmaker/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,JesseLivezey/plankton,mclaughlin6464/pylearn2,nouiz/pylearn2,hantek/pylearn2,se4u/pylearn2,lamblin/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,kastnerkyle/pylearn2,aalmah/pylearn2,lamblin/pylearn2,theoryno3/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,JesseLivezey/plankton,shiquanwang/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,lisa-lab/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,matrogers/pylearn2,mkraemer67/pylearn2,theoryno3/pylearn2,junbochen/pylearn2,daemonmaker/pylearn2,pkainz/pylearn2,theoryno3/pylearn2,CIFASIS/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,caidongyun/pylearn2,bartvm/pylearn2,se4u/pylearn2,kose-y/pylearn2,msingh172/pylearn2,KennethPierce/pylearnk,hyqneuron/pylearn2-maxsom,hyqneuron/pylearn2-maxsom,fishcorn/pylearn2,KennethPierce/pylearnk,fyffyt/pylearn2,kose-y/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lamblin/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,w1kke/pylearn2,caidongyun/pylearn2,CIFASIS/pylearn2,msingh172/pylearn2,pkainz/pylearn2,Refefer/pylearn2,aalmah/pylearn2,chrish42/pylearn,pkainz/pylearn2,bartvm/pylearn2,woozzu/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,pombredanne/pylearn2,jeremyfix/pylearn2,Refefer/pylearn2,lunyang/pylearn2,lisa-lab/pylearn2,JesseLivezey/pylearn2,skearnes/pylearn2,lunyang/pylearn2,TNick/pylearn2,goodfeli/pylearn2,kose-y/pylearn2,woozzu/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,aalmah/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,kastnerkyle/pylearn2,JesseLivezey/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,w1kke/pylearn2,cosmoharrigan/pylearn2,alexjc/pylearn2,TNick/pylearn2,mkraemer67/pylearn2,w1kke/pylearn2 |
c4809f9f43129d092235738127b90dc62f593fb8 | steinie/app.py | steinie/app.py | from werkzeug import routing
from werkzeug import serving
from werkzeug import wrappers
from . import routes
class Steinie(routes.Router):
def __init__(self, host="127.0.0.1", port=5151, debug=False):
self.host = host
self.port = port
self.debug = debug
super(Steinie, self).__init__()
def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
def wsgi_app(self, environ, start_response):
request = wrappers.Request(environ)
response = self.handle(request)
return wrappers.Response(response)(environ, start_response)
def run(self):
serving.run_simple(self.host, self.port, self, use_debugger=self.debug)
def use(self, route, router):
# if not route.endswith('/'):
# route += '/'
if route.startswith('/'):
route = route[1:]
submount = route
if not submount.startswith('/'):
submount = '/' + submount
rules = [a for a in router.map.iter_rules()]
mount = routing.EndpointPrefix(route, [routes.Submount(submount, rules)])
self.map.add(mount)
# import ipdb; ipdb.set_trace()
| from werkzeug import routing
from werkzeug import serving
from werkzeug import wrappers
from . import routes
class Steinie(routes.Router):
def __init__(self, host="127.0.0.1", port=5151, debug=False):
self.host = host
self.port = port
self.debug = debug
super(Steinie, self).__init__()
def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
def wsgi_app(self, environ, start_response):
request = wrappers.Request(environ)
response = self.handle(request)
return wrappers.Response(response)(environ, start_response)
def run(self):
serving.run_simple(self.host, self.port, self, use_debugger=self.debug)
def use(self, route, router):
if route.startswith('/'):
route = route[1:]
submount = route
if not submount.startswith('/'):
submount = '/' + submount
rules = [a for a in router.map.iter_rules()]
mount = routing.EndpointPrefix(route, [routes.Submount(submount, rules)])
self.map.add(mount)
| Remove some commented out code | Remove some commented out code
| Python | apache-2.0 | tswicegood/steinie,tswicegood/steinie |
Subsets and Splits