commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
bb2c92732ee7cf834d937025a03c87d7ee5bc343 | tests/modules/test_traffic.py | tests/modules/test_traffic.py | import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_mi... | import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_mi... | Fix tests for module traffic | [tests/traffic] Fix tests for module traffic
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -14,10 +14,10 @@
def test_get_minwidth_str(self):
# default value (two digits after dot)
- self.assertEqual(self.module.get_minwidth_str(), "1000.00MB")
+ self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
self.module._format = "... |
37bccb59874dd2e50a0ace482461e156ee5b7240 | pytips/util.py | pytips/util.py | # -*- coding: utf-8 -*-
"""Utility functions for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import html5lib
from dateutil.parser import parse as parse_date
def extract_publication_date(html):
"""... | # -*- coding: utf-8 -*-
"""Utility functions for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import signal
from decorator import decorator
import html5lib
from dateutil.parser import parse as parse_da... | Add a decorator to time out long-running functions. | Add a decorator to time out long-running functions.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips | ---
+++
@@ -6,6 +6,10 @@
from __future__ import division
+import signal
+
+
+from decorator import decorator
import html5lib
from dateutil.parser import parse as parse_date
@@ -15,3 +19,41 @@
root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
publication_date_string = root... |
0762dbb9b0a43eb6bd01f43d88ac990e90da2303 | chandra_suli/filter_reg.py | chandra_suli/filter_reg.py |
"""
Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes
Goals by Friday 6/31 - Get script working for one image at a time
below = code used by Giacomo to create filtered image
ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")]' test... | #!/usr/bin/env python
"""
Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes
Goals by Friday 6/31 - Get script working for one image at a time
below = code used by Giacomo to create filtered image
ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("m... | Copy reg file names into text file | Copy reg file names into text file
| Python | bsd-3-clause | nitikayad96/chandra_suli | ---
+++
@@ -1,4 +1,4 @@
-
+#!/usr/bin/env python
"""
Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes
@@ -6,4 +6,30 @@
below = code used by Giacomo to create filtered image
ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")... |
4ba9bc552e8d6cec598718c688cf5989769876c2 | cla_backend/settings/jenkins.py | cla_backend/settings/jenkins.py | import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.bac... | import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'cla_backend.a... | Use custom reports backend for test DB in Jenkins | Use custom reports backend for test DB in Jenkins
As Django test runner does not support replica DBs (MIRROR setting
just redirects to use the other connection), change the default
connection to use the custom engine when running in jenkins.
Tests fail during BST due to the connection not being UTC if using
the defau... | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -18,7 +18,7 @@
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.postgresql_psycopg2',
+ 'ENGINE': 'cla_backend.apps.reports.db.backend',
'NAME': os.environ.get('DB_USERNAME', ''),
'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ... |
3bf918d7c303371651e9e9890576dbb5a827629b | library/sensors/SensePressure.py | library/sensors/SensePressure.py | # -*- coding: utf-8 -*-
import sys
from sense_hat import SenseHat
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class SensePressure(Sensor):
def __init__(self):
... | # -*- coding: utf-8 -*-
import sys
from sense_hat import SenseHat
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class SensePressure(Sensor):
def __init__(self):
... | Fix to the pressure sensor | Fix to the pressure sensor
| Python | mit | OpenSpaceProgram/pyOSP,OpenSpaceProgram/pyOSP | ---
+++
@@ -13,7 +13,7 @@
def __init__(self):
super(SensePressure, self).__init__()
- tempMetaData = MetaData('millibars')
+ tempMetaData = MetaData('Millibars')
tempMetaData.setValueCallback(self.getPressureValue)
tempMetaData.setUnitCallback(self.getPressureUnit)
... |
ba9a758161b6863704b2be7b28f6638e2191d8dd | test/test_nc.py | test/test_nc.py | #!/usr/bin/env python
"""
Unittests for csvnc module
"""
import os
import pytest
from csvnc import csvnc
def test_generated_file_should_have_extention_nc():
data_file = 'data.csv'
assert 'data.nc' == csvnc.new_name(data_file)
| #!/usr/bin/env python
"""
Unittests for csvnc module
"""
import os
import pytest
from csvnc import csvnc
class TestCsvnc(object):
def test_generated_file_should_have_extention_nc(self):
data_file = 'data.csv'
assert 'data.nc' == csvnc.new_name(data_file)
| Add test class for grouping tests | Add test class for grouping tests
| Python | mit | qba73/nc | ---
+++
@@ -9,7 +9,8 @@
from csvnc import csvnc
-def test_generated_file_should_have_extention_nc():
- data_file = 'data.csv'
- assert 'data.nc' == csvnc.new_name(data_file)
+class TestCsvnc(object):
+ def test_generated_file_should_have_extention_nc(self):
+ data_file = 'data.csv'
+ asser... |
1b0253f09196d3824481451f8daee6b486825fa6 | prismriver/qt/gui.py | prismriver/qt/gui.py | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... | Set application name to "Lunasa Prismriver" | [qt] Set application name to "Lunasa Prismriver"
That value will be used as WM_CLASS of application.
| Python | mit | anlar/prismriver-lyrics,anlar/prismriver-lyrics,anlar/prismriver,anlar/prismriver | ---
+++
@@ -13,6 +13,7 @@
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
+ app.setApplicationName('Lunasa Prismriver')
main = MainWindow()
main.setGeometry(0, 0, 1024, 1000) |
e852a210a84e91369752ef8fcfbbf52c27b3db59 | pycrest/visualize.py | pycrest/visualize.py | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... | Make pycrest mesh viz more capable | Make pycrest mesh viz more capable
| Python | mit | Andlon/crest,Andlon/crest,Andlon/crest | ---
+++
@@ -8,5 +8,15 @@
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tri.elements, *args, **kwargs)
+ xmin = tri.vertices[:, 0].min()
+ xmax = tri.vertices[:, 0].max()
+ ymin = ... |
e1092caacec94bd016283b8452ad4399dba0f231 | cogs/gaming_tasks.py | cogs/gaming_tasks.py | from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def... | from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def... | Check if it is None before continuing | Check if it is None before continuing
| Python | mit | bsquidwrd/Squid-Bot,bsquidwrd/Squid-Bot | ---
+++
@@ -25,9 +25,12 @@
channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False)
if channels.count() >= 1:
for channel in channels:
+ if channel is None:
+ continue
try:... |
955d39c4ae1190b9bc4a0c7db9aa914a08acf8d5 | pwnedcheck/__init__.py | pwnedcheck/__init__.py | __author__ = 'Casey Dunham'
__version__ = "0.1.0"
import urllib
import urllib2
import json
PWNED_API_URL = "https://haveibeenpwned.com/api/breachedaccount/%s"
class InvalidEmail(Exception):
pass
def check(email):
req = urllib.Request(PWNED_API_URL % urllib.quote(email))
try:
resp = urllib.ur... | __author__ = 'Casey Dunham'
__version__ = "0.1.0"
import urllib
import urllib2
import json
PWNED_API_URL = "https://haveibeenpwned.com/api/breachedaccount/%s"
class InvalidEmail(Exception):
pass
def check(email):
req = urllib2.Request(PWNED_API_URL % urllib.quote(email))
try:
resp = urllib2.... | Fix stupid typo in urllib | Fix stupid typo in urllib
| Python | mit | caseydunham/PwnedCheck | ---
+++
@@ -15,9 +15,9 @@
def check(email):
- req = urllib.Request(PWNED_API_URL % urllib.quote(email))
+ req = urllib2.Request(PWNED_API_URL % urllib.quote(email))
try:
- resp = urllib.urlopen(req)
+ resp = urllib2.urlopen(req)
return json.loads(resp.read())
except urllib2... |
99764a2d1f99cd6a2b61b35c4a262d730a26ba1f | pytest_hidecaptured.py | pytest_hidecaptured.py | # -*- coding: utf-8 -*-
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(rep... | # -*- coding: utf-8 -*-
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(rep... | Fix failing tests for captured output in teardown | Fix failing tests for captured output in teardown
| Python | mit | hamzasheikh/pytest-hidecaptured | ---
+++
@@ -5,6 +5,6 @@
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report)))
# print("PLUGIN SAYS -> type(report) -> {0}".format(type(report)))
- sections = [item for item in report.sections if item[0] not in ("Capt... |
08aefdf3e5a991293ad9ce1cc7f1112a01e4506d | trade_server.py | trade_server.py | import threading
import socket
import SocketServer
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
messages.append(data)
... | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, bids
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if d... | Add basic handling of incoming bids and offers. | Add basic handling of incoming bids and offers.
| Python | mit | Tribler/decentral-market | ---
+++
@@ -1,6 +1,9 @@
+import json
import threading
import socket
import SocketServer
+
+from orderbook import match_bid, offers, bids
messages = []
@@ -12,10 +15,15 @@
while True:
data = self.request.recv(1024)
if data:
+ data = json.loads(d... |
c8828d563a3db96a52544c6bbe4ca219efd364c5 | falmer/events/filters.py | falmer/events/filters.py | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
... | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
... | Add filtering options to events | Add filtering options to events
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | ---
+++
@@ -15,6 +15,14 @@
'student_group',
'from_time',
'to_time',
+
+ 'audience_just_for_pgs',
+ 'audience_suitable_kids_families',
+ 'audience_good_to_meet_people',
+ 'is_over_18_only',
+ 'cost',
+ 'alcohol',
+... |
45501645e06743bd6341cfd6d2573f6c5f36d094 | netmiko/ubiquiti/__init__.py | netmiko/ubiquiti/__init__.py | from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH
from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH
from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH
__all__ = [
"UbiquitiEdgeRouterSSH",
"UbiquitiEdgeSSH",
"UnifiSwitchSSH",
"UbiquitiUnifiSwitchSSH",
]
| from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH
from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH
from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH
__all__ = [
"UbiquitiEdgeRouterSSH",
"UbiquitiEdgeSSH",
"UbiquitiUnifiSwitchSSH",
]
| Fix __all__ import for ubiquiti | Fix __all__ import for ubiquiti
| Python | mit | ktbyers/netmiko,ktbyers/netmiko | ---
+++
@@ -5,6 +5,5 @@
__all__ = [
"UbiquitiEdgeRouterSSH",
"UbiquitiEdgeSSH",
- "UnifiSwitchSSH",
"UbiquitiUnifiSwitchSSH",
] |
34c85636d11bc156a4ce4e5956ed1a19fe7f6f1f | buffer/models/profile.py | buffer/models/profile.py | import json
from buffer.response import ResponseObject
PATHS = {
'GET_PROFILES': 'profiles.json',
'GET_PROFILE': 'profiles/%s.json',
'GET_SCHEDULES': 'profiles/%s/schedules.json',
'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json'
}
class Profile(ResponseObject):
def __init__(self, api, raw_response)... | import json
from buffer.response import ResponseObject
PATHS = {
'GET_PROFILES': 'profiles.json',
'GET_PROFILE': 'profiles/%s.json',
'GET_SCHEDULES': 'profiles/%s/schedules.json',
'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json'
}
class Profile(ResponseObject):
def __init__(self, api, raw_response)... | Update the schedules times and days | Update the schedules times and days
| Python | mit | vtemian/buffpy,bufferapp/buffer-python | ---
+++
@@ -26,6 +26,18 @@
if hasattr(self, "_get_%s" % name):
return getattr(self, "_get_%s" % name)()
+ def _post_schedules(self, schedules):
+ url = PATHS['UPDATE_SCHEDULES'] % self.id
+
+ data_format = "schedules[0][%s][]=%s&"
+ post_data = ""
+
+ for format_type, values in schedules.it... |
c4406ffae02a4ea87a139b1d67d98d9c0c7a468b | train.py | train.py | import tensorflow as tf
import driving_data
import model
sess = tf.InteractiveSession()
loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
#train over the dataset about 30 ti... | import os
import tensorflow as tf
import driving_data
import model
LOGDIR = './save'
sess = tf.InteractiveSession()
loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
#train... | Add check for folder to save checkpoints | Add check for folder to save checkpoints
| Python | apache-2.0 | tmaila/autopilot,tmaila/autopilot,SullyChen/Autopilot-TensorFlow,tmaila/autopilot | ---
+++
@@ -1,6 +1,9 @@
+import os
import tensorflow as tf
import driving_data
import model
+
+LOGDIR = './save'
sess = tf.InteractiveSession()
@@ -18,5 +21,8 @@
print("step %d, train loss %g"%(i, loss.eval(feed_dict={
model.x:xs, model.y_: ys, model.keep_prob: 1.0})))
if i % 100 == 0:
- ... |
7eedd155f9f6e6361bdfc6fe84311ae38574d3fe | config/fuzzer_params.py | config/fuzzer_params.py | switch_failure_rate = 0.05
switch_recovery_rate = 0.05
dataplane_drop_rate = 0.0
dataplane_delay_rate = 0.0
controlplane_block_rate = 0.0
controlplane_unblock_rate = 1.0
ofp_message_receipt_rate = 1.0
link_failure_rate = 0.05
link_recovery_rate = 0.05
controller_crash_rate = 0.0
controller_recovery_rate = 0.0
traffic_g... | switch_failure_rate = 0.0
switch_recovery_rate = 0.0
dataplane_drop_rate = 0.0
dataplane_delay_rate = 0.0
controlplane_block_rate = 0.0
controlplane_unblock_rate = 1.0
ofp_message_receipt_rate = 1.0
link_failure_rate = 0.0
link_recovery_rate = 0.0
controller_crash_rate = 0.0
controller_recovery_rate = 0.0
traffic_gener... | Set fuzzer params to zero for now | Set fuzzer params to zero for now
| Python | apache-2.0 | jmiserez/sts,ucb-sts/sts,jmiserez/sts,ucb-sts/sts | ---
+++
@@ -1,13 +1,13 @@
-switch_failure_rate = 0.05
-switch_recovery_rate = 0.05
+switch_failure_rate = 0.0
+switch_recovery_rate = 0.0
dataplane_drop_rate = 0.0
dataplane_delay_rate = 0.0
controlplane_block_rate = 0.0
controlplane_unblock_rate = 1.0
ofp_message_receipt_rate = 1.0
-link_failure_rate = 0.05
-li... |
c1f8a586e4e4dcad16c0fc9261f61f93b2488830 | content/test/gpu/gpu_tests/pixel_expectations.py | content/test/gpu/gpu_tests/pixel_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopar... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopar... | Revert 273986 "Remove failing expectations for pixel tests." | Revert 273986 "Remove failing expectations for pixel tests."
Re-enable the failing expectations for the Pixel.CSS3DBlueBox test.
The <meta viewport> tag added to this test is causing failures on some
desktop bots. See Issue 368495.
> Remove failing expectations for pixel tests.
>
> This is a follow-up patch for r273... | Python | bsd-3-clause | M4sse/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,jaruba/chromium.src,ltilve/chromium,littlstar/chromium.src,ltilve/chromium,dushu1203/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,crosswal... | ---
+++
@@ -24,4 +24,6 @@
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
+ self.Fail('Pixel.CSS3DBlueBox', bug=368495)
+
pass |
06356979dd377137c77139c45a0b40deea3f5b27 | tests/test_api.py | tests/test_api.py | import scipy.interpolate
import numpy as np
import naturalneighbor
def test_output_size_matches_scipy():
points = np.random.rand(10, 3)
values = np.random.rand(10)
grid_ranges = [
[0, 4, 0.6], # step isn't a multiple
[-3, 3, 1.0], # step is a multiple
[0, 1, 3], # step is larg... | import scipy.interpolate
import numpy as np
import pytest
import naturalneighbor
@pytest.mark.parametrize("grid_ranges", [
[[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]],
[[0, 2, 1], [0, 2, 1j], [0, 2, 2j]],
])
def test_output_size_matches_scipy(grid_ranges):
points = np.random.rand(10, 3)
values = np.random... | Add test for complex indexing | Add test for complex indexing
| Python | mit | innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation | ---
+++
@@ -1,18 +1,17 @@
import scipy.interpolate
import numpy as np
+import pytest
import naturalneighbor
-def test_output_size_matches_scipy():
+@pytest.mark.parametrize("grid_ranges", [
+ [[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]],
+ [[0, 2, 1], [0, 2, 1j], [0, 2, 2j]],
+])
+def test_output_size_matche... |
9a3b0e2fc81187a0ec91230552552805dc6593e4 | profile_collection/startup/50-scans.py | profile_collection/startup/50-scans.py | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | Move smll and dcm to baseline devices | Move smll and dcm to baseline devices
| Python | bsd-2-clause | NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd | ---
+++
@@ -15,12 +15,12 @@
mesh = hxntools.scans.absolute_mesh
dmesh = hxntools.scans.relative_mesh
-gs.DETS = [zebra, sclr1, merlin1, xspress3, smll, lakeshore2, xbpm, s1]
-gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz',
+gs.DETS = [zebra, sclr1, merlin1, timepix1, ... |
5adfc507d00da4b38486f3bf80880b91828d673e | trac/upgrades/tests/db44.py | trac/upgrades/tests/db44.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists o... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists o... | Remove use of deprecated `assertEquals` | 1.3.2dev: Remove use of deprecated `assertEquals`
git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@15981 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac | ---
+++
@@ -26,7 +26,7 @@
(" t.description AS _description,",
None)]
for query, expected in fragments:
- self.assertEquals(expected, db44.replace_sql_fragment(query))
+ self.assertEqual(expected, db44.replace_sql_fragment(query))
def tes... |
d857c08ce1207c10aaec30878fc119ddacf44363 | tohu/derived_generators.py | tohu/derived_generators.py | from operator import attrgetter
from .base import logger, DependentGenerator
__all__ = ['ExtractAttribute']
class ExtractAttribute(DependentGenerator):
"""
Generator which produces items that are attributes extracted from
the items produced by a different generator.
"""
def __init__(self, g, att... | from operator import attrgetter
from .base import logger, DependentGenerator
__all__ = ['ExtractAttribute', 'Lookup']
class ExtractAttribute(DependentGenerator):
"""
Generator which produces items that are attributes extracted from
the items produced by a different generator.
"""
def __init__(se... | Add generator Lookup which emulates a dictionary lookup for generators | Add generator Lookup which emulates a dictionary lookup for generators
| Python | mit | maxalbert/tohu | ---
+++
@@ -1,7 +1,7 @@
from operator import attrgetter
from .base import logger, DependentGenerator
-__all__ = ['ExtractAttribute']
+__all__ = ['ExtractAttribute', 'Lookup']
class ExtractAttribute(DependentGenerator):
@@ -26,3 +26,21 @@
def __next__(self):
return self.attrgetter(next(self.ge... |
2d7c286321683a9d3241d0e923f1f182adfd84be | sr/templatetags/sr.py | sr/templatetags/sr.py | from django import template
register = template.Library()
from .. import sr as sr_func
@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
return sr_func(key, *args, **kwargs)
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sr", sr_... | from django import template
register = template.Library()
from .. import sr as sr_func
@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
return sr_func(key, *args, **kwargs)
try:
from django_jinja import library as jinja_library
jinja_library.global_function("sr", sr_func)
except ImportE... | Update support for new django-jinja versions. (backward incompatible) | Update support for new django-jinja versions. (backward incompatible)
| Python | bsd-3-clause | jespino/django-sr | ---
+++
@@ -7,10 +7,9 @@
def sr_tag(key, *args, **kwargs):
return sr_func(key, *args, **kwargs)
+
try:
- from django_jinja.base import Library
- jinja_register = Library()
-
- jinja_register.global_function("sr", sr_func)
+ from django_jinja import library as jinja_library
+ jinja_library.glob... |
60ef934e3bef7c00fc2d1823901babb665a4888f | get_study_attachments.py | get_study_attachments.py | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
study_files = []
for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'):
study_files.append(key)
return study_files
if __na... | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}')
if __name__ == '__main__':
study_uuid = sys.argv[1]
get_study_keys(study_uuid)
| Remove looping through items and appending them to list. | Remove looping through items and appending them to list.
| Python | apache-2.0 | CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api | ---
+++
@@ -5,12 +5,8 @@
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
-
bucket = s3.Bucket(BUCKET_NAME)
- study_files = []
- for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'):
- study_files.append(key)
- return study_files
+ return bucket.obje... |
16c372c905f44608a1d1ccabb949ad9cb736dae6 | tileserver.py | tileserver.py | import logging
import os
import json
import TileStache
if 'AWS_ACCESS_KEY_ID' in os.environ and \
'AWS_SECRET_ACCESS_KEY' in os.environ:
cache = {
"name": "S3",
"bucket": "telostats-tiles",
"access": os.environ['AWS_ACCESS_KEY_ID'],
"secret": os.environ['AWS_... | import logging
import os
import json
import TileStache
if 'AWS_ACCESS_KEY_ID' in os.environ and \
'AWS_SECRET_ACCESS_KEY' in os.environ:
cache = {
"name": "S3",
"bucket": "telostats-tiles",
"access": os.environ['AWS_ACCESS_KEY_ID'],
"secret": os.environ['AWS_... | Switch to memcachier dev plan | Switch to memcachier dev plan
| Python | bsd-3-clause | idan/telostats-tiles | ---
+++
@@ -16,10 +16,10 @@
cache = {"name": "Test"}
cache = {
- 'name': 'memcache',
- 'servers': [os.environ.get('MEMCACHE_SERVERS')],
- 'username': os.environ.get('MEMCACHE_USERNAME'),
- 'password': os.environ.get('MEMCACHE_PASSWORD'),
+ 'name': 'Memcache',
+ 'servers': [os.environ.get('MEMCACHIER_SER... |
4bfa74aa2ea9ef936d5ec5efbf32f2d6a8a10634 | adr/recipes/config_durations.py | adr/recipes/config_durations.py | """
Get the average and total runtime for build platforms and types.
.. code-block:: bash
adr config_durations [--branch <branch>]
"""
from __future__ import absolute_import, print_function
from ..query import run_query
def run(config, args):
# process config data
data = run_query('config_durations', c... | """
Get the average and total runtime for build platforms and types.
.. code-block:: bash
adr config_durations [--branch <branch>]
"""
from __future__ import absolute_import, print_function
from ..query import run_query
BROKEN = True
def run(config, args):
# process config data
data = run_query('confi... | Disable failing recipe in CRON tests | Disable failing recipe in CRON tests
| Python | mpl-2.0 | ahal/active-data-recipes,ahal/active-data-recipes | ---
+++
@@ -8,6 +8,8 @@
from __future__ import absolute_import, print_function
from ..query import run_query
+
+BROKEN = True
def run(config, args): |
ba75572bd7de9a441cad72fe90d7ec233e9c1a15 | test/adapt.py | test/adapt.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="... | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="... | Fix test failing on python 3 | Fix test failing on python 3
| Python | apache-2.0 | kovidgoyal/html5-parser,kovidgoyal/html5-parser | ---
+++
@@ -33,4 +33,4 @@
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
- self.assertIn('<!-- A -- comment --->', tostring(root))
+ self.assertIn('<!-- A -- comment --->', tostr... |
9ca0549ceff05f9f8a391c8ec2b685af48c0a5a8 | scripts/common.py | scripts/common.py | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... | Define variables for the DB name, host, etc. so they can be imported | Define variables for the DB name, host, etc. so they can be imported
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID | ---
+++
@@ -19,7 +19,13 @@
password: password_of_your_catmaid_user''' % (path,)
sys.exit(1)
-db_connection = psycopg2.connect(host=conf['host'],
- database=conf['database'],
- user=conf['username'],
- password=conf... |
a26dc400c479572be59bfe90d8e809d2e9e65a63 | python_humble_utils/pytest_commands.py | python_humble_utils/pytest_commands.py | import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path rooted in a temporary dir.
:param tmpdir_factory: py.test's tmpdir_factory fixture.
:param file_name_with_... | import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path relative to a temporary directory.
:param tmpdir_factory: py.test's `tmpdir_factory` fixture.
:param file_... | Improve generate_tmp_file_path pytest command docs | Improve generate_tmp_file_path pytest command docs
| Python | mit | webyneter/python-humble-utils | ---
+++
@@ -5,13 +5,12 @@
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
- Generate file path rooted in a temporary dir.
+ Generate file path relative to a temporary directory.
- :param tmpdir_factory: py.test's tmpdir_facto... |
058e2e75384052dcc2b90690cef695e4533eb854 | scripts/insert_demo.py | scripts/insert_demo.py | """Insert the demo into the codemirror site."""
from __future__ import print_function
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os... | """Insert the demo into the codemirror site."""
from __future__ import print_function
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os... | Delete live writing demo before loading new one | Delete live writing demo before loading new one
| Python | bsd-3-clause | jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,jstewmon/proselint | ---
+++
@@ -16,6 +16,8 @@
live_write_path = os.path.join(proselint_path, "site", "write")
+if os.path.exists(live_write_path):
+ shutil.rmtree(live_write_path)
shutil.copytree(code_mirror_path, live_write_path)
demo_path = os.path.join(proselint_path, "proselint", "demo.md") |
6620032e9f8574c3e1dad37c111040eca570a751 | features/memberships/models.py | features/memberships/models.py | from django.contrib.contenttypes import fields as contenttypes
from django.db import models
class Membership(models.Model):
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('grou... | from django.contrib.contenttypes import fields as contenttypes
from django.db import models
from . import querysets
class Membership(models.Model):
class Meta:
unique_together = ('group', 'member')
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
... | Add queryset for ordering memberships by activity | Add queryset for ordering memberships by activity
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten | ---
+++
@@ -1,22 +1,26 @@
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
+from . import querysets
+
class Membership(models.Model):
+ class Meta:
+ unique_together = ('group', 'member')
+
created_by = models.ForeignKey(
'gestalten.Gestalt... |
13301dfe93bcdd44218166bdab1c7aeacd4e4a7c | winthrop/annotation/models.py | winthrop/annotation/models.py | from urllib.parse import urlparse
from django.db import models
from django.urls import resolve, Resolver404
from annotator_store.models import BaseAnnotation
from djiffy.models import Canvas
from winthrop.people.models import Person
class Annotation(BaseAnnotation):
# NOTE: do we want to associate explicitly with... | from urllib.parse import urlparse
from django.db import models
from django.urls import resolve, Resolver404
from annotator_store.models import BaseAnnotation
from djiffy.models import Canvas
from winthrop.people.models import Person
class Annotation(BaseAnnotation):
# NOTE: do we want to associate explicitly with... | Add author field & autocomplete to annotation model+interface | Add author field & autocomplete to annotation model+interface
| Python | apache-2.0 | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django | ---
+++
@@ -19,21 +19,38 @@
return info
def save(self, *args, **kwargs):
- # NOTE: could set the canvas uri in javascript instead
- # of using page uri, but for now determine canvas id
- # based on the page uri
+ # for image annotation, URI should be set to canvas URI; look... |
045ead44ef69d6ebf2cb0dddf084762efcc62995 | handlers/base_handler.py | handlers/base_handler.py | from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
| from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
if offset < 0:
raise IndexError("File offset must be greater than 0")
... | Add bounds checking to BaseHandler.read() | Add bounds checking to BaseHandler.read()
| Python | mit | drx/rom-info | ---
+++
@@ -8,4 +8,10 @@
self.info = OrderedDict()
def read(self, offset, size):
+ if offset < 0:
+ raise IndexError("File offset must be greater than 0")
+
+ if offset + size >= len(self.file):
+ raise IndexError("Cannot read beyond the end of the file")
+
... |
7d4b58da2fd5040052ce2d7be924f1fd34be4ee7 | picaxe/local_settings_example.py | picaxe/local_settings_example.py | __author__ = 'peter'
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... | __author__ = 'peter'
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Turn debugging off for production environments!
DEBUG = False
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'd... | Add debugging setting to local_settings | Add debugging setting to local_settings
| Python | mit | TuinfeesT/PicAxe | ---
+++
@@ -3,6 +3,9 @@
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
+
+# Turn debugging off for production environments!
+DEBUG = False
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases |
d153696d44220523d072653b9ff0f0d01eef325f | django_enum_js/__init__.py | django_enum_js/__init__.py | import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] ==... | import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
return enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict... | Allow using register_enum as a decorator | Allow using register_enum as a decorator
By returning the original class instance, it'd be possible to use `enum_wrapper.register_enum` as a decorator, making the usage cleaner while staying backwards compatible:
```python
@enum_wrapper.register_enum
class MyAwesomeClass:
pass
``` | Python | mit | leifdenby/django_enum_js | ---
+++
@@ -6,6 +6,7 @@
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
+ return enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) |
6dcb33004c3775d707f362a6f2c8217c1d558f56 | kobin/server_adapters.py | kobin/server_adapters.py | from typing import Dict, Any
class ServerAdapter:
quiet = False
def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None:
self.options = options
self.host = host
self.port = int(port)
def run(self, handler):
pass
def __repr__(self):
args =... | from typing import Dict, Any
class ServerAdapter:
quiet = False
def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None:
self.options = options
self.host = host
self.port = int(port)
def run(self, handler):
pass
def __repr__(self):
args =... | Add a gunicorn server adpter | Add a gunicorn server adpter
| Python | mit | kobinpy/kobin,kobinpy/kobin,c-bata/kobin,c-bata/kobin | ---
+++
@@ -30,6 +30,24 @@
self.httpd.server_close()
raise
+
+class GunicornServer(ServerAdapter):
+ def run(self, handler):
+ from gunicorn.app.base import Application
+
+ config = {'bind': "%s:%d" % (self.host, int(self.port))}
+ config.update(self.options)
+
+ ... |
b7486b64cabc0ad4c022a520bb630fb88cb35e53 | feincms/content/raw/models.py | feincms/content/raw/models.py | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django import forms
class RawContent(models.Model):
text = models.TextField(_('content'), blank=True)
class Meta:
abstract = True
verbose_name = _('raw conte... | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django import forms
class RawContent(models.Model):
text = models.TextField(_('content'), blank=True)
class Meta:
abstract = True
verbose_name = _('raw conte... | Remove test content type media from RawContent | Remove test content type media from RawContent
| Python | bsd-3-clause | feincms/feincms,joshuajonah/feincms,pjdelport/feincms,feincms/feincms,matthiask/django-content-editor,joshuajonah/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,mjl/feincms,joshuajonah/feincms,matthiask/django-content-editor,nickburlett/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickbur... | ---
+++
@@ -12,13 +12,6 @@
verbose_name = _('raw content')
verbose_name_plural = _('raw contents')
- @property
- def media(self):
- return forms.Media(
- css={'all': ('whatever.css',)},
- js=('something.js',),
- )
-
def render(self, **kwargs):
... |
34be718d554b7a1563e253710bc6d70cd81d77bd | normandy/recipes/validators.py | normandy/recipes/validators.py | import json
import jsonschema
from django.core.exceptions import ValidationError
# Add path to required validator so we can get property name
def _required(validator, required, instance, schema):
'''Validate 'required' properties.'''
if not validator.is_type(instance, 'object'):
return
for index... | import json
import jsonschema
from django.core.exceptions import ValidationError
# Add path to required validator so we can get property name
def _required(validator, required, instance, schema):
"""Validate 'required' properties."""
if not validator.is_type(instance, 'object'):
return
for index... | Use triple double quotes rather than single | Use triple double quotes rather than single
| Python | mpl-2.0 | mozilla/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy | ---
+++
@@ -6,7 +6,7 @@
# Add path to required validator so we can get property name
def _required(validator, required, instance, schema):
- '''Validate 'required' properties.'''
+ """Validate 'required' properties."""
if not validator.is_type(instance, 'object'):
return
|
64636185744a9a64b1b04fcd81ee32930bb145af | scores.py | scores.py | from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_service = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_service.get_players()
return sorted(players, key=lambda player: player.score, reverse=True)
| from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
... | Add method to update a player's score | Add method to update a player's score
| Python | mit | radekj/poke-battle,skooda/poke-battle | ---
+++
@@ -4,9 +4,15 @@
class ScoreService(object):
name = 'score_service'
- player_service = RpcProxy('players_service')
+ player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
- players = self.player_service.get_players()
- return sorted(players, key=lambda pl... |
3f41dc9ee418c76548f1d69482bc3117739697fe | signbank/video/urls.py | signbank/video/urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import path
# Views
from . import views
# Application namespace
app_name = 'video'
urlpatterns = [
path('<intvideoid>/', views.video_view, name='glossvideo'),
path('poster/<int:videoid>', views.poster_view, name='glossvideo_post... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import path
# Views
from . import views
# Application namespace
app_name = 'video'
urlpatterns = [
path('<int:videoid>/', views.video_view, name='glossvideo'),
path('poster/<int:videoid>', views.poster_view, name='glossvideo_pos... | Fix missing colon in video url | Fix missing colon in video url
| Python | bsd-3-clause | Signbank/FinSL-signbank,Signbank/FinSL-signbank,Signbank/FinSL-signbank | ---
+++
@@ -9,7 +9,7 @@
app_name = 'video'
urlpatterns = [
- path('<intvideoid>/', views.video_view, name='glossvideo'),
+ path('<int:videoid>/', views.video_view, name='glossvideo'),
path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'),
path('upload/', views.upload_glossvideo... |
39ba5da2f6e80bc78ca061edb34c8a2dd7e9c199 | shortwave/urls.py | shortwave/urls.py | from django.conf.urls.defaults import *
from shortwave.views import wave_list, wave_detail
urlpatterns = patterns('',
url(r'^$', wave_list, name='shortwave-wave-list'),
url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail'),
)
| from django.conf.urls.defaults import *
from shortwave.views import wave_list, wave_detail
urlpatterns = patterns('',
url(r'^$',
wave_list,
name='shortwave-wave-list',
),
url(r'^(?P<username>[-\w]+)/$',
wave_detail,
name='shortwave-wave-detail',
),
)
| Format URL patterns into more readable form. | Format URL patterns into more readable form.
| Python | bsd-3-clause | benspaulding/django-shortwave | ---
+++
@@ -4,6 +4,12 @@
urlpatterns = patterns('',
- url(r'^$', wave_list, name='shortwave-wave-list'),
- url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail'),
+ url(r'^$',
+ wave_list,
+ name='shortwave-wave-list',
+ ),
+ url(r'^(?P<username>[-\w]+)/$',
+ ... |
ddf87057213c1068eaf81c47796eb5f77be310b2 | docs/src/examples/over2.py | docs/src/examples/over2.py | import numpy as np
from scikits.audiolab import Format, Sndfile
filename = 'foo.wav'
# Create some data to save as audio data: one second of stereo white noise
data = np.random.randn(48000, 2)
# Create a Sndfile instance for writing wav files @ 48000 Hz
format = Format('wav')
f = Sndfile(filename, 'w', format, 2, 48... | import numpy as np
from scikits.audiolab import Format, Sndfile
filename = 'foo.wav'
# Create some data to save as audio data: one second of stereo white noise
data = np.random.randn(48000, 2)
# Create a Sndfile instance for writing wav files @ 48000 Hz
format = Format('wav')
f = Sndfile(filename, 'w', format, 2, 48... | Update example to new write_frames API. | Update example to new write_frames API.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab | ---
+++
@@ -10,9 +10,9 @@
format = Format('wav')
f = Sndfile(filename, 'w', format, 2, 48000)
-# Write the first 500 frames of the signal Note that the write_frames method
+# Write the first 500 frames of the signal. Note that the write_frames method
# uses tmp's numpy dtype to determine how to write to the file... |
071f42389aef9c57cb4f0a0434d8297ccba05ab2 | openquake/hazardlib/general.py | openquake/hazardlib/general.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014, GEM Foundation.
#
# OpenQuake 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, ... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014, GEM Foundation.
#
# OpenQuake 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, ... | Replace subprocess.Popen with check_output to avoid git zombies | Replace subprocess.Popen with check_output to avoid git zombies
| Python | agpl-3.0 | larsbutler/oq-hazardlib,larsbutler/oq-hazardlib,gem/oq-engine,gem/oq-hazardlib,mmpagani/oq-hazardlib,gem/oq-engine,gem/oq-engine,mmpagani/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-engine,larsbutler/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,vup1120/oq-hazardli... | ---
+++
@@ -26,9 +26,9 @@
:returns: `<short git hash>` if Git repository found
"""
try:
- po = subprocess.Popen(
- ['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE,
- stderr=open(os.devnull, 'w'), cwd=os.path.dirname(fname))
+ po = subprocess.check_out... |
da51cd8b14231a3fa9850d0d1b939168ae7b0534 | sites/shared_conf.py | sites/shared_conf.py | from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementati... | from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementati... | Update to new alabaster-driven nav sidebar | Update to new alabaster-driven nav sidebar
| Python | lgpl-2.1 | jorik041/paramiko,anadigi/paramiko,toby82/paramiko,zarr12steven/paramiko,mirrorcoder/paramiko,paramiko/paramiko,varunarya10/paramiko,redixin/paramiko,zpzgone/paramiko,davidbistolas/paramiko,mhdaimi/paramiko,torkil/paramiko,digitalquacks/paramiko,fvicente/paramiko,dlitz/paramiko,thisch/paramiko,jaraco/paramiko,dorianpul... | ---
+++
@@ -17,21 +17,18 @@
'gittip_user': 'bitprophet',
'analytics_id': 'UA-18486793-2',
+ 'extra_nav_links': {
+ "API Docs": 'http://docs.paramiko.org',
+ },
+
'link': '#3782BE',
'link_hover': '#3782BE',
}
html_sidebars = {
- # Landing page (no ToC)
- 'index': [
- ... |
6c645b69b91b6a29d4e8786c07e6438d16667415 | emds/formats/exceptions.py | emds/formats/exceptions.py | """
Various parser-related exceptions.
"""
class ParseError(Exception):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| """
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError
class ParseError(EMDSError):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| Make ParseError a child of EMDSError. | Make ParseError a child of EMDSError.
| Python | mit | gtaylor/EVE-Market-Data-Structures | ---
+++
@@ -1,8 +1,9 @@
"""
Various parser-related exceptions.
"""
+from emds.exceptions import EMDSError
-class ParseError(Exception):
+class ParseError(EMDSError):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data. |
955fd5b8525e7edd6477d5f74d7cbe7b743a127c | wind_model.py | wind_model.py | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | Set depth for Lake Superior | Set depth for Lake Superior
| Python | bsd-3-clause | kjordahl/swm | ---
+++
@@ -5,7 +5,7 @@
Kelsey Jordahl
kjordahl@enthought.com
-Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
+Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
@@ -25,6 +25,7 @@
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latit... |
70f5669bd0ec39bbb8e785b7306ef97b646c8aae | helga_prod_fixer.py | helga_prod_fixer.py | import random
from helga.plugins import command
RESPONSES = [
'There is no hope for {thing}, {nick}',
'It looks ok to me...',
'Turning {thing} off and back on again',
'I really wish I could, but it looks past the point of no return',
]
@command('fix', help='Usage: helga fix <thing>')
def fix(client... | import random
from helga.plugins import command
RESPONSES = [
'There is no hope for {thing}, {nick}',
'It looks ok to me...',
'Turning {thing} off and back on again',
'I really wish I could, but it looks past the point of no return',
]
@command('fix', help='Usage: helga fix <thing>')
def fix(client... | Join with a space, duh | Join with a space, duh
| Python | mit | shaunduncan/helga-prod-fixer | ---
+++
@@ -13,4 +13,4 @@
@command('fix', help='Usage: helga fix <thing>')
def fix(client, channel, nick, message, cmd, args):
- return random.choice(RESPONSES).format(nick=nick, thing=''.join(args))
+ return random.choice(RESPONSES).format(nick=nick, thing=' '.join(args)) |
181da4be123dd63135592580f8fb567d5586d24b | apps/accounts/models.py | apps/accounts/models.py | from apps.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_le... | from apps.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_le... | Add deprecated field in students | Add deprecated field in students
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr | ---
+++
@@ -19,6 +19,7 @@
other_announcements = models.TextField(null = True, blank = True)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
+ deprecated = models.BooleanField(default = False)
def __unicode__(self):
return... |
c94f7e5f2c838c3fdd007229175da680de256b04 | tests/configurations/nginx/tests_file_size_limit.py | tests/configurations/nginx/tests_file_size_limit.py | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... | Revert "Hago un strip del output de subprocess" | Revert "Hago un strip del output de subprocess"
This reverts commit f5f21d78d87be641617a7cb920d0869975175e58.
| Python | mit | datosgobar/portal-andino,datosgobar/portal-andino | ---
+++
@@ -12,8 +12,6 @@
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(self):
- size_line = subprocess.check_output('docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf | '
- 'grep ... |
1a271575d92a6d7df1bc7dedf346b29a778f2261 | update.py | update.py | """DJRivals database updater."""
from random import shuffle
from time import localtime, sleep, strftime, time
import pop
import dj
import image
import html
def continuous():
"""continuous() -> None
Continuous incremental updates of the DJRivals database.
"""
while(True):
print("Beginning ne... | """DJRivals database updater."""
from collections import OrderedDict
from time import localtime, sleep, strftime, time
import json
from common import _link
import pop
import dj
import image
import html
def continuous():
"""continuous() -> None
Continuous incremental updates of the DJRivals database.
""... | Sort the disc list by timestamp. | Sort the disc list by timestamp.
| Python | bsd-2-clause | chingc/DJRivals,chingc/DJRivals | ---
+++
@@ -1,7 +1,9 @@
"""DJRivals database updater."""
-from random import shuffle
+from collections import OrderedDict
from time import localtime, sleep, strftime, time
+import json
+from common import _link
import pop
import dj
import image
@@ -14,13 +16,19 @@
Continuous incremental updates of the DJR... |
b4a0f37c22f69da352ae178da78eb99c97a757d5 | zou/app/utils/csv_utils.py | zou/app/utils/csv_utils.py | try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import csv
from zou.app import config
from flask import make_response
from slugify import slugify
def build_csv_response(csv_content, file_name="export"):
"""
Construct a Flask response that returns content of a csv a file... | try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import csv
from zou.app import config
from flask import make_response
from slugify import slugify
def build_csv_response(csv_content, file_name="export"):
"""
Construct a Flask response that returns content of a csv a file... | Fix non unicode chars problem | Fix non unicode chars problem
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -33,7 +33,7 @@
def build_csv_string(csv_content):
"""
- Build a CSV formatted string from an array.
+ Build a CSV formatted string from an array.
"""
string_wrapper = StringIO()
csv_writer = csv.writer(string_wrapper)
@@ -43,7 +43,7 @@
def build_csv_headers(csv_response, fil... |
b2b1c2b8543cae37990262b2a811a9b0f26327da | arm/utils/locker.py | arm/utils/locker.py | # -*- coding: utf-8 -*-
from kvs import CacheKvs
class Locker(object):
"""
locker for move the locker
"""
LOCKER_KEY = 'locker'
EXPIRES = 5 # 5 sec
def __init__(self, key=None):
self.key = self.LOCKER_KEY
if key:
self.key += '.{}'.format(key)
self.locker ... | # -*- coding: utf-8 -*-
from kvs import CacheKvs
class Locker(object):
"""
locker for move the locker
"""
LOCKER_KEY = 'locker'
EXPIRES = 5 # 5 sec
def __init__(self, key=None):
self.key = self.LOCKER_KEY
if key:
self.key += '.{}'.format(key)
self.locker ... | Fix redis lock, use SETNX | Fix redis lock, use SETNX
| Python | mit | mapler/tuesday,mapler/tuesday,mapler/tuesday | ---
+++
@@ -27,13 +27,11 @@
def on_lock(self, func):
def wrapper(*args, **kwargs):
- if self.is_lock():
- return
- self.lock()
- try:
- return func(*args, **kwargs)
- except Exception as e:
- raise e
- ... |
34ea2629aa8a97580567535a5a6885b06cce3419 | examples/test_client.py | examples/test_client.py | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... | Use asyncio.run() to run the test client. | Use asyncio.run() to run the test client.
This makes for cleaner code.
| Python | lgpl-2.1 | katajakasa/aiohttp-spyne | ---
+++
@@ -36,15 +36,14 @@
print(delta_time)
-def main():
- loop = asyncio.get_event_loop()
+async def main():
client = AsyncClient(
wsdl="http://localhost:8080/say_hello/?WSDL",
transport=AsyncTransport(cache=InMemoryCache(timeout=None)),
)
- loop.run_until_complete(send_m... |
07488d90549db4a47898bdea4ebd8687de638590 | forum/models.py | forum/models.py | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | Add footers the comment discusses. | Add footers the comment discusses.
| Python | mit | xfix/NextBoard | ---
+++
@@ -8,6 +8,7 @@
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
+ footer = models.TextField(null=True)
class Thread(models.Model): |
22b92437c1ae672297bed8567b335ef7da100103 | dotfiles/utils.py | dotfiles/utils.py | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | Fix link detection when target is itself a symlink | Fix link detection when target is itself a symlink
This shows up on OSX where /tmp is actually a symlink to /private/tmp.
| Python | isc | aparente/Dotfiles,nilehmann/dotfiles-1,aparente/Dotfiles,aparente/Dotfiles,aparente/Dotfiles,Bklyn/dotfiles | ---
+++
@@ -19,5 +19,4 @@
def normalize(path):
return os.path.normcase(os.path.normpath(path))
return islink(path) and \
- normalize(realpath(path)) == normalize(target)
-
+ normalize(realpath(path)) == normalize(realpath(target)) |
1fa7237f47096bc9574ffdf649e6231bf2a670e9 | features/stadt/views.py | features/stadt/views.py | import django
import utils
from features import gestalten, groups
class Entity(django.views.generic.View):
def get(self, request, *args, **kwargs):
try:
entity = groups.models.Group.objects.get(slug=kwargs.get('entity_slug'))
view = groups.views.Group()
except groups.model... | import django
import core
import utils
from features import gestalten, groups
class Entity(core.views.PermissionMixin, django.views.generic.View):
def get(self, request, *args, **kwargs):
return self.view.get(request, *args, **kwargs)
def get_view(self):
entity_slug = self.kwargs.get('entity... | Fix permission checking for entity proxy view | Fix permission checking for entity proxy view
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten | ---
+++
@@ -1,22 +1,32 @@
import django
+import core
import utils
from features import gestalten, groups
-class Entity(django.views.generic.View):
+class Entity(core.views.PermissionMixin, django.views.generic.View):
def get(self, request, *args, **kwargs):
+ return self.view.get(request, *args, ... |
7ffdd38b500b38d6bd48ca7f1bf88fb92c88e1d5 | prime-factors/prime_factors.py | prime-factors/prime_factors.py | def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
| def prime_factors(n):
factors = []
while n % 2 == 0:
factors += [2]
n //= 2
factor = 3
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 2
return factors
| Make solution more efficient by only testing odd numbers | Make solution more efficient by only testing odd numbers
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,9 +1,12 @@
def prime_factors(n):
factors = []
- factor = 2
+ while n % 2 == 0:
+ factors += [2]
+ n //= 2
+ factor = 3
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
- factor += 1
+ factor += 2
... |
6b7fe344827ddf49c40d165d6e0ff09013ee5716 | edxval/migrations/0002_data__default_profiles.py | edxval/migrations/0002_data__default_profiles.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
DEFAULT_PROFILES = [
"desktop_mp4",
"desktop_webm",
"mobile_high",
"mobile_low",
"youtube",
]
def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile =... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
DEFAULT_PROFILES = [
"desktop_mp4",
"desktop_webm",
"mobile_high",
"mobile_low",
"youtube",
]
def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile =... | Remove uses of using() from migrations | Remove uses of using() from migrations
This hardcoded the db_alias fetched from schema_editor and forces django
to try and migrate any second database you use, rather than routing to
the default database. In testing a build from scratch, these do not
appear needed.
Using using() prevents us from using multiple datab... | Python | agpl-3.0 | edx/edx-val | ---
+++
@@ -16,16 +16,14 @@
def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile = apps.get_model("edxval", "Profile")
- db_alias = schema_editor.connection.alias
for profile in DEFAULT_PROFILES:
- Profile.objects.using(db_alias).get_or_create(profile_name=p... |
78031ca1077a224d37c4f549cd8dac55edd4ed5f | fragdenstaat_de/urls.py | fragdenstaat_de/urls.py | from django.conf.urls.defaults import patterns
urlpatterns = patterns('fragdenstaat_de.views',
(r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'),
)
| from django.conf.urls import patterns, url
from django.http import HttpResponseRedirect
urlpatterns = patterns('fragdenstaat_de.views',
(r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'),
url(r'^nordrhein-westfalen/', lambda request: HttpResponseRedirect('/nrw/'),
name="jurisdiction-n... | Add custom NRW redirect url | Add custom NRW redirect url | Python | mit | okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de,okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de | ---
+++
@@ -1,6 +1,9 @@
-from django.conf.urls.defaults import patterns
+from django.conf.urls import patterns, url
+from django.http import HttpResponseRedirect
urlpatterns = patterns('fragdenstaat_de.views',
(r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'),
+ url(r'^nordrhein-westfal... |
185571932f518760bb3045347578caa98ef820f5 | froide/foiidea/views.py | froide/foiidea/views.py | from django.shortcuts import render
from foiidea.models import Article
def index(request):
return render(request, 'foiidea/index.html', {
'object_list': Article.objects.all().select_related('public_bodies', 'foirequests')
})
| from django.shortcuts import render
from foiidea.models import Article
def index(request):
return render(request, 'foiidea/index.html', {
'object_list': Article.objects.get_ordered()
})
| Use manager method for view articles | Use manager method for view articles | Python | mit | fin/froide,LilithWittmann/froide,stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,okfse/froide,okfse/froide,ryankanno/froide,ryankanno/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,fin/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/... | ---
+++
@@ -5,5 +5,5 @@
def index(request):
return render(request, 'foiidea/index.html', {
- 'object_list': Article.objects.all().select_related('public_bodies', 'foirequests')
+ 'object_list': Article.objects.get_ordered()
}) |
52e15ab96718a491f805eee6f7130d4f02530940 | alfred/helpers.py | alfred/helpers.py | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... | Add user to db.session only when it has been created | Add user to db.session only when it has been created
| Python | isc | alfredhq/alfred,alfredhq/alfred | ---
+++
@@ -37,9 +37,9 @@
email=github_user.email,
login=github_user.login,
)
+ db.session.add(user)
else:
user.github_access_token = access_token
user.login = github_user.login
- db.session.add(user)
db.session.commit()
return user |
8dba7306f73479fb3c0a102550f843e2fb9ea1c1 | serfnode/handler/docker_utils.py | serfnode/handler/docker_utils.py | import os
import subprocess
def env(image):
"""Return environment of image. """
out = docker('inspect', '-f', '{{.Config.Env}}', image)
return dict(map(lambda x: x.split('='), out.strip()[1:-1].split()))
def path(p):
"""Build the corresponding path `p` inside the container. """
return os.path.... | import os
import subprocess
def env(image):
"""Return environment of image. """
out = docker('inspect', '-f', '{{.Config.Env}}', image)
return dict(map(lambda x: x.split('='), out.strip()[1:-1].split()))
def path(p):
"""Build the corresponding path `p` inside the container. """
return os.path.... | Fix template for docker command line | Fix template for docker command line
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode | ---
+++
@@ -21,7 +21,7 @@
docker_binary = DOCKER
docker_socket = DOCKER_SOCKET
- cmd = ('{docker_binary} -H unix://{docker_socket}'
+ cmd = ('{docker_binary} -H {docker_socket}'
.format(**locals()).split())
cmd.extend(args)
return subprocess.check_output(cmd).strip() |
81e8fb8dd4f9f3d3648e13e8509208710619c615 | IMU_program/PythonServer.py | IMU_program/PythonServer.py | import socket
import serial.tools.list_ports
import serial
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
# print("Connecting on " + arduino_port[0])
PORT = 4242
HOST = 'localhost'
... | #!/usr/bin/env python3
import socket
import serial.tools.list_ports
import serial
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
# print("Connecting on " + arduino_port[0])
PORT = 4... | Add shebang to python server | Add shebang to python server
| Python | apache-2.0 | dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo | ---
+++
@@ -1,7 +1,8 @@
+#!/usr/bin/env python3
+
import socket
import serial.tools.list_ports
import serial
-
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None) |
3fa9a7c62aeae10a191b3782e32df107618c19b3 | boris/reporting/forms.py | boris/reporting/forms.py | '''
Created on 3.12.2011
@author: xaralis
'''
from django import forms
from django.utils.translation import ugettext_lazy as _
from boris.utils.widgets import SelectYearWidget
class MonthlyStatsForm(forms.Form):
year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok'))
class ServiceForm(fo... | '''
Created on 3.12.2011
@author: xaralis
'''
from django import forms
from django.utils.translation import ugettext_lazy as _
from boris.utils.widgets import SelectYearWidget
class MonthlyStatsForm(forms.Form):
year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok'))
class ServiceForm(fo... | Make dates in the ServiceForm optional. | Make dates in the ServiceForm optional.
| Python | mit | fragaria/BorIS,fragaria/BorIS,fragaria/BorIS | ---
+++
@@ -12,5 +12,5 @@
year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok'))
class ServiceForm(forms.Form):
- date_from = forms.DateField(label=_(u'Od'))
- date_to = forms.DateField(label=_(u'Do'))
+ date_from = forms.DateField(label=_(u'Od'), required=False)
+ date_to... |
70a004f1455448aca08754084502d4d13b9cc9cd | indra/tests/test_rlimsp.py | indra/tests/test_rlimsp.py | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_pmc('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations, "Missing a... | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... | Add a test for pmids and update to new api. | Add a test for pmids and update to new api.
| Python | bsd-2-clause | johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra | ---
+++
@@ -2,7 +2,7 @@
def test_simple_usage():
- rp = rlimsp.process_pmc('PMC3717945')
+ rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
@@ -14,5 +14,13 @@
def test_ungrounded_usage():
- rp = rlimsp.process_... |
4a6fe04a93e0d500b9e2fa7ed9951bcb497045df | sphinxcontrib/dd/__init__.py | sphinxcontrib/dd/__init__.py | from docutils.nodes import SkipNode
from . import data_dictionary
from . import database_diagram
def skip(self, node):
_ = self
_ = node
raise SkipNode
def setup(app):
app.setup_extension('sphinx.ext.graphviz')
app.add_directive('data-dictionary', data_dictionary.Directive)
app.add_config... | from docutils.nodes import SkipNode
from . import data_dictionary
from . import database_diagram
def skip(self, node):
_ = self
_ = node
raise SkipNode
def setup(app):
app.setup_extension('sphinx.ext.graphviz')
app.add_directive('data-dictionary', data_dictionary.Directive)
for option in ... | Replace dash to underscore for config | Replace dash to underscore for config
| Python | mit | julot/sphinxcontrib-dd | ---
+++
@@ -15,12 +15,9 @@
app.add_directive('data-dictionary', data_dictionary.Directive)
- app.add_config_value('database_diagram_graph_fontname', '', 'env')
- app.add_config_value('database_diagram_graph_fontsize', '', 'env')
- app.add_config_value('database_diagram_graph_label', '', 'env')
-
- ... |
9201e9c433930da8fd0bfb13eadbc249469e4d84 | fireplace/cards/tourney/mage.py | fireplace/cards/tourney/mage.py | from ..utils import *
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
)
| from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Ar... | Implement Mage cards for The Grand Tournament | Implement Mage cards for The Grand Tournament
| Python | agpl-3.0 | Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,smallnamespace/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace | ---
+++
@@ -1,4 +1,40 @@
from ..utils import *
+
+
+##
+# Minions
+
+# Dalaran Aspirant
+class AT_006:
+ inspire = Buff(SELF, "AT_006e")
+
+
+# Spellslinger
+class AT_007:
+ play = Give(ALL_PLAYERS, RandomSpell())
+
+
+# Rhonin
+class AT_009:
+ deathrattle = Give(CONTROLLER, "EX1_277") * 3
+
+
+##
+# Spells
+
+# Fla... |
52a9d0701f7ccc6e5ab12bf2c83473d878b80ee0 | src/file_types.py | src/file_types.py | import build_inputs
from path import Path
class SourceFile(build_inputs.File):
def __init__(self, name, source=Path.srcdir, lang=None):
build_inputs.File.__init__(self, name, source=source)
self.lang = lang
class HeaderFile(build_inputs.File):
install_kind = 'data'
install_root = Path.incl... | import build_inputs
from path import Path
class SourceFile(build_inputs.File):
def __init__(self, name, source=Path.srcdir, lang=None):
build_inputs.File.__init__(self, name, source=source)
self.lang = lang
class HeaderFile(build_inputs.File):
install_kind = 'data'
install_root = Path.incl... | Update comments on the built-in file types | Update comments on the built-in file types
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 | ---
+++
@@ -37,11 +37,13 @@
class SharedLibrary(Library):
pass
-# Used for Windows DLL files, which aren't linked to directly.
+# Used for Windows DLL files, which aren't linked to directly. Import libraries
+# are handled via SharedLibrary above.
class DynamicLibrary(Library):
pass
class ExternalLib... |
2145ee5961cc35d36013e2333c636c7390b6c039 | gooey/gui/util/taskkill.py | gooey/gui/util/taskkill.py | import sys
import os
import signal
if sys.platform.startswith("win"):
def taskkill(pid):
os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid))
else: # POSIX
def taskkill(pid):
os.kill(pid, signal.SIGTERM)
| import sys
import os
import signal
if sys.platform.startswith("win"):
def taskkill(pid):
os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid))
else: # POSIX
import psutil
def taskkill(pid):
parent = psutil.Process(pid)
for child in parent.children(recursive=True):
child.kill()
pare... | Kill child processes as well as shell process | Kill child processes as well as shell process
| Python | mit | jschultz/Gooey,partrita/Gooey,chriskiehl/Gooey,codingsnippets/Gooey | ---
+++
@@ -7,5 +7,9 @@
def taskkill(pid):
os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid))
else: # POSIX
+ import psutil
def taskkill(pid):
- os.kill(pid, signal.SIGTERM)
+ parent = psutil.Process(pid)
+ for child in parent.children(recursive=True):
+ child.kill()
+ parent.... |
2204fa211f09dda25830d9f3f84a0e748e6aa02c | freeze.py | freeze.py | from flask_site import freezer, config
if __name__ == '__main__':
freezer.run(debug=config.get('debug')) # build and serve from build directory
| from flask_site import freezer, flask_config
if __name__ == '__main__':
freezer.run(debug=flask_config.get('DEBUG')) # build and serve from build directory
| Fix freezing debug or not | Fix freezing debug or not
| Python | apache-2.0 | wcpr740/wcpr.org,wcpr740/wcpr.org,wcpr740/wcpr.org | ---
+++
@@ -1,4 +1,4 @@
-from flask_site import freezer, config
+from flask_site import freezer, flask_config
if __name__ == '__main__':
- freezer.run(debug=config.get('debug')) # build and serve from build directory
+ freezer.run(debug=flask_config.get('DEBUG')) # build and serve from build directory |
229ea6b0f373aa2d37c40f794c4c17bfff231e01 | mox3/fixture.py | mox3/fixture.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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://... | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# Unles... | Remove vim header from source files | Remove vim header from source files
Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765
| Python | apache-2.0 | openstack/mox3 | ---
+++
@@ -1,5 +1,3 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
# |
788ac45c702109036a4ebd0868919d5b42c040ef | this_app/forms.py | this_app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | Rename form BucketlistItem to Activity | Rename form BucketlistItem to Activity
| Python | mit | borenho/flask-bucketlist,borenho/flask-bucketlist | ---
+++
@@ -23,7 +23,7 @@
description = TextAreaField("Description", validators=[DataRequired()])
-class BucketlistItemForm(FlaskForm):
+class ActivityForm(FlaskForm):
"""Form to CRUd a bucketlist item"""
title = StringField("Title", validators=[DataRequired()])
description = TextAreaField("De... |
dddef6b793bc7c45d1f70f133a608d017ad4b341 | tests/manage_tests.py | tests/manage_tests.py | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... | Fix tests for new index. | Fix tests for new index.
| Python | bsd-3-clause | san-bil/astan,san-bil/astan,fert89/prueba-3-heroku-flask,albertogg/flask-bootstrap-skel,Agreste/MobUrbRoteiro,fert89/prueba-3-heroku-flask,san-bil/astan,scwu/stress-relief,san-bil/astan,scwu/stress-relief,Agreste/MobUrbRoteiro,Agreste/MobUrbRoteiro,akhilaryan/clickcounter | ---
+++
@@ -34,4 +34,6 @@
def test_index(self):
rv = self.app.get('/')
- assert 'hi' in rv.data
+ assert 'Flask bootstrap project' in rv.data
+ assert 'Flask-bootstrap' in rv.data
+ assert 'Read the wiki' in rv.data |
c32eb5f0a09f0a43172ed257ce21ab9545b6e03e | lazy_helpers.py | lazy_helpers.py | # Lazy objects, for the serializer to find them we put them here
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
disp... | # Lazy objects, for the serializer to find them we put them here
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
cls._display = display
display = Display(visible=0... | Update lazy helper to support the idea of a reset on bad state. | Update lazy helper to support the idea of a reset on bad state.
| Python | apache-2.0 | holdenk/diversity-analytics,holdenk/diversity-analytics | ---
+++
@@ -8,7 +8,8 @@
import os
if cls._driver is None:
from pyvirtualdisplay import Display
- display = Display(visible=0, size=(800, 600))
+ cls._display = display
+ display = Display(visible=0, size=(1024, 768))
display.start()
... |
2f4ed65bcddf9494134f279046fde75b0772b07d | utils/database.py | utils/database.py | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... | Fix mistake in path in warning when config file is missing | Fix mistake in path in warning when config file is missing
| Python | apache-2.0 | ProjectFlorida/outrider | ---
+++
@@ -24,5 +24,5 @@
try:
return yaml.load(config)['database']
except:
- print ("Ensure config/cmdb.%s.yml exists" % config_src)
+ print ("Ensure config/cmdb.%s.yml exists" % environment)
return None |
5dacd62d8d27f6d0d94313ec1bd39857ee314d2f | scrubadub/filth/named_entity.py | scrubadub/filth/named_entity.py | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | Change replacement string of named entity filth | Change replacement string of named entity filth
| Python | mit | deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub | ---
+++
@@ -10,3 +10,4 @@
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
self.label = label.lower()
+ self.replacement_string = "{}_{}".format(self.type, self.label) |
0e34fce69b01ab9b8f3ec00be633bc2581df26d5 | bibliopixel/animation/mixer.py | bibliopixel/animation/mixer.py | import copy
from . import parallel
from .. util import color_list
class Mixer(parallel.Parallel):
def __init__(self, *args, levels=None, master=1, **kwds):
self.master = master
super().__init__(*args, **kwds)
self.mixer = color_list.Mixer(
self.color_list,
[a.color... | import copy
from . import parallel
from .. util import color_list
class Mixer(parallel.Parallel):
def __init__(self, *args, levels=None, master=1, **kwds):
self.master = master
super().__init__(*args, **kwds)
self.mixer = color_list.Mixer(
self.color_list,
[a.color... | Handle getting and setting the Mixer levels correctly | Handle getting and setting the Mixer levels correctly
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel | ---
+++
@@ -12,7 +12,14 @@
self.color_list,
[a.color_list for a in self.animations],
levels)
- self.levels = self.mixer.levels
+
+ @property
+ def levels(self):
+ return self.mixer.levels
+
+ @levels.setter
+ def levels(self, levels):
+ self.mixe... |
a41e07ff20d9dc44288a57f76a83e86b4944049a | nlppln/commands/frog_to_saf.py | nlppln/commands/frog_to_saf.py | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if n... | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
from nlppln.utils import create_dirs, out_file_name
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Pa... | Update command to use nlppln utils | Update command to use nlppln utils
- fixes the double extension of output files
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln | ---
+++
@@ -6,13 +6,14 @@
from xtas.tasks._frog import parse_frog, frog_to_saf
+from nlppln.utils import create_dirs, out_file_name
+
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, o... |
8ad7e25d024e8549609119906fa09668dbb3e952 | pywikibot/families/wikivoyage_family.py | pywikibot/families/wikivoyage_family.py | """Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2020
#
# Distributed under the terms of the MIT license.
#
# The new Wikivoyage family that is hosted at Wikimedia
from pywikibot import family
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
na... | """Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2020
#
# Distributed under the terms of the MIT license.
#
# The new Wikivoyage family that is hosted at Wikimedia
from pywikibot import family
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
na... | Add support for trwikivoyage to Pywikibot | Add support for trwikivoyage to Pywikibot
Bug: T271263
Change-Id: I96597f57522147d26e9b0a86f89c67ca8959c5a2
| Python | mit | wikimedia/pywikibot-core,wikimedia/pywikibot-core | ---
+++
@@ -16,7 +16,7 @@
languages_by_size = [
'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he',
- 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi',
+ 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', 'tr',
]
category_red... |
5b66a57257807adf527fcb1de4c750013e532f25 | newsletter/utils.py | newsletter/utils.py | import logging
logger = logging.getLogger(__name__)
import random
from django.utils.hashcompat import sha_constructor
from django.contrib.sites.models import Site
from datetime import datetime
# Conditional import of 'now'
# Django 1.4 should use timezone.now, Django 1.3 datetime.now
try:
from django.utils.time... | import logging
logger = logging.getLogger(__name__)
import random
try:
from hashlib import sha1
except ImportError:
from django.utils.hashcompat import sha_constructor as sha1
from django.contrib.sites.models import Site
from datetime import datetime
# Conditional import of 'now'
# Django 1.4 should us... | Fix deprecation warnings with Django 1.5 | Fix deprecation warnings with Django 1.5
django/utils/hashcompat.py:9:
DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead | Python | agpl-3.0 | dsanders11/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter | ---
+++
@@ -3,7 +3,11 @@
import random
-from django.utils.hashcompat import sha_constructor
+try:
+ from hashlib import sha1
+except ImportError:
+ from django.utils.hashcompat import sha_constructor as sha1
+
from django.contrib.sites.models import Site
from datetime import datetime
@@ -21,12 +25,... |
45f30b4b1da110e79787b85c054796a671718910 | tests/__main__.py | tests/__main__.py |
import unittest
import os.path
if __name__ == '__main__':
HERE = os.path.dirname(__file__)
loader = unittest.loader.TestLoader()
suite = loader.discover(HERE)
result = unittest.result.TestResult()
suite.run(result)
print('Ran {} tests.'.format(result.testsRun))
print('{} errors, {} fail... |
import unittest
import os.path
if __name__ == '__main__':
HERE = os.path.dirname(__file__)
loader = unittest.loader.TestLoader()
suite = loader.discover(HERE)
result = unittest.result.TestResult()
suite.run(result)
print('Ran {} tests.'.format(result.testsRun))
print('{} errors, {} fail... | Print failures and errors in test run | Print failures and errors in test run
| Python | mit | funkybob/antfarm | ---
+++
@@ -18,5 +18,11 @@
len(result.skipped),
))
if not result.wasSuccessful():
- for module, traceback in result.errors:
- print('[{}]\n{}\n\n'.format(module, traceback))
+ if result.errors:
+ print('\nErrors:')
+ for module, traceback in result.err... |
5990374409ca2c5f35c602cb6d2276eb536d979a | tests/test_lib.py | tests/test_lib.py | """
Unit tests for One Codex
"""
from onecodex.lib.auth import check_version
from onecodex.version import __version__
SERVER = 'https://app.onecodex.com/'
def test_check_version():
# TODO: Remove Internet dependency here -- need a version response mock
should_upgrade, msg = check_version(__version__, SERVER... | """
Unit tests for One Codex
"""
from onecodex.lib.auth import check_version
from onecodex.version import __version__
SERVER = 'https://app.onecodex.com/'
def test_check_version_integration():
# TODO: Remove Internet dependency here -- need a version response mock
should_upgrade, msg = check_version(__versi... | Update verison check test, note it's an integration test | Update verison check test, note it's an integration test
| Python | mit | refgenomics/onecodex,refgenomics/onecodex,onecodex/onecodex,onecodex/onecodex | ---
+++
@@ -8,9 +8,9 @@
SERVER = 'https://app.onecodex.com/'
-def test_check_version():
+def test_check_version_integration():
# TODO: Remove Internet dependency here -- need a version response mock
- should_upgrade, msg = check_version(__version__, SERVER, 'gui')
+ should_upgrade, msg = check_version... |
f2af046da299686515e4eaf2d9ae58a62108cc21 | games/urls/installers.py | games/urls/installers.py | # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'revisions/(?P<pk>[\d]+)$',
views.InstallerRevisionDetailView.as_view(),
name="api_installer_revision_detail"),
url(r'(?P<pk>[\d]+)/r... | # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'game/(?P<slug>[\w\-]+)$',
views.GameInstallerList.as_view(),
name='api_game_installer_list'),
url(r'game/(?P<slug>[\w\-]+)/revisions... | Fix order for installer API routes | Fix order for installer API routes
| Python | agpl-3.0 | lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website | ---
+++
@@ -5,19 +5,19 @@
urlpatterns = [
- url(r'revisions/(?P<pk>[\d]+)$',
- views.InstallerRevisionDetailView.as_view(),
- name="api_installer_revision_detail"),
- url(r'(?P<pk>[\d]+)/revisions$',
- views.InstallerRevisionListView.as_view(),
- name="api_installer_revision_lis... |
3f1aeba98cd4bc2f326f9c18c34e66c396be99cf | scikits/statsmodels/tools/tests/test_data.py | scikits/statsmodels/tools/tests/test_data.py | import pandas
import numpy as np
from scikits.statsmodels.tools import data
def test_missing_data_pandas():
"""
Fixes GH: #144
"""
X = np.random.random((10,5))
X[1,2] = np.nan
df = pandas.DataFrame(X)
vals, cnames, rnames = data.interpret_data(df)
np.testing.assert_equal(rnames, [0,2,3... | import pandas
import numpy as np
from scikits.statsmodels.tools import data
def test_missing_data_pandas():
"""
Fixes GH: #144
"""
X = np.random.random((10,5))
X[1,2] = np.nan
df = pandas.DataFrame(X)
vals, cnames, rnames = data.interpret_data(df)
np.testing.assert_equal(rnames, [0,2,3... | Add some tests for unused function | TST: Add some tests for unused function
| Python | bsd-3-clause | Averroes/statsmodels,saketkc/statsmodels,wwf5067/statsmodels,phobson/statsmodels,musically-ut/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,statsmodels/statsmodels,gef756/statsmodels,rgommers/statsmodels,alekz112/statsmodels,jstoxrocky/statsmodels,kiyoto/statsmodels,music... | ---
+++
@@ -12,3 +12,30 @@
df = pandas.DataFrame(X)
vals, cnames, rnames = data.interpret_data(df)
np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9])
+
+def test_structarray():
+ X = np.random.random((10,)).astype([('var1', 'f8'),
+ ('var2', 'f8'),
+ ... |
98dd2759a184ba1066e8fd49cd09ff4194d2da0f | docweb/tests/__init__.py | docweb/tests/__init__.py | import os, sys
from django.conf import settings
# -- Setup Django configuration appropriately
TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
# The CSRF middleware prevents the Django test client from working, so
# disabl... | import os, sys
from django.conf import settings
# -- Setup Django configuration appropriately
TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
settings.SITE_ID = 1
# The CSRF middleware prevents the Django test client from... | Set SITE_ID=1 in tests (corresponds to that in the test fixtures) | Set SITE_ID=1 in tests (corresponds to that in the test fixtures) | Python | bsd-3-clause | pv/pydocweb,pv/pydocweb | ---
+++
@@ -6,6 +6,7 @@
TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
+settings.SITE_ID = 1
# The CSRF middleware prevents the Django test client from working, so
# disable it. |
85748e4b18dffca6436c5439a3e40ac773611c37 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell
# Copyright (c) 2013 Jon Surrell
#
# License: MIT
#
"""This module exports the Ghc plugin class."""
from SublimeLinter.lint import Linter, util
class Ghc(Linter):
"""Provides an interface to ghc."... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell
# Copyright (c) 2013 Jon Surrell
#
# License: MIT
#
"""This module exports the Ghc plugin class."""
from SublimeLinter.lint import Linter, util
class Ghc(Linter):
"""Provides an interface to ghc."... | Remove todo comment, no settings support | Remove todo comment, no settings support
| Python | mit | alexbiehl/SublimeLinter-stack-ghc,SublimeLinter/SublimeLinter-ghc | ---
+++
@@ -28,7 +28,6 @@
# ghc writes errors to STDERR
error_stream = util.STREAM_STDERR
- # @todo allow some settings
defaults = {}
inline_settings = None
inline_overrides = None |
23d8664a80a51c489615db6dbcde8a7e76265f15 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | Move the SERVER_NAME to the start of the default config | Move the SERVER_NAME to the start of the default config
Minor nit but the SERVER_NAME is one of the more important settings
on a per app basis.
| Python | bsd-2-clause | davidfischer/warehouse | ---
+++
@@ -2,12 +2,12 @@
from __future__ import division
from __future__ import unicode_literals
-# The URI for our PostgreSQL database.
-SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
-
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.lo... |
71ec798d6a85a2aa0e4b80e6095d4da67612db70 | apps/article/serializers.py | apps/article/serializers.py | from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by')
absolute_url... | from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by')
absolute_url = serializers.CharField(source='get_absolute_url', rea... | Clean up article serializer a bit | Clean up article serializer a bit
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 | ---
+++
@@ -5,7 +5,7 @@
class ArticleSerializer(serializers.ModelSerializer):
- author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by')
+ author = UserSerializer(source='created_by')
absolute_url = serializers.CharField(source='get_absolute_url', read_only=T... |
3fca658f3db21a0b3b8de626e6a7faf07da6ddab | restalchemy/dm/models.py | restalchemy/dm/models.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# 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
#
# ... | Add equal method to model with uuid | Add equal method to model with uuid
Change-Id: Iefa05d50f2f591399d5423debd699f88074a574e
| Python | apache-2.0 | phantomii/restalchemy | ---
+++
@@ -44,3 +44,8 @@
def get_id(self):
return self.uuid
+
+ def __eq__(self, other):
+ if isinstance(other, type(self)):
+ return self.get_id() == other.get_id()
+ return False |
2f34954716c3164b6fd65e997a6d0b02a4be6a03 | pyblox/api/http.py | pyblox/api/http.py | #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = paylo... | #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = paylo... | Check this commits description for more information | [Http] Check this commits description for more information
- sendRequest() and postRequest now have better error handling and display the error via console
- No longer toggles error on 403, instead it toggles everything but 200 | Python | mit | Sanjay-B/Pyblox | ---
+++
@@ -16,8 +16,8 @@
statusCode = payload.status_code
header = payload.headers
content = payload.content
- if statusCode == 403:
- return print("[Roblox][GET] Something went wrong. Error: 403")
+ if statusCode is not 200:
+ return print("[Roblox][GET] Something went wrong. Error: "+statusCode)
... |
8e755e7dc94b6966e73af5434d382fa1ecd15572 | manage.py | manage.py | # TODO: migrate to Flask CLI instead of Flask-Script
'''This module enables command line interface for randompeople app.'''
from flask_script import Manager
from app import create_app, db
from app.models import Room, Member
manager = Manager(create_app)
@manager.shell
def make_shell_context():
''''''
return d... | # TODO: migrate to Flask CLI instead of Flask-Script
'''This module enables command line interface for randompeople app.'''
from flask_script import Manager
from app import create_app, db
from app.models import Room, Member
app = create_app()
manager = Manager(app)
@manager.shell
def make_shell_context():
''''''
... | Add Flask app variable to use with gunicorn | Add Flask app variable to use with gunicorn
| Python | mit | chetotam/randompeople,chetotam/randompeople,chetotam/randompeople | ---
+++
@@ -4,12 +4,13 @@
from app import create_app, db
from app.models import Room, Member
-manager = Manager(create_app)
+app = create_app()
+manager = Manager(app)
@manager.shell
def make_shell_context():
''''''
- return dict(app=manager.app, db=db, Room=Room, Member=Member)
+ return dict(app=a... |
2958e793ea30d879afe265bb511183e4512fc049 | webstr/core/config.py | webstr/core/config.py | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | Change the default value for SELENIUM_SERVER | Change the default value for SELENIUM_SERVER
with this change it is possible to use webstr on localhost without any action
Change-Id: Ife533552d7a746401df01c03af0b2d1caf0702b5
Signed-off-by: ltrilety <b0b91364d2d251c1396ffbe2df56e3ab774d4d4b@redhat.com>
| Python | apache-2.0 | Webstr-framework/webstr | ---
+++
@@ -30,7 +30,7 @@
BROWSER = 'Firefox'
BROWSER_VERSION = ''
BROWSER_PLATFORM = 'ANY'
-SELENIUM_SERVER = 'selenium-grid.example.com'
+SELENIUM_SERVER = None
SELENIUM_PORT = 4444
BROWSER_WIDTH = 1280
BROWSER_HEIGHT = 1024 |
d6d15743f6bac48a051798df0638190e1241ffb1 | parliament/politicians/twit.py | parliament/politicians/twit.py | import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(s... | import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(s... | Change the base URL for the Twitter API | Change the base URL for the Twitter API
| Python | agpl-3.0 | rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,rhymeswithcycle/openparliament,twhyte/openparliament,litui/openparliament,twhyte/openparliament | ---
+++
@@ -11,7 +11,7 @@
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')])
- twit = twitter.Twitter()
+ twit = twitter.Twitter(domain='api.twitter.com/1')
statuses = twit.openparlca.... |
add6013c8484e56545ed2f11c8c6e042c1384429 | swf/exceptions.py | swf/exceptions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class PollTimeout(Exception):
pass
class InvalidCredentialsError(Exception):
pass
class ResponseError(Exception):
pass
class DoesNotExistError(Exception):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.spli... | Enhance swf errors wrapping via an exception helper | Enhance swf errors wrapping via an exception helper
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | ---
+++
@@ -5,26 +5,47 @@
#
# See the file LICENSE for copying permission.
+class SWFError(Exception):
+ def __init__(self, message, raw_error, *args):
+ Exception.__init__(self, message, *args)
+ self.kind, self.details = raw_error.split(':')
-class PollTimeout(Exception):
+ def __repr__(se... |
5397cb0d10f680bc4bf4ab30deb77e9fbff4761d | tapes/__init__.py | tapes/__init__.py | from datetime import datetime
__version__ = '0.2.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
try:
# we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc.,
# but at the point of invocation in setup.py the dependencies imported in .registry are not installed
# yet, so we ... | from datetime import datetime
__version__ = '0.3.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
try:
# we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc.,
# but at the point of invocation in setup.py the dependencies imported in .registry are not installed
# yet, so we ... | Bump version for future dev | Bump version for future dev
| Python | apache-2.0 | emilssolmanis/tapes,emilssolmanis/tapes,emilssolmanis/tapes | ---
+++
@@ -1,5 +1,5 @@
from datetime import datetime
-__version__ = '0.2.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
+__version__ = '0.3.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
try:
# we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc., |
5f6fb9dc79982331a36debdeb33212357def2b11 | bayohwoolph.py | bayohwoolph.py | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... | Make bot respond to mentions. | Make bot respond to mentions.
| Python | agpl-3.0 | dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph | ---
+++
@@ -17,7 +17,7 @@
MAIN = config['MAIN']
description = '''Dark Echo's barkeep'''
-bot = commands.Bot(command_prefix='$', description=description)
+bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description)
@bot.event
@asyncio.coroutine |
bfc16a9010a664d18d01f0fc4684353adbab7a47 | {{cookiecutter.project_name}}/{{cookiecutter.module_name}}.py | {{cookiecutter.project_name}}/{{cookiecutter.module_name}}.py | #!/usr/bin/env python
"""{{ cookiecutter.description }}"""
# Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use.
import sys
import logging
import click
from click import echo
__version__ = '{{ cookiecutter.version }}'
@click.command()
@click.help_option('--help', '-h')
@c... | #!/usr/bin/env python
"""{{ cookiecutter.description }}"""
# Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use.
import sys
import logging
import click
from click import echo
__version__ = '{{ cookiecutter.version }}'
@click.command()
@click.help_option('--help', '-h')
@c... | Remove ability to run module directly | Remove ability to run module directly
| Python | mit | goerz/cookiecutter-pyscript | ---
+++
@@ -23,6 +23,3 @@
logger.setLevel(logging.DEBUG)
logger.debug("Enabled debug output")
-
-if __name__ == "__main__":
- sys.exit(main()) |
faf8f70128d70696707f073181f9ce8d08629fd2 | teknologr/members/lookups.py | teknologr/members/lookups.py | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
... | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
... | Remove too many newlines (pep8 E303) | Remove too many newlines (pep8 E303)
| Python | mit | Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io | ---
+++
@@ -19,7 +19,6 @@
if not args:
return [] # No words in query (only spaces?)
-
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj): |
01ca6c2c71b8558e119ae4448e02c2c84a5ef6f9 | mailviews/tests/urls.py | mailviews/tests/urls.py | from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| Remove unused import on test url's | Remove unused import on test url's
| Python | apache-2.0 | disqus/django-mailviews,disqus/django-mailviews | ---
+++
@@ -1,5 +1,3 @@
-from mailviews.utils import is_django_version_greater
-
from django.conf.urls import include, url
|
6d48f5fb6be6045d89948729c6e28ed1f1a305ab | pywal/reload.py | pywal/reload.py | """
Reload programs.
"""
import shutil
import subprocess
from pywal.settings import CACHE_DIR
from pywal import util
def reload_i3():
"""Reload i3 colors."""
if shutil.which("i3-msg"):
util.disown("i3-msg", "reload")
def reload_xrdb():
"""Merge the colors into the X db so new terminals use them... | """
Reload programs.
"""
import shutil
import subprocess
from pywal.settings import CACHE_DIR
from pywal import util
def reload_xrdb():
"""Merge the colors into the X db so new terminals use them."""
if shutil.which("xrdb"):
subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"])
def r... | Fix bug with i3 titlebars not being the right color. | colors: Fix bug with i3 titlebars not being the right color.
| Python | mit | dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal | ---
+++
@@ -8,20 +8,20 @@
from pywal import util
+def reload_xrdb():
+ """Merge the colors into the X db so new terminals use them."""
+ if shutil.which("xrdb"):
+ subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"])
+
+
def reload_i3():
"""Reload i3 colors."""
if shutil.w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.