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 |
|---|---|---|---|---|---|---|---|---|---|---|
f2c34f7e0e7f50ca6669632d6fd89feb26c98609 | tools/daily.py | tools/daily.py | #!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI_CONFIG", os.path.join(prefix, 'config.ini'))
conf = config.Config(CONFIG_FILE)
store = store.Store(conf)
cursor = store.get_cursor()
cursor.execute("delete from cookies where last_seen < now()-INTERVAL'1day';")
cursor.execute("delete from openid_sessions where expires < now();")
cursor.execute("delete from openid_nonces where created < now()-INTERVAL'1day'; ")
cursor.execute("delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');")
cursor.execute("delete from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles));")
store.commit()
| #!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI_CONFIG", os.path.join(prefix, 'config.ini'))
conf = config.Config(CONFIG_FILE)
store = store.Store(conf)
cursor = store.get_cursor()
cursor.execute("delete from cookies where last_seen < now()-INTERVAL'1day';")
cursor.execute("delete from openid_sessions where expires < now();")
cursor.execute("delete from openid_nonces where created < now()-INTERVAL'1day'; ")
cursor.execute("delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');")
cursor.execute("delete from accounts_email where user_id in (select id from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles)));")
cursor.execute("delete from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles));")
store.commit()
| Delete emails before deleting users | Delete emails before deleting users
--HG--
branch : production
| Python | bsd-3-clause | pydotorg/pypi,pydotorg/pypi,pydotorg/pypi,pydotorg/pypi | ---
+++
@@ -23,6 +23,7 @@
cursor.execute("delete from openid_sessions where expires < now();")
cursor.execute("delete from openid_nonces where created < now()-INTERVAL'1day'; ")
cursor.execute("delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');")
+cursor.execute("delete from accounts_email where user_id in (select id from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles)));")
cursor.execute("delete from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles));")
store.commit() |
a6eeda7ed6037285627ca6e468a7ef8ab467034f | data/build_dictionary.py | data/build_dictionary.py | #!/usr/bin/python
import numpy
import json
import sys
import fileinput
from collections import OrderedDict
def main():
for filename in sys.argv[1:]:
print 'Processing', filename
word_freqs = OrderedDict()
with open(filename, 'r') as f:
for line in f:
words_in = line.strip().split(' ')
for w in words_in:
if w not in word_freqs:
word_freqs[w] = 0
word_freqs[w] += 1
words = word_freqs.keys()
freqs = word_freqs.values()
sorted_idx = numpy.argsort(freqs)
sorted_words = [words[ii] for ii in sorted_idx[::-1]]
worddict = OrderedDict()
for ii, ww in enumerate(sorted_words):
worddict[ww] = ii+2
worddict['eos'] = 0
worddict['UNK'] = 1
with open('%s.json'%filename, 'wb') as f:
json.dump(worddict, f, indent=2, ensure_ascii=False)
print 'Done'
if __name__ == '__main__':
main()
| #!/usr/bin/python
import numpy
import json
import sys
import fileinput
from collections import OrderedDict
def main():
for filename in sys.argv[1:]:
print 'Processing', filename
word_freqs = OrderedDict()
with open(filename, 'r') as f:
for line in f:
words_in = line.strip().split(' ')
for w in words_in:
if w not in word_freqs:
word_freqs[w] = 0
word_freqs[w] += 1
words = word_freqs.keys()
freqs = word_freqs.values()
sorted_idx = numpy.argsort(freqs)
sorted_words = [words[ii] for ii in sorted_idx[::-1]]
worddict = OrderedDict()
worddict['eos'] = 0
worddict['UNK'] = 1
for ii, ww in enumerate(sorted_words):
worddict[ww] = ii+2
with open('%s.json'%filename, 'wb') as f:
json.dump(worddict, f, indent=2, ensure_ascii=False)
print 'Done'
if __name__ == '__main__':
main()
| Revert "eos and UNK will be overwritten if they occur in the corpus, should always be 0 and 1" | Revert "eos and UNK will be overwritten if they occur in the corpus, should always be 0 and 1"
Actually fine if there are weird values, as Nematus does not really use them.
This reverts commit 09eb3594fb395d43dd3f6c2a4dec85af683cbb30.
| Python | bsd-3-clause | rsennrich/nematus,shuoyangd/nematus,EdinburghNLP/nematus,Proyag/nematus,shuoyangd/nematus,EdinburghNLP/nematus,EdinburghNLP/nematus,Proyag/nematus,rsennrich/nematus,yang1fan2/nematus,Proyag/nematus,Proyag/nematus,yang1fan2/nematus,yang1fan2/nematus,cshanbo/nematus,rsennrich/nematus,rsennrich/nematus,shuoyangd/nematus,Proyag/nematus,yang1fan2/nematus,rsennrich/nematus,cshanbo/nematus,shuoyangd/nematus,yang1fan2/nematus,yang1fan2/nematus,cshanbo/nematus,yang1fan2/nematus,cshanbo/nematus,rsennrich/nematus,EdinburghNLP/nematus,EdinburghNLP/nematus,Proyag/nematus,cshanbo/nematus,cshanbo/nematus,EdinburghNLP/nematus,yang1fan2/nematus,shuoyangd/nematus,yang1fan2/nematus,yang1fan2/nematus,shuoyangd/nematus | ---
+++
@@ -26,10 +26,10 @@
sorted_words = [words[ii] for ii in sorted_idx[::-1]]
worddict = OrderedDict()
+ worddict['eos'] = 0
+ worddict['UNK'] = 1
for ii, ww in enumerate(sorted_words):
worddict[ww] = ii+2
- worddict['eos'] = 0
- worddict['UNK'] = 1
with open('%s.json'%filename, 'wb') as f:
json.dump(worddict, f, indent=2, ensure_ascii=False) |
670b896f0ef8a4feda9cbb0181364f277dc50299 | miner_plotter/models.py | miner_plotter/models.py | import pymodm
import slugify
class DevicePlot(pymodm.MongoModel):
device_name = pymodm.fields.CharField()
slug = pymodm.fields.CharField()
plot_title = pymodm.fields.CharField()
x_label = pymodm.fields.CharField()
y_label = pymodm.fields.CharField()
def save(self, *args, **kwargs):
if not self.pk:
self.slug = slugify.slugify(self.device_name)
super(DevicePlot, self).save(*args, **kwargs)
class PlotPoints(pymodm.MongoModel):
device_plot = pymodm.fields.ReferenceField(DevicePlot)
label = pymodm.fields.CharField()
points = pymodm.fields.ListField(default=[])
def save(self, *args, **kwargs):
# TODO: configurable setting...
if len(self.points) >= 30:
self.points = self.points[30:]
super(PlotPoints, self).save(*args, **kwargs)
| import pymodm
import slugify
class DevicePlot(pymodm.MongoModel):
device_name = pymodm.fields.CharField()
slug = pymodm.fields.CharField()
plot_title = pymodm.fields.CharField()
x_label = pymodm.fields.CharField()
y_label = pymodm.fields.CharField()
def save(self, *args, **kwargs):
if not self.pk:
self.slug = slugify.slugify(self.device_name)
super(DevicePlot, self).save(*args, **kwargs)
class PlotPoints(pymodm.MongoModel):
device_plot = pymodm.fields.ReferenceField(DevicePlot)
label = pymodm.fields.CharField()
points = pymodm.fields.ListField(default=[])
def save(self, *args, **kwargs):
# TODO: configurable setting...
if len(self.points) >= 30:
self.points = self.points[-30:]
super(PlotPoints, self).save(*args, **kwargs)
| Fix bug to only store the 30 most recent points | Fix bug to only store the 30 most recent points
| Python | mit | juannyG/miner-plotter,juannyG/miner-plotter,juannyG/miner-plotter | ---
+++
@@ -23,5 +23,5 @@
def save(self, *args, **kwargs):
# TODO: configurable setting...
if len(self.points) >= 30:
- self.points = self.points[30:]
+ self.points = self.points[-30:]
super(PlotPoints, self).save(*args, **kwargs) |
d15b996dc4a741390507a96d6facf113f8da0869 | test/test_play.py | test/test_play.py | # -*- coding: utf-8 -*-
"""Tests for the play plugin"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from mock import patch, Mock
from test._common import unittest
from test.helper import TestHelper
class PlayPluginTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()
self.load_plugins('play')
self.add_item(title='aNiceTitle')
def tearDown(self):
self.teardown_beets()
self.unload_plugins()
@patch('beetsplug.play.util.interactive_open', Mock())
def test_basic(self):
self.run_command('play', 'title:aNiceTitle')
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == b'__main__':
unittest.main(defaultTest='suite')
| # -*- coding: utf-8 -*-
"""Tests for the play plugin"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from mock import patch, ANY
from test._common import unittest
from test.helper import TestHelper
class PlayPluginTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()
self.load_plugins('play')
self.item = self.add_item(title='aNiceTitle')
def tearDown(self):
self.teardown_beets()
self.unload_plugins()
@patch('beetsplug.play.util.interactive_open')
def test_basic(self, open_mock):
self.run_command('play', 'title:aNiceTitle')
open_mock.assert_called_once_with(ANY, None)
playlist = open(open_mock.call_args[0][0][0], 'r')
self.assertEqual(self.item.path.decode('utf-8') + '\n',
playlist.read().decode('utf-8'))
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == b'__main__':
unittest.main(defaultTest='suite')
| Verify that the generated playlist contains the path to the item | Verify that the generated playlist contains the path to the item
| Python | mit | lengtche/beets,SusannaMaria/beets,jcoady9/beets,xsteadfastx/beets,diego-plan9/beets,shamangeorge/beets,jackwilsdon/beets,jcoady9/beets,LordSputnik/beets,sampsyo/beets,LordSputnik/beets,lengtche/beets,madmouser1/beets,mosesfistos1/beetbox,mried/beets,LordSputnik/beets,jcoady9/beets,SusannaMaria/beets,ibmibmibm/beets,swt30/beets,MyTunesFreeMusic/privacy-policy,shamangeorge/beets,artemutin/beets,mosesfistos1/beetbox,artemutin/beets,swt30/beets,swt30/beets,beetbox/beets,shamangeorge/beets,lengtche/beets,mried/beets,jcoady9/beets,Freso/beets,xsteadfastx/beets,MyTunesFreeMusic/privacy-policy,Kraymer/beets,swt30/beets,Kraymer/beets,shamangeorge/beets,pkess/beets,xsteadfastx/beets,jackwilsdon/beets,diego-plan9/beets,lengtche/beets,MyTunesFreeMusic/privacy-policy,parapente/beets,sampsyo/beets,pkess/beets,xsteadfastx/beets,Freso/beets,Freso/beets,LordSputnik/beets,mried/beets,ibmibmibm/beets,Kraymer/beets,ibmibmibm/beets,pkess/beets,madmouser1/beets,sampsyo/beets,madmouser1/beets,jackwilsdon/beets,Freso/beets,SusannaMaria/beets,beetbox/beets,diego-plan9/beets,ibmibmibm/beets,pkess/beets,MyTunesFreeMusic/privacy-policy,beetbox/beets,mosesfistos1/beetbox,parapente/beets,sampsyo/beets,artemutin/beets,jackwilsdon/beets,artemutin/beets,madmouser1/beets,beetbox/beets,mosesfistos1/beetbox,Kraymer/beets,SusannaMaria/beets,mried/beets,parapente/beets,diego-plan9/beets,parapente/beets | ---
+++
@@ -5,7 +5,7 @@
from __future__ import (division, absolute_import, print_function,
unicode_literals)
-from mock import patch, Mock
+from mock import patch, ANY
from test._common import unittest
from test.helper import TestHelper
@@ -15,15 +15,20 @@
def setUp(self):
self.setup_beets()
self.load_plugins('play')
- self.add_item(title='aNiceTitle')
+ self.item = self.add_item(title='aNiceTitle')
def tearDown(self):
self.teardown_beets()
self.unload_plugins()
- @patch('beetsplug.play.util.interactive_open', Mock())
- def test_basic(self):
+ @patch('beetsplug.play.util.interactive_open')
+ def test_basic(self, open_mock):
self.run_command('play', 'title:aNiceTitle')
+
+ open_mock.assert_called_once_with(ANY, None)
+ playlist = open(open_mock.call_args[0][0][0], 'r')
+ self.assertEqual(self.item.path.decode('utf-8') + '\n',
+ playlist.read().decode('utf-8'))
def suite(): |
6b36639cc7ff17f4d74aa0239311867b3937da87 | py/longest-increasing-path-in-a-matrix.py | py/longest-increasing-path-in-a-matrix.py | from collections import defaultdict, Counter
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
neighbors = defaultdict(list)
in_deg = Counter()
longest_length = Counter()
ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
starts = set(xrange(h * w))
for x, row in enumerate(matrix):
for y, v in enumerate(row):
for dx, dy in ds:
nx, ny = x + dx, y + dy
if 0 <= nx < h and 0 <= ny < w:
if matrix[nx][ny] > v:
neighbors[x * w + y].append(nx * w + ny)
in_deg[nx * w + ny] += 1
starts.discard(nx * w + ny)
for start in starts:
longest_length[start] = 1
q = list(starts)
ans = 1
for v in q:
for neighbor in neighbors[v]:
longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
ans = max(longest_length[neighbor], ans)
in_deg[neighbor] -= 1
if in_deg[neighbor] == 0:
q.append(neighbor)
return ans
| from collections import Counter
class Solution(object):
def dfs(self, dp, matrix, x, y, w, h):
v = matrix[x][y]
if dp[x, y] == 0:
dp[x, y] = 1 + max(
0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
)
return dp[x, y]
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
ans = 1
starts = set(xrange(h * w))
dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans
| Add py solution for 329. Longest Increasing Path in a Matrix | Add py solution for 329. Longest Increasing Path in a Matrix
329. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Approach 2:
Top down search
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -1,5 +1,17 @@
-from collections import defaultdict, Counter
+from collections import Counter
class Solution(object):
+ def dfs(self, dp, matrix, x, y, w, h):
+ v = matrix[x][y]
+ if dp[x, y] == 0:
+ dp[x, y] = 1 + max(
+ 0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
+ 0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
+ 0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
+ 0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
+ )
+
+ return dp[x, y]
+
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
@@ -9,31 +21,10 @@
return 0
h = len(matrix)
w = len(matrix[0])
- neighbors = defaultdict(list)
- in_deg = Counter()
- longest_length = Counter()
-
- ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
+ ans = 1
starts = set(xrange(h * w))
+ dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
- for dx, dy in ds:
- nx, ny = x + dx, y + dy
- if 0 <= nx < h and 0 <= ny < w:
- if matrix[nx][ny] > v:
- neighbors[x * w + y].append(nx * w + ny)
- in_deg[nx * w + ny] += 1
- starts.discard(nx * w + ny)
- for start in starts:
- longest_length[start] = 1
-
- q = list(starts)
- ans = 1
- for v in q:
- for neighbor in neighbors[v]:
- longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
- ans = max(longest_length[neighbor], ans)
- in_deg[neighbor] -= 1
- if in_deg[neighbor] == 0:
- q.append(neighbor)
+ ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans |
4e68ee7d361bc34e77002cbdcfe077e89fcb3bd8 | gala/__init__.py | gala/__init__.py | """
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
| """
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.2dev'
| Add __version__ attribute to gala package | Add __version__ attribute to gala package
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala | ---
+++
@@ -17,3 +17,5 @@
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
+
+__version__ = '0.2dev' |
d3670f4c8a07cc9e29c417a0f0ffa6499a3f53e2 | session_csrf/templatetags/session_csrf.py | session_csrf/templatetags/session_csrf.py | from copy import copy
from django.template.defaulttags import CsrfTokenNode
from django import template
from ..models import Token
register = template.Library()
@register.simple_tag(takes_context=True)
def per_view_csrf(context, view_name):
"""Register per view csrf token. Not pure!"""
_context = copy(context)
request = _context['request']
if request.user.is_authenticated():
token, _ = Token.objects.get_or_create(
owner=request.user, for_view=view_name)
_context['csrf_token'] = token.value
node = CsrfTokenNode()
return node.render(_context)
per_view_csrf.is_safe = True
| from contextlib import contextmanager
from django.template.defaulttags import CsrfTokenNode
from django import template
from ..models import Token
register = template.Library()
@contextmanager
def save_token(context):
is_exists = 'csrf_token' in context
token = context.get('csrf_token')
yield
if is_exists:
context['csrf_token'] = token
else:
del context['csrf_token']
@register.simple_tag(takes_context=True)
def per_view_csrf(context, view_name):
"""Register per view csrf token. Not pure!"""
with save_token(context):
request = context['request']
if request.user.is_authenticated():
token, _ = Token.objects.get_or_create(
owner=request.user, for_view=view_name)
context['csrf_token'] = token.value
node = CsrfTokenNode()
return node.render(context)
per_view_csrf.is_safe = True
| Fix error with per-view and not per-view csrf on one page | Fix error with per-view and not per-view csrf on one page
| Python | bsd-3-clause | nvbn/django-session-csrf,nvbn/django-session-csrf | ---
+++
@@ -1,4 +1,4 @@
-from copy import copy
+from contextlib import contextmanager
from django.template.defaulttags import CsrfTokenNode
from django import template
from ..models import Token
@@ -7,15 +7,25 @@
register = template.Library()
+@contextmanager
+def save_token(context):
+ is_exists = 'csrf_token' in context
+ token = context.get('csrf_token')
+ yield
+ if is_exists:
+ context['csrf_token'] = token
+ else:
+ del context['csrf_token']
+
@register.simple_tag(takes_context=True)
def per_view_csrf(context, view_name):
"""Register per view csrf token. Not pure!"""
- _context = copy(context)
- request = _context['request']
- if request.user.is_authenticated():
- token, _ = Token.objects.get_or_create(
- owner=request.user, for_view=view_name)
- _context['csrf_token'] = token.value
- node = CsrfTokenNode()
- return node.render(_context)
+ with save_token(context):
+ request = context['request']
+ if request.user.is_authenticated():
+ token, _ = Token.objects.get_or_create(
+ owner=request.user, for_view=view_name)
+ context['csrf_token'] = token.value
+ node = CsrfTokenNode()
+ return node.render(context)
per_view_csrf.is_safe = True |
1933715436a7f7828255bf3e002728f2bb80ed0d | bin/profile_queries.py | bin/profile_queries.py | #!/usr/bin/env sh
import os
import time
import json
try:
import requests
except ImportError:
print('Profiling script requires requests package. \n'
'You can install it by running "pip install requests"')
exit()
API_BASE_URL = 'http://localhost:9000/api/'
# If user in bin directory set correct path to quires
if os.getcwd().endswith('bin'):
queries_folder = os.getcwd().rstrip('bin') + 'test/queries'
else:
queries_folder = os.getcwd() + '/test/queries'
results = []
test_queries = []
for file_name in os.listdir(queries_folder):
if file_name.endswith('.txt') and file_name != 'README.txt':
for query in open('{}/{}'.format(queries_folder, file_name)).readlines():
test_queries.append(query.rstrip())
print('Start profiling {} queries'.format(len(test_queries)))
for query in test_queries:
time_start = time.time()
url = API_BASE_URL + 'search.json?source=cache&q={}'.format(query)
result = json.loads(requests.get(url).text)
assert 'statuses' in result
time_finish = time.time()
results.append(time_finish - time_start)
print('Profiling finished.')
print('Average time: {} seconds'.format(sum(results) / len(results)))
print('Minimal time: {} seconds'.format(min(results)))
print('Maximal time: {} seconds'.format(max(results)))
| #!/usr/bin/env python
import os
import time
import json
try:
import requests
except ImportError:
print('Profiling script requires requests package. \n'
'You can install it by running "pip install requests"')
exit()
API_BASE_URL = 'http://localhost:9000/api/'
# If user in bin directory set correct path to quires
if os.getcwd().endswith('bin'):
queries_folder = os.getcwd().rstrip('bin') + 'test/queries'
else:
queries_folder = os.getcwd() + '/test/queries'
results = []
test_queries = []
for file_name in os.listdir(queries_folder):
if file_name.endswith('.txt') and file_name != 'README.txt':
for query in open('{}/{}'.format(queries_folder, file_name)).readlines():
test_queries.append(query.rstrip())
print('Start profiling {} queries'.format(len(test_queries)))
for query in test_queries:
time_start = time.time()
url = API_BASE_URL + 'search.json?source=cache&q={}'.format(query)
result = json.loads(requests.get(url).text)
assert 'statuses' in result
time_finish = time.time()
results.append(time_finish - time_start)
print('Profiling finished.')
print('Average time: {} seconds'.format(sum(results) / len(results)))
print('Minimal time: {} seconds'.format(min(results)))
print('Maximal time: {} seconds'.format(max(results)))
| Add sheebang to queries profiling script | Add sheebang to queries profiling script | Python | lgpl-2.1 | sudheesh001/loklak_server,arashahmadi/sensemi_ai,daminisatya/loklak_server,kavithaenair/apps.loklak.org,smokingwheels/loklak_server_frontend_hdd,shivenmian/loklak_server,daminisatya/loklak_server,loklak/loklak_server,kavithaenair/apps.loklak.org,smokingwheels/loklak_server_frontend_hdd,YagoGG/loklak_server,smsunarto/loklak_server,singhpratyush/loklak_server,shivenmian/loklak_server,singhpratyush/loklak_server,daminisatya/loklak_server,YagoGG/loklak_server,YagoGG/loklak_server,singhpratyush/loklak_server,sudheesh001/loklak_server,PiotrKowalski/loklak_server,smokingwheels/loklak_server_frontend_hdd,djmgit/apps.loklak.org,loklak/loklak_server,djmgit/apps.loklak.org,loklak/loklak_server,singhpratyush/loklak_server,smokingwheels/loklak_server_frontend_hdd,loklak/loklak_server,PiotrKowalski/loklak_server,YagoGG/loklak_server,fazeem84/susi_server,djmgit/apps.loklak.org,sudheesh001/loklak_server,loklak/loklak_server,shivenmian/loklak_server,smsunarto/loklak_server,DravitLochan/susi_server,kavithaenair/apps.loklak.org,PiotrKowalski/loklak_server,YagoGG/loklak_server,daminisatya/loklak_server,shivenmian/loklak_server,smokingwheels/loklak_server_frontend_hdd,loklak/loklak_server,singhpratyush/loklak_server,arashahmadi/sensemi_ai,daminisatya/loklak_server,fazeem84/susi_server,smsunarto/loklak_server,PiotrKowalski/loklak_server,smsunarto/loklak_server,sudheesh001/loklak_server,fazeem84/susi_server,smsunarto/loklak_server,smokingwheels/loklak_server_frontend_hdd,DravitLochan/susi_server,DravitLochan/susi_server,smsunarto/loklak_server,daminisatya/loklak_server,fazeem84/susi_server,loklak/loklak_server,shivenmian/loklak_server,singhpratyush/loklak_server,arashahmadi/sensemi_ai,arashahmadi/sensemi_ai,sudheesh001/loklak_server,djmgit/apps.loklak.org,DravitLochan/susi_server,shivenmian/loklak_server,sudheesh001/loklak_server,smokingwheels/loklak_server_frontend_hdd,YagoGG/loklak_server,YagoGG/loklak_server,shivenmian/loklak_server,smsunarto/loklak_server,kavithaenair/apps.loklak.org,PiotrKowalski/loklak_server,PiotrKowalski/loklak_server,sudheesh001/loklak_server,singhpratyush/loklak_server,daminisatya/loklak_server,PiotrKowalski/loklak_server | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env sh
+#!/usr/bin/env python
import os
import time
import json |
07b7a666bc1c538580b5e7f528e528e4cc4bc25d | testing/client.py | testing/client.py | import gevent
from kvclient import KeyValueClient
class TestClient(KeyValueClient):
yield_loop = gevent.sleep
| import gevent
from kvclient import KeyValueClient
class TestClient(KeyValueClient):
yield_loop = lambda: gevent.sleep(0)
| Fix gevent.sleep not having a parameter. | Fix gevent.sleep not having a parameter. | Python | unlicense | squirly/eece411-kvclient | ---
+++
@@ -3,4 +3,4 @@
class TestClient(KeyValueClient):
- yield_loop = gevent.sleep
+ yield_loop = lambda: gevent.sleep(0) |
b5593bbfb8fda3bbdb9c5408f17078949ab91481 | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
def pytest_funcarg__api_factory(request):
class APIFactory:
def create(self, token='dummy_token'):
from annict.api import API
return API(token)
return APIFactory()
| # -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def api_factory():
class APIFactory:
def create(self, token='dummy_token'):
from annict.api import API
return API(token)
return APIFactory()
| Fix old-style `pytest_funcarg__`, instead @pytest.fixture. | Fix old-style `pytest_funcarg__`, instead @pytest.fixture.
| Python | mit | kk6/python-annict | ---
+++
@@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
+import pytest
-def pytest_funcarg__api_factory(request):
+@pytest.fixture
+def api_factory():
class APIFactory:
def create(self, token='dummy_token'):
from annict.api import API |
36740bf92999dae7258e1aeb6e8d82b43e1773f5 | tests/conftest.py | tests/conftest.py | from flask import Flask
import pytest
app = Flask('__config_test')
@pytest.fixture()
def client():
return app, app.test_client()
| from flask import Flask
import pytest
from flask_extras import FlaskExtras
app = Flask('__config_test')
app.secret_key = '123'
app.debug = True
FlaskExtras(app)
@pytest.fixture()
def client():
return app, app.test_client()
| Add config and plugin wrapper for app test fixture. | Add config and plugin wrapper for app test fixture.
| Python | mit | christabor/flask_extras,christabor/flask_extras,christabor/jinja2_template_pack,christabor/jinja2_template_pack | ---
+++
@@ -1,8 +1,12 @@
from flask import Flask
import pytest
+from flask_extras import FlaskExtras
app = Flask('__config_test')
+app.secret_key = '123'
+app.debug = True
+FlaskExtras(app)
@pytest.fixture() |
ad4c1014184f8a7c4b72a4620262bf5fda3264d2 | sympy/physics/gaussopt.py | sympy/physics/gaussopt.py | from sympy.physics.optics.gaussopt import RayTransferMatrix, FreeSpace,\
FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens,\
GeometricRay, BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\
geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt",
useinstead="sympy.physics.optics.gaussopt",
deprecated_since_version="0.7.6").warn()
| from sympy.physics.optics.gaussopt import RayTransferMatrix, FreeSpace,\
FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens,\
GeometricRay, BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\
geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt",
useinstead="sympy.physics.optics.gaussopt",
deprecated_since_version="0.7.6", issue=7659).warn()
| Add issue number(7659) in the deprecation warning | Add issue number(7659) in the deprecation warning
| Python | bsd-3-clause | rahuldan/sympy,debugger22/sympy,pbrady/sympy,farhaanbukhsh/sympy,kevalds51/sympy,yashsharan/sympy,toolforger/sympy,Sumith1896/sympy,Vishluck/sympy,kaushik94/sympy,asm666/sympy,pandeyadarsh/sympy,rahuldan/sympy,madan96/sympy,sampadsaha5/sympy,sunny94/temp,skirpichev/omg,Curious72/sympy,sahmed95/sympy,jbbskinny/sympy,MridulS/sympy,asm666/sympy,maniteja123/sympy,shipci/sympy,meghana1995/sympy,mcdaniel67/sympy,MechCoder/sympy,aktech/sympy,moble/sympy,Arafatk/sympy,cccfran/sympy,emon10005/sympy,jaimahajan1997/sympy,emon10005/sympy,asm666/sympy,Gadal/sympy,drufat/sympy,VaibhavAgarwalVA/sympy,cswiercz/sympy,wyom/sympy,Sumith1896/sympy,abloomston/sympy,meghana1995/sympy,aktech/sympy,Designist/sympy,vipulroxx/sympy,Curious72/sympy,AkademieOlympia/sympy,saurabhjn76/sympy,lindsayad/sympy,kumarkrishna/sympy,lindsayad/sympy,drufat/sympy,dqnykamp/sympy,atsao72/sympy,madan96/sympy,moble/sympy,yashsharan/sympy,postvakje/sympy,emon10005/sympy,beni55/sympy,kumarkrishna/sympy,ChristinaZografou/sympy,abhiii5459/sympy,iamutkarshtiwari/sympy,abhiii5459/sympy,postvakje/sympy,kaushik94/sympy,vipulroxx/sympy,atreyv/sympy,ahhda/sympy,shipci/sympy,rahuldan/sympy,sahmed95/sympy,maniteja123/sympy,Shaswat27/sympy,abhiii5459/sympy,Arafatk/sympy,liangjiaxing/sympy,moble/sympy,MridulS/sympy,hargup/sympy,Titan-C/sympy,cswiercz/sympy,Shaswat27/sympy,kaichogami/sympy,postvakje/sympy,ChristinaZografou/sympy,debugger22/sympy,souravsingh/sympy,yashsharan/sympy,sahmed95/sympy,garvitr/sympy,yukoba/sympy,garvitr/sympy,Mitchkoens/sympy,ga7g08/sympy,Curious72/sympy,sahilshekhawat/sympy,chaffra/sympy,jaimahajan1997/sympy,jamesblunt/sympy,abloomston/sympy,ahhda/sympy,saurabhjn76/sympy,wyom/sympy,madan96/sympy,bukzor/sympy,mafiya69/sympy,chaffra/sympy,grevutiu-gabriel/sympy,pbrady/sympy,toolforger/sympy,shipci/sympy,jbbskinny/sympy,wanglongqi/sympy,souravsingh/sympy,VaibhavAgarwalVA/sympy,atsao72/sympy,jamesblunt/sympy,Gadal/sympy,kaichogami/sympy,VaibhavAgarwalVA/sympy,shikil/sympy,mcdaniel67/sympy,MridulS/sympy,ahhda/sympy,Mitchkoens/sympy,farhaanbukhsh/sympy,Arafatk/sympy,Designist/sympy,jerli/sympy,bukzor/sympy,AunShiLord/sympy,bukzor/sympy,aktech/sympy,jamesblunt/sympy,jaimahajan1997/sympy,jerli/sympy,ga7g08/sympy,Shaswat27/sympy,liangjiaxing/sympy,Gadal/sympy,farhaanbukhsh/sympy,jbbskinny/sympy,Davidjohnwilson/sympy,cccfran/sympy,wanglongqi/sympy,yukoba/sympy,wyom/sympy,Mitchkoens/sympy,maniteja123/sympy,sahilshekhawat/sympy,kaichogami/sympy,Vishluck/sympy,sunny94/temp,Davidjohnwilson/sympy,AkademieOlympia/sympy,wanglongqi/sympy,beni55/sympy,grevutiu-gabriel/sympy,cccfran/sympy,AunShiLord/sympy,skidzo/sympy,oliverlee/sympy,garvitr/sympy,diofant/diofant,Davidjohnwilson/sympy,sampadsaha5/sympy,sunny94/temp,cswiercz/sympy,atsao72/sympy,dqnykamp/sympy,shikil/sympy,Titan-C/sympy,drufat/sympy,lindsayad/sympy,Sumith1896/sympy,kevalds51/sympy,toolforger/sympy,vipulroxx/sympy,oliverlee/sympy,saurabhjn76/sympy,iamutkarshtiwari/sympy,sampadsaha5/sympy,abloomston/sympy,pbrady/sympy,AunShiLord/sympy,MechCoder/sympy,oliverlee/sympy,chaffra/sympy,skidzo/sympy,Vishluck/sympy,jerli/sympy,shikil/sympy,kevalds51/sympy,beni55/sympy,mcdaniel67/sympy,meghana1995/sympy,debugger22/sympy,souravsingh/sympy,ChristinaZografou/sympy,hargup/sympy,hargup/sympy,Designist/sympy,sahilshekhawat/sympy,kaushik94/sympy,grevutiu-gabriel/sympy,yukoba/sympy,skidzo/sympy,kumarkrishna/sympy,MechCoder/sympy,atreyv/sympy,ga7g08/sympy,pandeyadarsh/sympy,pandeyadarsh/sympy,AkademieOlympia/sympy,atreyv/sympy,mafiya69/sympy,liangjiaxing/sympy,mafiya69/sympy,Titan-C/sympy,iamutkarshtiwari/sympy,dqnykamp/sympy | ---
+++
@@ -8,5 +8,4 @@
SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt",
useinstead="sympy.physics.optics.gaussopt",
- deprecated_since_version="0.7.6").warn()
-
+ deprecated_since_version="0.7.6", issue=7659).warn() |
745b0b2d83cdbd28fcb4f565b77b31ef6f888350 | openmc/capi/__init__.py | openmc/capi/__init__.py | """
This module provides bindings to C functions defined by OpenMC shared library.
When the :mod:`openmc` package is imported, the OpenMC shared library is
automatically loaded. Calls to the OpenMC library can then be via functions or
objects in the :mod:`openmc.capi` subpackage, for example:
.. code-block:: python
openmc.capi.init()
openmc.capi.run()
openmc.capi.finalize()
"""
from ctypes import CDLL
import sys
from warnings import warn
import pkg_resources
# Determine shared-library suffix
if sys.platform == 'darwin':
_suffix = 'dylib'
else:
_suffix = 'so'
# Open shared library
_filename = pkg_resources.resource_filename(
__name__, '_libopenmc.{}'.format(_suffix))
try:
_dll = CDLL(_filename)
except OSError:
warn("OpenMC shared library is not available from the Python API. This "
"means you will not be able to use openmc.capi to make in-memory "
"calls to OpenMC.")
else:
from .error import *
from .core import *
from .nuclide import *
from .material import *
from .cell import *
from .tally import *
| """
This module provides bindings to C functions defined by OpenMC shared library.
When the :mod:`openmc` package is imported, the OpenMC shared library is
automatically loaded. Calls to the OpenMC library can then be via functions or
objects in the :mod:`openmc.capi` subpackage, for example:
.. code-block:: python
openmc.capi.init()
openmc.capi.run()
openmc.capi.finalize()
"""
from ctypes import CDLL
import sys
from warnings import warn
import pkg_resources
# Determine shared-library suffix
if sys.platform == 'darwin':
_suffix = 'dylib'
else:
_suffix = 'so'
# Open shared library
_filename = pkg_resources.resource_filename(
__name__, '_libopenmc.{}'.format(_suffix))
_dll = CDLL(_filename)
from .error import *
from .core import *
from .nuclide import *
from .material import *
from .cell import *
from .tally import *
| Remove try/except block around CDLL | Remove try/except block around CDLL
| Python | mit | walshjon/openmc,johnnyliu27/openmc,liangjg/openmc,shikhar413/openmc,amandalund/openmc,liangjg/openmc,liangjg/openmc,shikhar413/openmc,wbinventor/openmc,liangjg/openmc,mit-crpg/openmc,amandalund/openmc,smharper/openmc,walshjon/openmc,smharper/openmc,johnnyliu27/openmc,smharper/openmc,shikhar413/openmc,wbinventor/openmc,amandalund/openmc,paulromano/openmc,mit-crpg/openmc,amandalund/openmc,walshjon/openmc,johnnyliu27/openmc,mit-crpg/openmc,paulromano/openmc,wbinventor/openmc,walshjon/openmc,shikhar413/openmc,smharper/openmc,wbinventor/openmc,paulromano/openmc,mit-crpg/openmc,johnnyliu27/openmc,paulromano/openmc | ---
+++
@@ -28,16 +28,11 @@
# Open shared library
_filename = pkg_resources.resource_filename(
__name__, '_libopenmc.{}'.format(_suffix))
-try:
- _dll = CDLL(_filename)
-except OSError:
- warn("OpenMC shared library is not available from the Python API. This "
- "means you will not be able to use openmc.capi to make in-memory "
- "calls to OpenMC.")
-else:
- from .error import *
- from .core import *
- from .nuclide import *
- from .material import *
- from .cell import *
- from .tally import *
+_dll = CDLL(_filename)
+
+from .error import *
+from .core import *
+from .nuclide import *
+from .material import *
+from .cell import *
+from .tally import * |
3f0a3cd5540680be07e25afe282ed7df7381e802 | tests/testVpns.py | tests/testVpns.py | import json
import os
import sys
sys.path.append('..')
from skytap.Vpns import Vpns # noqa
vpns = Vpns()
def test_vpn_count():
"""Test VPN count."""
assert len(vpns) > 0, 'Vpn list is empty.'
def test_vpn_id():
"""Ensure each VPN has an ID."""
for v in vpns:
assert len(v.id) > 0
def test_vpn_json():
"""Ensure vpn json conversion seems to be working."""
for l in list(vpns.data):
v = vpns[l]
assert len(json.dumps(v.json())) > 0
def test_vpn_string_conversion():
"""Ensure string conversion works."""
for v in vpns:
assert len(str(v)) > 0
| import json
import os
import sys
sys.path.append('..')
from skytap.Vpns import Vpns # noqa
vpns = Vpns()
def test_vpn_id():
"""Ensure each VPN has an ID."""
for v in vpns:
assert len(v.id) > 0
def test_vpn_json():
"""Ensure vpn json conversion seems to be working."""
for l in list(vpns.data):
v = vpns[l]
assert len(json.dumps(v.json())) > 0
def test_vpn_string_conversion():
"""Ensure string conversion works."""
for v in vpns:
assert len(str(v)) > 0
| Remove check for existance of VPNs. Not having them may be correct | Remove check for existance of VPNs. Not having them may be correct
| Python | mit | FulcrumIT/skytap,mapledyne/skytap | ---
+++
@@ -6,12 +6,6 @@
from skytap.Vpns import Vpns # noqa
vpns = Vpns()
-
-
-def test_vpn_count():
- """Test VPN count."""
- assert len(vpns) > 0, 'Vpn list is empty.'
-
def test_vpn_id():
"""Ensure each VPN has an ID.""" |
b9c6d875bcddca73deaff35e14a56e373e5dcf46 | alerta/app/shell.py | alerta/app/shell.py |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)'
)
parser.add_argument(
'-P',
'--port',
type=int,
default=8080,
help='Listen port (default: 8080)'
)
parser.add_argument(
'-H',
'--host',
type=str,
default='0.0.0.0',
help='Bind host (default: 0.0.0.0)'
)
parser.add_argument(
'--debug',
action='store_true',
default=False,
help='Debug output'
)
args = parser.parse_args()
LOG.info('Starting alerta version %s ...', __version__)
LOG.info('Using MongoDB version %s ...', db.get_version())
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
|
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
'-H',
'--host',
type=str,
default='0.0.0.0',
help='Bind host'
)
parser.add_argument(
'-P',
'--port',
type=int,
default=8080,
help='Listen port'
)
parser.add_argument(
'--debug',
action='store_true',
default=False,
help='Debug output'
)
args = parser.parse_args()
LOG.info('Starting alerta version %s ...', __version__)
LOG.info('Using MongoDB version %s ...', db.get_version())
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
| Use argparse helper to add default values | Use argparse helper to add default values
| Python | apache-2.0 | guardian/alerta,skob/alerta,skob/alerta,guardian/alerta,guardian/alerta,guardian/alerta,skob/alerta,skob/alerta | ---
+++
@@ -11,21 +11,22 @@
parser = argparse.ArgumentParser(
prog='alertad',
- description='Alerta server (for development purposes only)'
+ description='Alerta server (for development purposes only)',
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
+ )
+ parser.add_argument(
+ '-H',
+ '--host',
+ type=str,
+ default='0.0.0.0',
+ help='Bind host'
)
parser.add_argument(
'-P',
'--port',
type=int,
default=8080,
- help='Listen port (default: 8080)'
- )
- parser.add_argument(
- '-H',
- '--host',
- type=str,
- default='0.0.0.0',
- help='Bind host (default: 0.0.0.0)'
+ help='Listen port'
)
parser.add_argument(
'--debug', |
9c84e5d4c1ef0670b3b6622fb7946486f78ff7fe | capstone/util/c4uci.py | capstone/util/c4uci.py | from __future__ import division, print_function, unicode_literals
from capstone.game import Connect4 as C4
def load_instance(instance):
'''
Loads a position from the UCI Connect 4 database:
https://archive.ics.uci.edu/ml/machine-learning-databases/connect-4/connect-4.names
Returns a tuple with an instance of a Connect4 game with that position, and the
outcome for the first player under perfect play.
'''
tokens = instance.split(',')
cells = tokens[:-1]
outcome = tokens[-1]
cell_map = {'x': 'X', 'o': 'O', 'b': '-'}
board = [[' '] * C4.COLS for row in range(C4.ROWS)]
for ix, cell in enumerate(cells):
row = C4.ROWS - (ix % C4.ROWS) - 1
col = ix // C4.ROWS
board[row][col] = cell_map[cell]
return C4(board), outcome
| from __future__ import division, print_function, unicode_literals
from capstone.game import Connect4 as C4
def load_instance(instance):
'''
Loads a position from the UCI Connect 4 database:
https://archive.ics.uci.edu/ml/machine-learning-databases/connect-4/connect-4.names
Returns a tuple with an instance of a Connect4 game with that position, and the
outcome for the first player under perfect play.
'''
instance = instance.rstrip()
tokens = instance.split(',')
cells = tokens[:-1]
outcome = tokens[-1]
cell_map = {'x': 'X', 'o': 'O', 'b': '-'}
board = [[' '] * C4.COLS for row in range(C4.ROWS)]
for ix, cell in enumerate(cells):
row = C4.ROWS - (ix % C4.ROWS) - 1
col = ix // C4.ROWS
board[row][col] = cell_map[cell]
return C4(board), outcome
| Remove trailing line break from C4 UCI instance | Remove trailing line break from C4 UCI instance
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -11,6 +11,7 @@
Returns a tuple with an instance of a Connect4 game with that position, and the
outcome for the first player under perfect play.
'''
+ instance = instance.rstrip()
tokens = instance.split(',')
cells = tokens[:-1]
outcome = tokens[-1] |
3489cc9f6ab593cd3664f2086577a6fde5e4ab94 | dimod/compatibility23.py | dimod/compatibility23.py | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.iterkeys()
zip_longest = itertools.izip_longest
def getargspec(f):
return inspect.getargspec(f)
else:
range_ = range
zip_ = zip
def iteritems(d):
return iter(d.items())
def itervalues(d):
return iter(d.values())
def iterkeys(d):
return iter(d.keys())
zip_longest = itertools.zip_longest
def getargspec(f):
ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
# FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
argspec = inspect.getfullargspec(f)
return ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
| import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.iterkeys()
zip_longest = itertools.izip_longest
def getargspec(f):
return inspect.getargspec(f)
else:
range_ = range
zip_ = zip
def iteritems(d):
return iter(d.items())
def itervalues(d):
return iter(d.values())
def iterkeys(d):
return iter(d.keys())
zip_longest = itertools.zip_longest
_ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
def getargspec(f):
argspec = inspect.getfullargspec(f)
# FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
return _ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
| Move namedtuple definition outside of argspec function | Move namedtuple definition outside of argspec function
| Python | apache-2.0 | oneklc/dimod,oneklc/dimod | ---
+++
@@ -43,10 +43,10 @@
zip_longest = itertools.zip_longest
+ _ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
+
def getargspec(f):
- ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
+ argspec = inspect.getfullargspec(f)
+ # FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
- # FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
- argspec = inspect.getfullargspec(f)
-
- return ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
+ return _ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults) |
3c319e21ea026651ee568d3c2a74786d33257a93 | paystackapi/paystack.py | paystackapi/paystack.py | """Entry point defined here."""
from paystackapi.cpanel import ControlPanel
from paystackapi.customer import Customer
from paystackapi.invoice import Invoice
from paystackapi.misc import Misc
from paystackapi.page import Page
from paystackapi.plan import Plan
from paystackapi.product import Product
from paystackapi.refund import Refund
from paystackapi.settlement import Settlement
from paystackapi.subaccount import SubAccount
from paystackapi.subscription import Subscription
from paystackapi.transaction import Transaction
from paystackapi.transfer import Transfer
from paystackapi.trecipient import TransferRecipient
from paystackapi.verification import Verification
from paystackapi.base import PayStackBase
class Paystack(PayStackBase):
"""Base class defined for PayStack Instance Method."""
def __init__(self, secret_key=None):
"""Instantiate Basic Classes to call here."""
PayStackBase.__init__(self, secret_key=secret_key)
self.cpanel = ControlPanel
self.customer = Customer
self.invoice = Invoice
self.misc = Misc
self.page = Page
self.plan = Plan
self.product = Product
self.refund = Refund
self.settlement = Settlement
self.subaccount = SubAccount
self.subscription = Subscription
self.transaction = Transaction
self.transfer = Transfer
self.transferRecipient = TransferRecipient
self.verification = Verification
| """Entry point defined here."""
from paystackapi.charge import Charge
from paystackapi.cpanel import ControlPanel
from paystackapi.customer import Customer
from paystackapi.invoice import Invoice
from paystackapi.misc import Misc
from paystackapi.page import Page
from paystackapi.plan import Plan
from paystackapi.product import Product
from paystackapi.refund import Refund
from paystackapi.settlement import Settlement
from paystackapi.subaccount import SubAccount
from paystackapi.subscription import Subscription
from paystackapi.transaction import Transaction
from paystackapi.transfer import Transfer
from paystackapi.trecipient import TransferRecipient
from paystackapi.verification import Verification
from paystackapi.base import PayStackBase
class Paystack(PayStackBase):
"""Base class defined for PayStack Instance Method."""
def __init__(self, secret_key=None):
"""Instantiate Basic Classes to call here."""
PayStackBase.__init__(self, secret_key=secret_key)
self.charge = Charge
self.cpanel = ControlPanel
self.customer = Customer
self.invoice = Invoice
self.misc = Misc
self.page = Page
self.plan = Plan
self.product = Product
self.refund = Refund
self.settlement = Settlement
self.subaccount = SubAccount
self.subscription = Subscription
self.transaction = Transaction
self.transfer = Transfer
self.transferRecipient = TransferRecipient
self.verification = Verification
| Add charge to Paystack class | Add charge to Paystack class
| Python | mit | andela-sjames/paystack-python | ---
+++
@@ -1,4 +1,5 @@
"""Entry point defined here."""
+from paystackapi.charge import Charge
from paystackapi.cpanel import ControlPanel
from paystackapi.customer import Customer
from paystackapi.invoice import Invoice
@@ -24,6 +25,7 @@
def __init__(self, secret_key=None):
"""Instantiate Basic Classes to call here."""
PayStackBase.__init__(self, secret_key=secret_key)
+ self.charge = Charge
self.cpanel = ControlPanel
self.customer = Customer
self.invoice = Invoice
@@ -39,4 +41,3 @@
self.transfer = Transfer
self.transferRecipient = TransferRecipient
self.verification = Verification
- |
19857719f3a68d14c1221bb04193a69379a8bf89 | examples/g/modulegen.py | examples/g/modulegen.py | #! /usr/bin/env python
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
def my_module_gen(out_file):
mod = Module('g')
mod.add_include('"g.h"')
mod.add_function('GDoA', None, [])
G = mod.add_cpp_namespace("G")
G.add_function('GDoB', None, [])
GInner = G.add_cpp_namespace("GInner")
GInner.add_function('GDoC', None, [])
mod.generate(FileCodeSink(out_file))
if __name__ == '__main__':
my_module_gen(sys.stdout)
| #! /usr/bin/env python
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
def my_module_gen(out_file):
mod = Module('g')
mod.add_include('"g.h"')
mod.add_function('GDoA', None, [])
G = mod.add_cpp_namespace("G")
G.add_function('GDoB', None, [])
GInner = G.add_cpp_namespace("GInner")
GInner.add_function('GDoC', None, [])
G.add_include('<fstream>')
ofstream = G.add_class('ofstream', foreign_cpp_namespace='::std')
ofstream.add_enum('openmode', [
('app', 'std::ios_base::app'),
('ate', 'std::ios_base::ate'),
('binary', 'std::ios_base::binary'),
('in', 'std::ios_base::in'),
('out', 'std::ios_base::out'),
('trunc', 'std::ios_base::trunc'),
])
ofstream.add_constructor([Parameter.new("const char *", 'filename'),
Parameter.new("::std::ofstream::openmode", 'mode', default_value="std::ios_base::out")])
ofstream.add_method('close', None, [])
mod.generate(FileCodeSink(out_file))
if __name__ == '__main__':
my_module_gen(sys.stdout)
| Add wrapping of std::ofstream to the example | Add wrapping of std::ofstream to the example
| Python | lgpl-2.1 | cawka/pybindgen,caramucho/pybindgen,cawka/pybindgen,cawka/pybindgen,caramucho/pybindgen,cawka/pybindgen,caramucho/pybindgen,caramucho/pybindgen | ---
+++
@@ -15,6 +15,21 @@
GInner = G.add_cpp_namespace("GInner")
GInner.add_function('GDoC', None, [])
+ G.add_include('<fstream>')
+
+ ofstream = G.add_class('ofstream', foreign_cpp_namespace='::std')
+ ofstream.add_enum('openmode', [
+ ('app', 'std::ios_base::app'),
+ ('ate', 'std::ios_base::ate'),
+ ('binary', 'std::ios_base::binary'),
+ ('in', 'std::ios_base::in'),
+ ('out', 'std::ios_base::out'),
+ ('trunc', 'std::ios_base::trunc'),
+ ])
+ ofstream.add_constructor([Parameter.new("const char *", 'filename'),
+ Parameter.new("::std::ofstream::openmode", 'mode', default_value="std::ios_base::out")])
+ ofstream.add_method('close', None, [])
+
mod.generate(FileCodeSink(out_file))
if __name__ == '__main__': |
d5819e689ee5284b5c6aae28d20a6ef88051b4ef | vscode_manual/install_extensions.py | vscode_manual/install_extensions.py | #!/usr/bin/env python
# Install VSCode Extensions from file.
from __future__ import print_function
import subprocess
EXTENSIONS_FILE = "extensions.txt"
def extensions(filename):
""" Yield each of the extensions in the given file. """
with open(filename) as extension_file:
for extension in extension_file:
yield extension
def install_extension(extension):
""" Install the given extension. """
cmd_list = ["code", "--install-extension", extension]
print(" ".join(cmd_list), end="")
subprocess.call(cmd_list, shell=True)
def main():
for extension in extensions(EXTENSIONS_FILE):
install_extension(extension)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# Install VSCode Extensions from file.
#
# Instead of writing this, could have just written:
# cat extensions.txt | xargs -L 1 code --install-extension
from __future__ import print_function
import subprocess
EXTENSIONS_FILE = "extensions.txt"
def extensions(filename):
""" Yield each of the extensions in the given file. """
with open(filename) as extension_file:
for extension in extension_file:
yield extension
def install_extension(extension):
""" Install the given extension. """
cmd_list = ["code", "--install-extension", extension]
print(" ".join(cmd_list), end="")
subprocess.call(cmd_list, shell=True)
def main():
for extension in extensions(EXTENSIONS_FILE):
install_extension(extension)
if __name__ == '__main__':
main()
| Add snarky comment in VSCode Extension Installer. | Add snarky comment in VSCode Extension Installer.
| Python | mit | kashev/dotfiles,kashev/dotfiles | ---
+++
@@ -1,5 +1,8 @@
#!/usr/bin/env python
# Install VSCode Extensions from file.
+#
+# Instead of writing this, could have just written:
+# cat extensions.txt | xargs -L 1 code --install-extension
from __future__ import print_function
|
92b90cbdd41905d69863b7cd329d8280a3662db8 | chrome/common/extensions/docs/server2/url_constants.py | chrome/common/extensions/docs/server2/url_constants.py | # Copyright (c) 2012 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.
GITHUB_URL = 'https://api.github.com/repos/GoogleChrome/chrome-app-samples'
NEW_GITHUB_URL = 'https://api.github.com/repos'
GITHUB_BASE = 'https://github.com/GoogleChrome/chrome-app-samples/tree/master'
RAW_GITHUB_BASE = ('https://github.com/GoogleChrome/chrome-app-samples/raw/'
'master')
OMAHA_PROXY_URL = 'http://omahaproxy.appspot.com/json'
OMAHA_DEV_HISTORY = ('http://omahaproxy.appspot.com/history?channel=dev'
'&os=win&json=1')
SVN_URL = 'http://src.chromium.org/chrome'
VIEWVC_URL = 'http://src.chromium.org/viewvc/chrome'
EXTENSIONS_SAMPLES = ('http://src.chromium.org/viewvc/chrome/trunk/src/chrome/'
'common/extensions/docs/examples')
CODEREVIEW_SERVER = 'https://chromiumcodereview.appspot.com'
| # Copyright (c) 2012 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.
GITHUB_URL = 'https://api.github.com/repos/GoogleChrome/chrome-app-samples'
NEW_GITHUB_URL = 'https://api.github.com/repos'
GITHUB_BASE = 'https://github.com/GoogleChrome/chrome-app-samples/tree/master'
RAW_GITHUB_BASE = ('https://github.com/GoogleChrome/chrome-app-samples/raw/'
'master')
OMAHA_PROXY_URL = 'http://omahaproxy.appspot.com/json'
OMAHA_DEV_HISTORY = ('http://omahaproxy.appspot.com/history?channel=dev'
'&os=win&json=1')
SVN_URL = 'http://src.chromium.org/chrome'
VIEWVC_URL = 'http://src.chromium.org/viewvc/chrome'
EXTENSIONS_SAMPLES = ('http://src.chromium.org/viewvc/chrome/trunk/src/chrome/'
'common/extensions/docs/examples')
CODEREVIEW_SERVER = 'https://codereview.chromium.org'
| Use codereview.chromium.org instead of chromiumcodereview.appspot.com in extensions doc script. | Use codereview.chromium.org instead of chromiumcodereview.appspot.com in extensions doc script.
BUG=273810
R=kalman@chromium.org, kalman
Review URL: https://codereview.chromium.org/24980005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@225762 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | anirudhSK/chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,M4sse/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,ltilve/chromium,ltilve/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,dednal/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ltilve/chromium,ChromiumWebApps/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,jaruba/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,dednal/chromium.src,dednal/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,ltilve/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk | ---
+++
@@ -14,4 +14,4 @@
VIEWVC_URL = 'http://src.chromium.org/viewvc/chrome'
EXTENSIONS_SAMPLES = ('http://src.chromium.org/viewvc/chrome/trunk/src/chrome/'
'common/extensions/docs/examples')
-CODEREVIEW_SERVER = 'https://chromiumcodereview.appspot.com'
+CODEREVIEW_SERVER = 'https://codereview.chromium.org' |
5012ff1dfbcd8e7d0d9b0691f45c7b3efd811a08 | adventure/__init__.py | adventure/__init__.py | """The Adventure game."""
def load_advent_dat(data):
import os
from .data import parse
datapath = os.path.join(os.path.dirname(__file__), 'advent.dat')
with open(datapath, 'r', encoding='ascii') as datafile:
parse(data, datafile)
def play(seed=None):
"""Turn the Python prompt into an Adventure game.
With `seed` the caller can supply an integer to start the random
number generator at a known state. When `quiet` is true, no output
is printed as the game is played; the caller of a command has to
manually check `_game.output` for the result, which makes it
possible to write very quiet tests.
"""
global _game
from .game import Game
from .prompt import install_words
_game = Game(seed)
load_advent_dat(_game)
install_words(_game)
_game.start()
print(_game.output[:-1])
def resume(savefile, quiet=False):
global _game
from .game import Game
from .prompt import install_words
_game = Game.resume(savefile)
install_words(_game)
if not quiet:
print('GAME RESTORED\n')
| """The Adventure game."""
def load_advent_dat(data):
import os
from .data import parse
datapath = os.path.join(os.path.dirname(__file__), 'advent.dat')
with open(datapath, 'r', encoding='ascii') as datafile:
parse(data, datafile)
def play(seed=None):
"""Turn the Python prompt into an Adventure game.
With optional the `seed` argument the caller can supply an integer
to start the Python random number generator at a known state.
"""
global _game
from .game import Game
from .prompt import install_words
_game = Game(seed)
load_advent_dat(_game)
install_words(_game)
_game.start()
print(_game.output[:-1])
def resume(savefile, quiet=False):
global _game
from .game import Game
from .prompt import install_words
_game = Game.resume(savefile)
install_words(_game)
if not quiet:
print('GAME RESTORED\n')
| Remove outdated parameter from docstring | Remove outdated parameter from docstring
| Python | apache-2.0 | devinmcgloin/advent,devinmcgloin/advent | ---
+++
@@ -11,11 +11,8 @@
def play(seed=None):
"""Turn the Python prompt into an Adventure game.
- With `seed` the caller can supply an integer to start the random
- number generator at a known state. When `quiet` is true, no output
- is printed as the game is played; the caller of a command has to
- manually check `_game.output` for the result, which makes it
- possible to write very quiet tests.
+ With optional the `seed` argument the caller can supply an integer
+ to start the Python random number generator at a known state.
"""
global _game |
d1d668139be98283dc9582c32fadf7de2b30914d | src/identfilter.py | src/identfilter.py | import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about Graphene types
if not text.startswith('graphene_') and not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to do this for types like graphene_point3d_t, which
# need to be transformed into GraphenePoint3D, not GraphenePoint3d
matches = NUMBER_REGEX.match(uc_token)
if matches and matches.group(2):
uc_token = ''.join([matches.group(1), matches.group(2).title])
res.append(uc_token)
return ''.join(res)
if __name__ == '__main__':
in_text = sys.stdin.read()
sys.stdout.write(to_camel_case(in_text))
| # Copyright 2014 Emmanuele Bassi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import re
NUMBER_REGEX = re.compile(r'([0-9])([a-z])')
def to_camel_case(text):
# We only care about Graphene types
if not text.startswith('graphene_') and not text.endswith('_t'):
return text
res = []
for token in text[:-2].split('_'):
uc_token = token.title()
# We need to do this for types like graphene_point3d_t, which
# need to be transformed into GraphenePoint3D, not GraphenePoint3d
matches = NUMBER_REGEX.match(uc_token)
if matches and matches.group(2):
uc_token = ''.join([matches.group(1), matches.group(2).title])
res.append(uc_token)
return ''.join(res)
if __name__ == '__main__':
in_text = sys.stdin.read()
sys.stdout.write(to_camel_case(in_text))
| Add licensing to the introspection filter | Add licensing to the introspection filter
It's a small utility script, but it's better to have a license for it
anyway.
| Python | mit | ebassi/graphene,ebassi/graphene | ---
+++
@@ -1,3 +1,23 @@
+# Copyright 2014 Emmanuele Bassi
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
import sys
import re
|
1a48f85e04f9192ccf9ba675ff8ddd5719752950 | infrastructure/control/simple/src/start-opensim.py | infrastructure/control/simple/src/start-opensim.py | #!/usr/bin/python
import os.path
import sys
### CONFIGURE THESE PATHS ###
binaryPath = "/home/opensim/opensim/opensim-current/bin"
pidPath = "/tmp/OpenSim.pid"
### END OF CONFIG ###
if not os.path.exists(pidPath):
print >> sys.stderr, "ERROR: OpenSim PID file %s still present. Assuming OpenSim has been started already." % pidPath
sys.exit(1)
| #!/usr/bin/python
import os.path
import re
import subprocess
import sys
### CONFIGURE THESE PATHS ###
binaryPath = "/home/opensim/opensim/opensim-current/bin"
pidPath = "/tmp/OpenSim.pid"
### END OF CONFIG ###
if os.path.exists(pidPath):
print >> sys.stderr, "ERROR: OpenSim PID file %s still present. Assuming OpenSim has been started already." % pidPath
sys.exit(1)
# If PID isn't set then we'll check the screen list.
# However, this is a much less perfect mechanism since OpenSimulator may have been started outside screen
screenList = ""
try:
screenList = subprocess.check_output("screen -list", shell=True)
except:
None
if re.match("\s+\d+\.OpenSim", screenList):
print >> sys.stderr, "ERROR: Screen session for OpenSim already started."
sys.exit(1)
| Add screen -list check, fix initial pid check | Add screen -list check, fix initial pid check
| Python | bsd-3-clause | justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools | ---
+++
@@ -1,6 +1,8 @@
#!/usr/bin/python
import os.path
+import re
+import subprocess
import sys
### CONFIGURE THESE PATHS ###
@@ -8,6 +10,19 @@
pidPath = "/tmp/OpenSim.pid"
### END OF CONFIG ###
-if not os.path.exists(pidPath):
+if os.path.exists(pidPath):
print >> sys.stderr, "ERROR: OpenSim PID file %s still present. Assuming OpenSim has been started already." % pidPath
sys.exit(1)
+
+# If PID isn't set then we'll check the screen list.
+# However, this is a much less perfect mechanism since OpenSimulator may have been started outside screen
+screenList = ""
+
+try:
+ screenList = subprocess.check_output("screen -list", shell=True)
+except:
+ None
+
+if re.match("\s+\d+\.OpenSim", screenList):
+ print >> sys.stderr, "ERROR: Screen session for OpenSim already started."
+ sys.exit(1) |
bd5a6b1983851d8d696390b19fae862775ee0084 | apps/i4p_base/urls.py | apps/i4p_base/urls.py | #-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
#url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider-bestof'),
url(r'^homepage/ajax/slider/latest/$', ajax.slider_latest, name='i4p-homepage-ajax-slider-latest'),
url(r'^homepage/ajax/slider/commented/$', ajax.slider_most_commented, name='i4p-homepage-ajax-slider-commented'),
url(r'^history/check_version/(?P<pk>[\d]+)$', views.VersionActivityCheckView.as_view(), name='history-check-version'),
url(r'^search/', search_view_factory(view_class=views.SearchView), name='i4p-search'),
url(r'^location/(?P<location_id>\d+)', views.LocationEditView.as_view(), name='i4p-location-edit'),
url(r'^locations/$', views.LocationListView.as_view(), name='i4p-location-list'),
url(r'^locations/missing/(?P<missing_field_name>\w+)$', views.LocationListView.as_view(), name='i4p-location-missing-list'),
)
| #-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider-bestof'),
url(r'^homepage/ajax/slider/latest/$', ajax.slider_latest, name='i4p-homepage-ajax-slider-latest'),
url(r'^homepage/ajax/slider/commented/$', ajax.slider_most_commented, name='i4p-homepage-ajax-slider-commented'),
url(r'^history/check_version/(?P<pk>[\d]+)$', views.VersionActivityCheckView.as_view(), name='history-check-version'),
url(r'^search/', search_view_factory(view_class=views.SearchView), name='i4p-search'),
url(r'^location/(?P<location_id>\d+)', views.LocationEditView.as_view(), name='i4p-location-edit'),
url(r'^locations/$', views.LocationListView.as_view(), name='i4p-location-list'),
url(r'^locations/missing/(?P<missing_field_name>\w+)$', views.LocationListView.as_view(), name='i4p-location-missing-list'),
)
| Revert "Remove explicit link to homepage view in i3p_base" | Revert "Remove explicit link to homepage view in i3p_base"
This reverts commit 3d4327f6d9d71c6b396b0655de81373210417aba.
| Python | agpl-3.0 | ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople | ---
+++
@@ -7,7 +7,7 @@
import ajax
urlpatterns = patterns('',
- #url(r'^$', views.homepage, name='i4p-index'),
+ url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider-bestof'),
url(r'^homepage/ajax/slider/latest/$', ajax.slider_latest, name='i4p-homepage-ajax-slider-latest'),
url(r'^homepage/ajax/slider/commented/$', ajax.slider_most_commented, name='i4p-homepage-ajax-slider-commented'), |
ffe9bba2e4045236a3f3731e39876b6220f8f9a1 | jarviscli/plugins/joke_of_day.py | jarviscli/plugins/joke_of_day.py | from plugin import plugin, require
import requests
from colorama import Fore
from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
spinner.start()
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
spinner.stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| from plugin import plugin, require
import requests
from colorama import Fore
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
while True:
url = "https://api.jokes.one/jod"
jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| Update joke of day: Fix for moved SpinnerThread | Update joke of day: Fix for moved SpinnerThread
| Python | mit | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis | ---
+++
@@ -1,7 +1,6 @@
from plugin import plugin, require
import requests
from colorama import Fore
-from plugins.animations import SpinnerThread
@require(network=True)
@@ -24,16 +23,15 @@
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
- spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
- spinner.start()
+ jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
- spinner.stop()
+ jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch): |
b0e558b70613871097361ee3c1f016aa60e4c2f1 | processors/yui.py | processors/yui.py |
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
ERROR_STRING = ("Failed to execute Java VM or yuicompressor. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"YUICOMPRESSOR_PATH in your settings correctly.\n"
"Error was: %s")
class YUI(Processor):
def process(self, inputs):
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.YUI_COMPRESSOR_BINARY
try:
for filename, contents in inputs.items():
filetype = os.path.splitext(filename)[-1].lstrip(".")
cmd = Popen([
'java', '-jar', compressor,
'--charset', 'utf-8', '--type', filetype],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
if error != '':
raise ValueError(ERROR_STRING % error)
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
except Exception, e:
raise ValueError(ERROR_STRING % e)
return outputs
|
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
ERROR_STRING = ("Failed to execute Java VM or yuicompressor. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"YUICOMPRESSOR_PATH in your settings correctly.\n"
"Error was: %s")
class YUI(Processor):
def process(self, inputs):
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.YUI_COMPRESSOR_BINARY
for filename, contents in inputs.items():
filetype = os.path.splitext(filename)[-1].lstrip(".")
try:
cmd = Popen([
'java', '-jar', compressor,
'--charset', 'utf-8', '--type', filetype],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
except Exception, e:
raise ValueError(ERROR_STRING % e)
if error != '':
raise ValueError(ERROR_STRING % error)
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
return outputs
| Update YUI error handling logic | Update YUI error handling logic
| Python | bsd-2-clause | potatolondon/assetpipe | ---
+++
@@ -21,9 +21,10 @@
outputs = OrderedDict()
compressor = settings.YUI_COMPRESSOR_BINARY
- try:
- for filename, contents in inputs.items():
- filetype = os.path.splitext(filename)[-1].lstrip(".")
+ for filename, contents in inputs.items():
+ filetype = os.path.splitext(filename)[-1].lstrip(".")
+
+ try:
cmd = Popen([
'java', '-jar', compressor,
'--charset', 'utf-8', '--type', filetype],
@@ -31,16 +32,15 @@
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
+ except Exception, e:
+ raise ValueError(ERROR_STRING % e)
- if error != '':
- raise ValueError(ERROR_STRING % error)
+ if error != '':
+ raise ValueError(ERROR_STRING % error)
- file_out = StringIO.StringIO()
- file_out.write(output)
- file_out.seek(0)
- outputs[filename] = file_out
-
- except Exception, e:
- raise ValueError(ERROR_STRING % e)
+ file_out = StringIO.StringIO()
+ file_out.write(output)
+ file_out.seek(0)
+ outputs[filename] = file_out
return outputs |
34186d908af01aa05d255e91aba085d1ca4f1837 | wger/manager/migrations/0011_remove_set_exercises.py | wger/manager/migrations/0011_remove_set_exercises.py | # Generated by Django 3.1.5 on 2021-02-28 14:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manager', '0010_auto_20210102_1446'),
]
operations = [
migrations.RemoveField(
model_name='set',
name='exercises',
),
]
| # Generated by Django 3.1.5 on 2021-02-28 14:10
from django.db import migrations
def increment_order(apps, schema_editor):
"""
Increment the oder in settings so ensure the order is preserved
Otherwise, and depending on the database, when a set has supersets, the
exercises could be ordered alphabetically.
"""
WorkoutSet = apps.get_model("manager", "Set")
for workout_set in WorkoutSet.objects.all():
counter = 1
for exercise in workout_set.exercises.all():
for setting in workout_set.setting_set.filter(exercise=exercise):
setting.order = counter
setting.save()
counter += 1
class Migration(migrations.Migration):
dependencies = [
('manager', '0010_auto_20210102_1446'),
]
operations = [
migrations.RunPython(increment_order),
migrations.RemoveField(
model_name='set',
name='exercises',
),
]
| Increment the oder in settings so ensure the order is preserved | Increment the oder in settings so ensure the order is preserved
Otherwise, and depending on the database, when a set has supersets, the
exercises could be ordered alphabetically.
| Python | agpl-3.0 | wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,petervanderdoes/wger,petervanderdoes/wger,wger-project/wger,wger-project/wger,wger-project/wger | ---
+++
@@ -1,6 +1,25 @@
# Generated by Django 3.1.5 on 2021-02-28 14:10
from django.db import migrations
+
+
+def increment_order(apps, schema_editor):
+ """
+ Increment the oder in settings so ensure the order is preserved
+
+ Otherwise, and depending on the database, when a set has supersets, the
+ exercises could be ordered alphabetically.
+ """
+
+ WorkoutSet = apps.get_model("manager", "Set")
+
+ for workout_set in WorkoutSet.objects.all():
+ counter = 1
+ for exercise in workout_set.exercises.all():
+ for setting in workout_set.setting_set.filter(exercise=exercise):
+ setting.order = counter
+ setting.save()
+ counter += 1
class Migration(migrations.Migration):
@@ -10,6 +29,7 @@
]
operations = [
+ migrations.RunPython(increment_order),
migrations.RemoveField(
model_name='set',
name='exercises', |
420b9a4e2b52de7234734b9c457e0711bb0f1a70 | utils/lit/lit/__init__.py | utils/lit/lit/__init__.py | """'lit' Testing Tool"""
__author__ = 'Daniel Dunbar'
__email__ = 'daniel@minormatter.com'
__versioninfo__ = (0, 6, 0)
__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'
__all__ = []
| """'lit' Testing Tool"""
__author__ = 'Daniel Dunbar'
__email__ = 'daniel@minormatter.com'
__versioninfo__ = (0, 6, 0)
__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'
__all__ = []
from .main import main
| Fix issue which cases lit installed with setup.py to not resolve main | Fix issue which cases lit installed with setup.py to not resolve main
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@283818 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm | ---
+++
@@ -6,3 +6,5 @@
__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'
__all__ = []
+
+from .main import main |
f604de4794c87c155cdda758a43aa7261662dcff | examples/pystray_icon.py | examples/pystray_icon.py | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
raise NotImplementedError('This example does not work on macOS.')
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
| from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
import multiprocessing
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
webview_process = None
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
if __name__ == '__main__':
def start_webview_process():
global webview_process
webview_process = Process(target=run_webview)
webview_process.start()
def on_open(icon, item):
global webview_process
if not webview_process.is_alive():
start_webview_process()
def on_exit(icon, item):
icon.stop()
start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, menu=menu)
icon.run()
webview_process.terminate()
| Improve example, start pystray in main thread and webview in new process | Improve example, start pystray in main thread and webview in new process
| Python | bsd-3-clause | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview | ---
+++
@@ -2,12 +2,15 @@
from pystray import Icon, Menu, MenuItem
import webview
import sys
+import multiprocessing
if sys.platform == 'darwin':
- raise NotImplementedError('This example does not work on macOS.')
-
-from threading import Thread
-from queue import Queue
+ ctx = multiprocessing.get_context('spawn')
+ Process = ctx.Process
+ Queue = ctx.Queue
+else:
+ Process = multiprocessing.Process
+ Queue = multiprocessing.Queue
"""
@@ -15,39 +18,34 @@
"""
+webview_process = None
+
+
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
-def run_pystray(queue: Queue):
+if __name__ == '__main__':
+
+ def start_webview_process():
+ global webview_process
+ webview_process = Process(target=run_webview)
+ webview_process.start()
def on_open(icon, item):
- queue.put('open')
+ global webview_process
+ if not webview_process.is_alive():
+ start_webview_process()
def on_exit(icon, item):
icon.stop()
- queue.put('exit')
+
+ start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
- icon = Icon('Pystray', image, "Pystray", menu)
+ icon = Icon('Pystray', image, menu=menu)
icon.run()
-
-if __name__ == '__main__':
- queue = Queue()
-
- icon_thread = Thread(target=run_pystray, args=(queue,))
- icon_thread.start()
-
- run_webview()
-
- while True:
- event = queue.get()
- if event == 'open':
- run_webview()
- if event == 'exit':
- break
-
- icon_thread.join()
+ webview_process.terminate() |
7ef053749f4bfbcf7c2007a57d16139cfea09588 | jsonapi_requests/configuration.py | jsonapi_requests/configuration.py | from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
| from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
| Append slash to API root if needed. | Append slash to API root if needed.
| Python | bsd-3-clause | socialwifi/jsonapi-requests | ---
+++
@@ -22,7 +22,10 @@
@property
def API_ROOT(self):
- return self._config_dict['API_ROOT']
+ url = self._config_dict['API_ROOT']
+ if not url.endswith('/'):
+ url += '/'
+ return url
@property
def AUTH(self): |
e3bf9032e704989aee2044f90a053064e9fd9253 | preserved_game.py | preserved_game.py | from persistent_dict import *
class PreservedGame():
def game_name(self):
return "Freddo" # TODO
class AllPreservedGames():
def __init__(self, filename):
self.games = PersistentDict(filename, 'c', format='pickle')
def add_game(self, pg):
self.games[pg.game_name()] = pg
self.games.sync()
'''
# TODO
with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
print(d, 'start')
d['abc'] = '123'
d['rand'] = random.randrange(10000)
print(d, 'updated')
# Show what the file looks like on disk
with open('/tmp/demo.json', 'rb') as f:
print(f.read())
'''
| from persistent_dict import *
class PreservedGame():
def __init__(self, game):
self.rules = game.rules # .clone?
self.player = [None, game.player[1].key(), game.player[2].key()]
self.move_history = game.move_history[:]
def game_name(self):
return "Freddo" # TODO
class AllPreservedGames():
def __init__(self, filename):
self.games = PersistentDict(filename, 'c', format='pickle')
def add_game(self, pg):
self.games[pg.game_name()] = pg
self.games.sync()
def preserving(self):
return cfp
'''
# TODO
with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
print(d, 'start')
d['abc'] = '123'
d['rand'] = random.randrange(10000)
print(d, 'updated')
# Show what the file looks like on disk
with open('/tmp/demo.json', 'rb') as f:
print(f.read())
'''
| Store the player keys in the preserved games | Store the player keys in the preserved games
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | ---
+++
@@ -1,8 +1,16 @@
from persistent_dict import *
class PreservedGame():
+ def __init__(self, game):
+ self.rules = game.rules # .clone?
+
+ self.player = [None, game.player[1].key(), game.player[2].key()]
+
+ self.move_history = game.move_history[:]
+
def game_name(self):
return "Freddo" # TODO
+
class AllPreservedGames():
def __init__(self, filename):
@@ -11,6 +19,10 @@
def add_game(self, pg):
self.games[pg.game_name()] = pg
self.games.sync()
+
+ def preserving(self):
+ return cfp
+
'''
# TODO
with PersistentDict('/tmp/demo.json', 'c', format='json') as d: |
4dd13a8b031a57f6290fb43dc6daa5082041658a | dashboard/consumers.py | dashboard/consumers.py | from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
Group('btc-price').add(message.reply_channel)
message.reply_channel.send({
'accept': True
})
@channel_session_user
def ws_disconnect(message):
Group('btc-price').discard(message.reply_channel)
| import json
from channels import Group
from channels.auth import channel_session_user
@channel_session_user
def ws_connect(message):
Group('btc-price').add(message.reply_channel)
message.channel_session['coin-group'] = 'btc-price'
message.reply_channel.send({
'accept': True
})
@channel_session_user
def ws_receive(message):
data = json.loads(message.content.get('text'))
if data.get('coin') == 'litecoin':
Group('ltc-price').add(message.reply_channel)
Group('btc-price').discard(message.reply_channel)
message.channel_session['coin-group'] = 'ltc-price'
elif data.get('coin') == 'bitcoin':
Group('btc-price').add(message.reply_channel)
Group('ltc-price').discard(message.reply_channel)
message.channel_session['coin-group'] = 'btc-price'
@channel_session_user
def ws_disconnect(message):
user_group = message.channel_session['coin-group']
Group(user_group).discard(message.reply_channel)
| Add ws_receive consumer with channel_session_user decorator | Add ws_receive consumer with channel_session_user decorator
| Python | mit | alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor | ---
+++
@@ -1,11 +1,14 @@
+import json
+
from channels import Group
-from channels.auth import channel_session_user, channel_session_user_from_http
+from channels.auth import channel_session_user
-@channel_session_user_from_http
+@channel_session_user
def ws_connect(message):
+ Group('btc-price').add(message.reply_channel)
- Group('btc-price').add(message.reply_channel)
+ message.channel_session['coin-group'] = 'btc-price'
message.reply_channel.send({
'accept': True
@@ -13,5 +16,24 @@
@channel_session_user
+def ws_receive(message):
+ data = json.loads(message.content.get('text'))
+
+ if data.get('coin') == 'litecoin':
+ Group('ltc-price').add(message.reply_channel)
+ Group('btc-price').discard(message.reply_channel)
+
+ message.channel_session['coin-group'] = 'ltc-price'
+
+ elif data.get('coin') == 'bitcoin':
+ Group('btc-price').add(message.reply_channel)
+ Group('ltc-price').discard(message.reply_channel)
+
+ message.channel_session['coin-group'] = 'btc-price'
+
+
+@channel_session_user
def ws_disconnect(message):
- Group('btc-price').discard(message.reply_channel)
+ user_group = message.channel_session['coin-group']
+
+ Group(user_group).discard(message.reply_channel) |
495a33c0dbb2bd9174b15ea934b8282ca3b78929 | pytask/profile/utils.py | pytask/profile/utils.py | from django.http import Http404
from django.contrib.auth.models import User
from pytask.profile.models import Notification
def get_notification(nid, user):
""" if notification exists, and belongs to the current user, return it.
else return None.
"""
user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
current_notifications = user_notifications.filter(uniq_key=nid)
if user_notifications:
current_notification = current_notifications[0]
try:
newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
newest_notification = user_notifications.reverse()[0]
if newest_notification == newer_notification:
newest_notification = None
except Notification.DoesNotExist:
newest_notification, newer_notification = None, None
try:
older_notification = current_notification.get_previous_by_sent_date(sent_to=user, is_deleted=False)
oldest_notification = user_notifications[0]
if oldest_notification == older_notification:
oldest_notification = None
except:
oldest_notification, older_notification = None, None
return newest_notification, newer_notification, current_notification, older_notification, oldest_notification
else:
return None, None, None, None, None
def get_user(uid):
try:
user = User.objects.get(id=uid)
except User.DoesNotExist:
raise Http404
if user.is_active:
return user
else:
raise Http404
| from django import shortcuts
from django.http import Http404
from django.contrib.auth.models import User
from pytask.profile.models import Notification
def get_notification(nid, user):
""" if notification exists, and belongs to the current user, return it.
else return None.
"""
user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
current_notifications = user_notifications.filter(uniq_key=nid)
if user_notifications:
current_notification = current_notifications[0]
try:
newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
newest_notification = user_notifications.reverse()[0]
if newest_notification == newer_notification:
newest_notification = None
except Notification.DoesNotExist:
newest_notification, newer_notification = None, None
try:
older_notification = current_notification.get_previous_by_sent_date(sent_to=user, is_deleted=False)
oldest_notification = user_notifications[0]
if oldest_notification == older_notification:
oldest_notification = None
except:
oldest_notification, older_notification = None, None
return newest_notification, newer_notification, current_notification, older_notification, oldest_notification
else:
return None, None, None, None, None
def get_user(uid):
user = shortcuts.get_object_or_404(User, pk=uid)
if user.is_active:
return user
else:
raise Http404
| Use django shortcut for raising 404s. | Use django shortcut for raising 404s.
| Python | agpl-3.0 | madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask | ---
+++
@@ -1,3 +1,4 @@
+from django import shortcuts
from django.http import Http404
from django.contrib.auth.models import User
from pytask.profile.models import Notification
@@ -35,13 +36,9 @@
def get_user(uid):
- try:
- user = User.objects.get(id=uid)
- except User.DoesNotExist:
- raise Http404
+ user = shortcuts.get_object_or_404(User, pk=uid)
if user.is_active:
return user
else:
raise Http404
- |
3c145a47a20a55787b8ce8a4f00ff3449306ccbc | blazar/cmd/manager.py | blazar/cmd/manager.py | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import eventlet
eventlet.monkey_patch()
import gettext
import sys
from oslo_config import cfg
from oslo_service import service
gettext.install('blazar')
from blazar.db import api as db_api
from blazar.manager import service as manager_service
from blazar.notification import notifier
from blazar.utils import service as service_utils
def main():
cfg.CONF(project='blazar', prog='blazar-manager')
service_utils.prepare_service(sys.argv)
db_api.setup_db()
notifier.init()
service.launch(
cfg.CONF,
manager_service.ManagerService()
).wait()
if __name__ == '__main__':
main()
| # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import eventlet
eventlet.monkey_patch()
import gettext
import sys
from oslo_config import cfg
from oslo_service import service
gettext.install('blazar')
from blazar.db import api as db_api
from blazar.manager import service as manager_service
from blazar.notification import notifier
from blazar.utils import service as service_utils
def main():
cfg.CONF(project='blazar', prog='blazar-manager')
service_utils.prepare_service(sys.argv)
db_api.setup_db()
notifier.init()
service.launch(
cfg.CONF,
manager_service.ManagerService(),
restart_method='mutate'
).wait()
if __name__ == '__main__':
main()
| Enable mutable config in blazar | Enable mutable config in blazar
New releases of oslo.config support a 'mutable' parameter in Opts.
oslo.service provides an option [1] which allows services to tell it
they want mutate_config_files to be called by passing a parameter.
This commit is to use the same approach. This allows Blazar to benefit
from [2], where the 'debug' option (owned by oslo.log) is made mutable.
We should be able to turn debug logging on and off by changing the
config and sending a SIGHUP signal to blazar-manager.
However, please note that blazar-manager currently doesn't work
correctly after receiving a SIGHUP. As a result the mutable config is
not yet usable. Operators should continue restarting blazar-manager
after changing blazar.conf.
TC goal: https://governance.openstack.org/tc/goals/rocky/enable-mutable-configuration.html
[1] https://review.openstack.org/263312/
[2] https://review.openstack.org/254821/
Change-Id: Ieea9043b6f3a28dc92717680585614a68227120e
| Python | apache-2.0 | stackforge/blazar,stackforge/blazar,openstack/blazar,ChameleonCloud/blazar,ChameleonCloud/blazar,openstack/blazar | ---
+++
@@ -37,7 +37,8 @@
notifier.init()
service.launch(
cfg.CONF,
- manager_service.ManagerService()
+ manager_service.ManagerService(),
+ restart_method='mutate'
).wait()
|
e812791b42c16a809e9913d682562804f5335be6 | pytx/pytx/__init__.py | pytx/pytx/__init__.py | # import vocabulary
# from init import init
# from malware import Malware
# from threat_exchange_member import ThreatExchangeMember
# from threat_indicator import ThreatIndicator
| from init import init
from malware import Malware
from threat_exchange_member import ThreatExchangeMember
from threat_indicator import ThreatIndicator
__all__ = ['init', 'Malware', 'ThreatExchangeMember', 'ThreatIndicator']
| Add an `__all__` array to expose the public objects of the pytx module | Add an `__all__` array to expose the public objects of the pytx module
| Python | bsd-3-clause | theCatWisel/ThreatExchange,theCatWisel/ThreatExchange,mgoffin/ThreatExchange,theCatWisel/ThreatExchange,RyPeck/ThreatExchange,mgoffin/ThreatExchange,tiegz/ThreatExchange,mgoffin/ThreatExchange,tiegz/ThreatExchange,tiegz/ThreatExchange,wxsBSD/ThreatExchange,RyPeck/ThreatExchange,RyPeck/ThreatExchange,theCatWisel/ThreatExchange,wxsBSD/ThreatExchange,mgoffin/ThreatExchange,tiegz/ThreatExchange,tiegz/ThreatExchange,arirubinstein/ThreatExchange,wxsBSD/ThreatExchange,theCatWisel/ThreatExchange,tiegz/ThreatExchange,RyPeck/ThreatExchange,RyPeck/ThreatExchange,mgoffin/ThreatExchange,wxsBSD/ThreatExchange,wxsBSD/ThreatExchange,mgoffin/ThreatExchange,RyPeck/ThreatExchange,wxsBSD/ThreatExchange,theCatWisel/ThreatExchange | ---
+++
@@ -1,5 +1,6 @@
-# import vocabulary
-# from init import init
-# from malware import Malware
-# from threat_exchange_member import ThreatExchangeMember
-# from threat_indicator import ThreatIndicator
+from init import init
+from malware import Malware
+from threat_exchange_member import ThreatExchangeMember
+from threat_indicator import ThreatIndicator
+
+__all__ = ['init', 'Malware', 'ThreatExchangeMember', 'ThreatIndicator'] |
5208abd072d747c0da9dbd599ee50ea63c61842e | migrations/0010_create_alerts.py | migrations/0010_create_alerts.py | from redash.models import db, Alert, AlertSubscription
if __name__ == '__main__':
with db.database.transaction():
Alert.create_table()
AlertSubscription.create_table()
db.close_db(None)
| from redash.models import db, Alert, AlertSubscription
if __name__ == '__main__':
with db.database.transaction():
Alert.create_table()
AlertSubscription.create_table()
db.close_db(None)
| Make lines indented by four spaces instead of three | Make lines indented by four spaces instead of three
| Python | bsd-2-clause | 44px/redash,imsally/redash,chriszs/redash,useabode/redash,vishesh92/redash,M32Media/redash,rockwotj/redash,jmvasquez/redashtest,jmvasquez/redashtest,imsally/redash,EverlyWell/redash,amino-data/redash,denisov-vlad/redash,EverlyWell/redash,getredash/redash,getredash/redash,M32Media/redash,amino-data/redash,M32Media/redash,denisov-vlad/redash,hudl/redash,chriszs/redash,ninneko/redash,hudl/redash,akariv/redash,ninneko/redash,easytaxibr/redash,moritz9/redash,useabode/redash,crowdworks/redash,stefanseifert/redash,rockwotj/redash,akariv/redash,rockwotj/redash,easytaxibr/redash,useabode/redash,alexanderlz/redash,pubnative/redash,pubnative/redash,akariv/redash,stefanseifert/redash,moritz9/redash,easytaxibr/redash,akariv/redash,useabode/redash,easytaxibr/redash,44px/redash,akariv/redash,easytaxibr/redash,ninneko/redash,jmvasquez/redashtest,stefanseifert/redash,EverlyWell/redash,chriszs/redash,pubnative/redash,vishesh92/redash,imsally/redash,getredash/redash,jmvasquez/redashtest,ninneko/redash,denisov-vlad/redash,denisov-vlad/redash,denisov-vlad/redash,vishesh92/redash,getredash/redash,amino-data/redash,hudl/redash,guaguadev/redash,imsally/redash,crowdworks/redash,crowdworks/redash,guaguadev/redash,stefanseifert/redash,alexanderlz/redash,ninneko/redash,getredash/redash,guaguadev/redash,vishesh92/redash,jmvasquez/redashtest,alexanderlz/redash,M32Media/redash,guaguadev/redash,pubnative/redash,EverlyWell/redash,pubnative/redash,moritz9/redash,guaguadev/redash,hudl/redash,moritz9/redash,44px/redash,stefanseifert/redash,alexanderlz/redash,amino-data/redash,rockwotj/redash,chriszs/redash,44px/redash,crowdworks/redash | ---
+++
@@ -2,7 +2,7 @@
if __name__ == '__main__':
with db.database.transaction():
- Alert.create_table()
- AlertSubscription.create_table()
+ Alert.create_table()
+ AlertSubscription.create_table()
db.close_db(None) |
6848b3ad8709a16a520ba1db1aa6eb94c201728f | tests/ExperimentTest.py | tests/ExperimentTest.py | import sys
sys.path.insert(0,".")
import unittest
import neuroml
import neuroml.writers as writers
import PyOpenWorm
from PyOpenWorm import *
import networkx
import rdflib
import rdflib as R
import pint as Q
import os
import subprocess as SP
import subprocess
import tempfile
import doctest
from glob import glob
from GraphDBInit import *
from DataTestTemplate import _DataTest
class ExperimentTest(_DataTest):
def test_DataUser(self):
do = Experiment('', conf=self.config)
self.assertTrue(isinstance(do, DataUser))
| import sys
sys.path.insert(0,".")
import unittest
import neuroml
import neuroml.writers as writers
import PyOpenWorm
from PyOpenWorm import *
import networkx
import rdflib
import rdflib as R
import pint as Q
import os
import subprocess as SP
import subprocess
import tempfile
import doctest
from glob import glob
from GraphDBInit import *
from DataTestTemplate import _DataTest
class ExperimentTest(_DataTest):
def test_DataUser(self):
"""
Test that the Experiment object is a DataUser object as well.
"""
do = Experiment('', conf=self.config)
self.assertTrue(isinstance(do, DataUser))
def test_unimplemented_conditions(self):
"""
Test that an Experiment with no conditions attribute raises an
error when get_conditions() is called.
"""
ex = Experiment()
with self.assertRaises(NotImplementedError):
ex.get_conditions()
| Add test checking that unimplemented attribute raises error | Add test checking that unimplemented attribute raises error
| Python | mit | gsarma/PyOpenWorm,openworm/PyOpenWorm,openworm/PyOpenWorm,gsarma/PyOpenWorm | ---
+++
@@ -22,7 +22,20 @@
from DataTestTemplate import _DataTest
class ExperimentTest(_DataTest):
+
def test_DataUser(self):
+ """
+ Test that the Experiment object is a DataUser object as well.
+ """
do = Experiment('', conf=self.config)
self.assertTrue(isinstance(do, DataUser))
+ def test_unimplemented_conditions(self):
+ """
+ Test that an Experiment with no conditions attribute raises an
+ error when get_conditions() is called.
+ """
+ ex = Experiment()
+ with self.assertRaises(NotImplementedError):
+ ex.get_conditions()
+ |
122f38717170766473df4dffd79632f90b3d41ad | axes/apps.py | axes/apps.py | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not enabled or not set to verbose
if not settings.AXES_ENABLED:
return
if not settings.AXES_VERBOSE:
return
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
| from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not set to verbose
if settings.AXES_VERBOSE:
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
| Adjust init verbose and enabled mode handling | Adjust init verbose and enabled mode handling
Reduce complexity and leave the enabled mode to be used
with the toggleable decorator that disables functionality
when AXES_ENABLED is set to False for testing etc.
This conforms with the previous behaviour and logic flow. | Python | mit | jazzband/django-axes | ---
+++
@@ -27,27 +27,22 @@
from axes.conf import settings
from axes import checks, signals # noqa
- # Skip startup log messages if Axes is not enabled or not set to verbose
- if not settings.AXES_ENABLED:
- return
+ # Skip startup log messages if Axes is not set to verbose
+ if settings.AXES_VERBOSE:
+ log.info("AXES: BEGIN LOG")
+ log.info(
+ "AXES: Using django-axes version %s",
+ get_distribution("django-axes").version,
+ )
- if not settings.AXES_VERBOSE:
- return
-
- log.info("AXES: BEGIN LOG")
- log.info(
- "AXES: Using django-axes version %s",
- get_distribution("django-axes").version,
- )
-
- if settings.AXES_ONLY_USER_FAILURES:
- log.info("AXES: blocking by username only.")
- elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
- log.info("AXES: blocking by combination of username and IP.")
- elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
- log.info("AXES: blocking by username or IP.")
- else:
- log.info("AXES: blocking by IP only.")
+ if settings.AXES_ONLY_USER_FAILURES:
+ log.info("AXES: blocking by username only.")
+ elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
+ log.info("AXES: blocking by combination of username and IP.")
+ elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
+ log.info("AXES: blocking by username or IP.")
+ else:
+ log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize() |
3d281a3524a4cd1bf9e2f60767ec8d89d3b589e2 | tools/wcloud/wcloud/deploymentsettings.py | tools/wcloud/wcloud/deploymentsettings.py | from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 10000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admin
Creation.ADMIN_NAME: 'CHANGE_ME', # --admin-name=(lo que diga)
Creation.ADMIN_PASSWORD: 'CHANGE_ME', # --admin-password=(lo que diga)
Creation.ADMIN_MAIL: 'CHANGE_ME', # --admin-mail=(lo que diga)
Creation.START_PORTS: 'CHANGE_ME', # --start-port=10000
Creation.SYSTEM_IDENTIFIER: 'CHANGE_ME', # -i (nombre de la uni, puede tener espacios)
Creation.SERVER_HOST: 'weblab.deusto.es', # --server-host=(de settings)
Creation.ENTITY_LINK: 'http://www.deusto.es/', # --entity-link= http://www.deusto.es/
Creation.CORES: 3,
}
| from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 10000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admin
Creation.ADMIN_NAME: 'CHANGE_ME', # --admin-name=(lo que diga)
Creation.ADMIN_PASSWORD: 'CHANGE_ME', # --admin-password=(lo que diga)
Creation.ADMIN_MAIL: 'CHANGE_ME', # --admin-mail=(lo que diga)
Creation.START_PORTS: 'CHANGE_ME', # --start-port=10000
Creation.SYSTEM_IDENTIFIER: 'CHANGE_ME', # -i (nombre de la uni, puede tener espacios)
Creation.SERVER_HOST: 'weblab.deusto.es', # --server-host=(de settings)
Creation.ENTITY_LINK: 'http://www.deusto.es/', # --entity-link= http://www.deusto.es/
Creation.CORES: 3,
Creation.ADD_FEDERATED_LOGIC : True,
Creation.ADD_FEDERATED_VISIR : True,
Creation.ADD_FEDERATED_SUBMARINE : True,
}
| Add logic, visir and submarine to wcloud | Add logic, visir and submarine to wcloud
| Python | bsd-2-clause | morelab/weblabdeusto,weblabdeusto/weblabdeusto,zstars/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto,porduna/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/weblabdeusto,porduna/weblabdeusto,weblabdeusto/weblabdeusto,zstars/weblabdeusto,weblabdeusto/weblabdeusto,zstars/weblabdeusto,zstars/weblabdeusto,weblabdeusto/weblabdeusto,zstars/weblabdeusto,morelab/weblabdeusto,porduna/weblabdeusto,weblabdeusto/weblabdeusto,porduna/weblabdeusto,zstars/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,porduna/weblabdeusto,porduna/weblabdeusto,zstars/weblabdeusto,porduna/weblabdeusto,zstars/weblabdeusto,porduna/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/weblabdeusto,zstars/weblabdeusto,zstars/weblabdeusto,porduna/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,porduna/weblabdeusto | ---
+++
@@ -17,5 +17,7 @@
Creation.SERVER_HOST: 'weblab.deusto.es', # --server-host=(de settings)
Creation.ENTITY_LINK: 'http://www.deusto.es/', # --entity-link= http://www.deusto.es/
Creation.CORES: 3,
-
+ Creation.ADD_FEDERATED_LOGIC : True,
+ Creation.ADD_FEDERATED_VISIR : True,
+ Creation.ADD_FEDERATED_SUBMARINE : True,
} |
e02d1ffc989b81cadaf6539685388b421444a4a4 | bioc/__init__.py | bioc/__init__.py | __author__ = 'Yifan Peng'
__version__ = '1.0.0-SNAPSHOT'
from bioc import BioCCollection, BioCDocument, BioCPassage, BioCSentence, BioCAnnotation, \
BioCRelation, BioCLocation, BioCNode, parse, merge, validate
from iterparse import iterparse
__all__ = ['BioCAnnotation', 'BioCCollection', 'BioCDocument', 'BioCLocation', 'BioCNode',
'BioCPassage', 'BioCRelation', 'BioCSentence', 'parse', 'iterparse', 'merge', 'validate']
| __author__ = 'Yifan Peng'
__version__ = '1.0.0-SNAPSHOT'
from .bioc import BioCCollection, BioCDocument, BioCPassage, BioCSentence, BioCAnnotation, \
BioCRelation, BioCLocation, BioCNode, parse, merge, validate
from .iterparse import iterparse
__all__ = ['BioCAnnotation', 'BioCCollection', 'BioCDocument', 'BioCLocation', 'BioCNode',
'BioCPassage', 'BioCRelation', 'BioCSentence', 'parse', 'iterparse', 'merge', 'validate']
| Fix Python 3 packaging issue | Fix Python 3 packaging issue | Python | bsd-3-clause | yfpeng/pengyifan-pybioc,yfpeng/bioc | ---
+++
@@ -2,9 +2,9 @@
__version__ = '1.0.0-SNAPSHOT'
-from bioc import BioCCollection, BioCDocument, BioCPassage, BioCSentence, BioCAnnotation, \
+from .bioc import BioCCollection, BioCDocument, BioCPassage, BioCSentence, BioCAnnotation, \
BioCRelation, BioCLocation, BioCNode, parse, merge, validate
-from iterparse import iterparse
+from .iterparse import iterparse
__all__ = ['BioCAnnotation', 'BioCCollection', 'BioCDocument', 'BioCLocation', 'BioCNode',
'BioCPassage', 'BioCRelation', 'BioCSentence', 'parse', 'iterparse', 'merge', 'validate'] |
6dc73aa3f4acd40ffbf6057c8765e2c693495657 | bookmarkd/cli.py | bookmarkd/cli.py | """
Author: Ryan Brown <sb@ryansb.com>
License: AGPL3
"""
import click
@click.group()
def cli():
pass
@cli.command()
def version():
click.echo("You are using ofcourse version {}".format(__version__))
click.echo("Get more information at "
"https://github.com/ryansb/ofCourse")
@cli.command(short_help="Push this to openshift. Requires "
"http://openshift.com account. Will check for "
"course.openshift.git_url as well as CLI flag --remote")
@click.option("-o", "--output", help="File to send output to")
@click.option("--stdout", help="Sent output to stdout instead", is_flag=True)
def md(output, stdout):
pass
| # -*- coding: utf8 -*-
"""
Copyright 2014 Ryan Brown <sb@ryansb.com>
This file is part of bookmarkd.
bookmarkd is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
bookmarkd is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with bookmarkd. If not, see <http://www.gnu.org/licenses/>.
"""
import click
from bookmarkd.version import __version__
from bookmarkd.to_notebook import to_notebook as md_to_nb
@click.group()
def cli():
pass
@cli.command()
def version():
click.echo("You are using bookmarkd version {}".format(__version__))
click.echo("Get more information at "
"https://github.com/ryansb/bookmarkd")
@cli.command(short_help="Do the conversion")
@click.argument("infile", type=click.File('rb'))
@click.argument("outfile", type=click.File('wb'))
def convert(infile, outfile):
if infile.name.endswith('.md'):
pynb = md_to_nb(infile)
outfile.write(pynb)
else:
click.echo("Only markdown -> notebook conversion is "
"currently supported")
| Make convert command work with files or stdin/out | Make convert command work with files or stdin/out
| Python | agpl-3.0 | ryansb/bookmarkd | ---
+++
@@ -1,26 +1,49 @@
+# -*- coding: utf8 -*-
"""
-Author: Ryan Brown <sb@ryansb.com>
-License: AGPL3
+Copyright 2014 Ryan Brown <sb@ryansb.com>
+
+This file is part of bookmarkd.
+
+bookmarkd is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of
+the License, or (at your option) any later version.
+
+bookmarkd is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with bookmarkd. If not, see <http://www.gnu.org/licenses/>.
"""
import click
+
+from bookmarkd.version import __version__
+from bookmarkd.to_notebook import to_notebook as md_to_nb
@click.group()
def cli():
pass
+
@cli.command()
def version():
- click.echo("You are using ofcourse version {}".format(__version__))
+ click.echo("You are using bookmarkd version {}".format(__version__))
click.echo("Get more information at "
- "https://github.com/ryansb/ofCourse")
+ "https://github.com/ryansb/bookmarkd")
-@cli.command(short_help="Push this to openshift. Requires "
- "http://openshift.com account. Will check for "
- "course.openshift.git_url as well as CLI flag --remote")
-@click.option("-o", "--output", help="File to send output to")
-@click.option("--stdout", help="Sent output to stdout instead", is_flag=True)
-def md(output, stdout):
- pass
+@cli.command(short_help="Do the conversion")
+@click.argument("infile", type=click.File('rb'))
+@click.argument("outfile", type=click.File('wb'))
+def convert(infile, outfile):
+ if infile.name.endswith('.md'):
+ pynb = md_to_nb(infile)
+ outfile.write(pynb)
+
+ else:
+ click.echo("Only markdown -> notebook conversion is "
+ "currently supported") |
f269b7b5c7b0bb0973f504db1c3605c9ff3ac6da | tutorials/2017/thursday/graphColouring.py | tutorials/2017/thursday/graphColouring.py | from boolean import *
def graphColouring2SAT(G, k):
conj = []
for i in range(len(G)):
conj.append(Or(*((i, j) for j in range(k))))
for j in range(k):
for jj in range(j+1, k):
conj.append(Or(Not((i, j)), Not((i, jj))))
for ii in G[i]:
for j in range(k):
conj.append(Or(Not((i, j)), Not((ii, j))))
return And(*conj)
| from boolean import *
def graphColouring2SAT(G, k):
conj = []
for i in range(len(G)):
conj.append(Or(*((i, j) for j in range(k))))
for j in range(k):
for jj in range(j+1, k):
conj.append(Or(Not((i, j)), Not((i, jj))))
for ii in G[i]:
for j in range(k):
conj.append(Or(Not((i, j)), Not((ii, j))))
return And(*conj)
def SAT2graphColouring(sol):
d = {i: j for (i, j), v in sol.items() if v}
out = [None] * len(d)
for i, j in d.items():
out[i] = j
return out
| Add function to extract solution from valuation | Add function to extract solution from valuation
| Python | mit | jaanos/LVR-2016,jaanos/LVR-2016 | ---
+++
@@ -11,3 +11,10 @@
for j in range(k):
conj.append(Or(Not((i, j)), Not((ii, j))))
return And(*conj)
+
+def SAT2graphColouring(sol):
+ d = {i: j for (i, j), v in sol.items() if v}
+ out = [None] * len(d)
+ for i, j in d.items():
+ out[i] = j
+ return out |
b18c0f6b732b5adc42f123d83886d260c8278ad5 | tests/test_slackelot.py | tests/test_slackelot.py | import pytest
import mock
from slackelot.slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
| import pytest
try:
from unittest import mock
except ImportError:
import mock
from slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
| Refactor imports to be less verbose | Refactor imports to be less verbose
| Python | mit | Chris-Graffagnino/slackelot | ---
+++
@@ -1,7 +1,11 @@
import pytest
-import mock
-from slackelot.slackelot import SlackNotificationError, send_message
+try:
+ from unittest import mock
+except ImportError:
+ import mock
+
+from slackelot import SlackNotificationError, send_message
def test_send_message_success(): |
5d1bc24d585c6a51367d322cfaf52a84be05a132 | myuw_mobile/urls.py | myuw_mobile/urls.py | from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'^visual', 'index'),
url(r'^textbooks', 'index'),
url(r'^instructor', 'index'),
url(r'^links', 'index'),
url(r'^$', 'index'),
url(r'^api/v1/schedule/current/$', StudClasScheCurQuar().run),
url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/person/(?P<regid>.*)$', InstructorContact().run),
)
| from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'^visual', 'index'),
url(r'^textbooks', 'index'),
url(r'^instructor', 'index'),
url(r'^links', 'index'),
url(r'^$', 'index'),
)
urlpatterns += patterns('myuw_mobile.views.api',
url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/schedule/current/$', StudClasScheCurQuar().run),
url(r'^api/v1/person/(?P<regid>.*)$', InstructorContact().run),
)
| Use a separate set of urlpatterns for each file in views. | Use a separate set of urlpatterns for each file in views.
| Python | apache-2.0 | fanglinfang/myuw,uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw | ---
+++
@@ -10,8 +10,10 @@
url(r'^instructor', 'index'),
url(r'^links', 'index'),
url(r'^$', 'index'),
+)
+
+urlpatterns += patterns('myuw_mobile.views.api',
+ url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/schedule/current/$', StudClasScheCurQuar().run),
- url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/person/(?P<regid>.*)$', InstructorContact().run),
)
- |
6f540821e891f49e0f2059757b58d2aa0efdf267 | src/panda_test.py | src/panda_test.py | from direct.showbase.ShowBase import ShowBase
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
app = MyApp()
app.run()
| from math import pi, sin, cos
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import Sequence
from panda3d.core import Point3
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.scene = self.loader.loadModel("environment")
self.scene.reparentTo(self.render)
self.scene.setScale(0.25, 0.25, 0.25)
self.scene.setPos(-8, 42, 0)
self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
self.pandaActor = Actor("panda-model",
{"walk": "panda-walk4"})
self.pandaActor.setScale(0.005, 0.005, 0.005)
self.pandaActor.reparentTo(self.render)
self.pandaActor.loop("walk")
pandaPosInterval1 = self.pandaActor.posInterval(13,
Point3(0, -10, 0),
startPos=Point3(0, 10, 0))
pandaPosInterval2 = self.pandaActor.posInterval(13,
Point3(0, 10, 0),
startPos=Point3(0, -10, 0))
pandaHprInterval1 = self.pandaActor.hprInterval(3,
Point3(180, 0, 0),
startHpr=Point3(0, 0, 0))
pandaHprInterval2 = self.pandaActor.hprInterval(3,
Point3(0, 0, 0),
startHpr=Point3(180, 0, 0))
self.pandaPace = Sequence(pandaPosInterval1,
pandaHprInterval1,
pandaPosInterval2,
pandaHprInterval2,
name="pandaPace")
self.pandaPace.loop()
def spinCameraTask(self, task):
angleDegrees = task.time * 6.0
angleRadians = angleDegrees * (pi / 180.0)
self.camera.setPos(20 * sin(angleRadians), -20 * cos(angleRadians), 3)
self.camera.setHpr(angleDegrees, 0, 0)
return Task.cont
app = MyApp()
app.run()
| Add the rest of Panda3D test program. | Add the rest of Panda3D test program.
| Python | mit | CheeseLord/warts,CheeseLord/warts | ---
+++
@@ -1,9 +1,56 @@
+from math import pi, sin, cos
+
from direct.showbase.ShowBase import ShowBase
+from direct.task import Task
+from direct.actor.Actor import Actor
+from direct.interval.IntervalGlobal import Sequence
+from panda3d.core import Point3
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
+
+ self.scene = self.loader.loadModel("environment")
+ self.scene.reparentTo(self.render)
+ self.scene.setScale(0.25, 0.25, 0.25)
+ self.scene.setPos(-8, 42, 0)
+
+ self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
+
+ self.pandaActor = Actor("panda-model",
+ {"walk": "panda-walk4"})
+ self.pandaActor.setScale(0.005, 0.005, 0.005)
+ self.pandaActor.reparentTo(self.render)
+ self.pandaActor.loop("walk")
+
+ pandaPosInterval1 = self.pandaActor.posInterval(13,
+ Point3(0, -10, 0),
+ startPos=Point3(0, 10, 0))
+ pandaPosInterval2 = self.pandaActor.posInterval(13,
+ Point3(0, 10, 0),
+ startPos=Point3(0, -10, 0))
+ pandaHprInterval1 = self.pandaActor.hprInterval(3,
+ Point3(180, 0, 0),
+ startHpr=Point3(0, 0, 0))
+ pandaHprInterval2 = self.pandaActor.hprInterval(3,
+ Point3(0, 0, 0),
+ startHpr=Point3(180, 0, 0))
+
+ self.pandaPace = Sequence(pandaPosInterval1,
+ pandaHprInterval1,
+ pandaPosInterval2,
+ pandaHprInterval2,
+ name="pandaPace")
+ self.pandaPace.loop()
+
+ def spinCameraTask(self, task):
+ angleDegrees = task.time * 6.0
+ angleRadians = angleDegrees * (pi / 180.0)
+ self.camera.setPos(20 * sin(angleRadians), -20 * cos(angleRadians), 3)
+ self.camera.setHpr(angleDegrees, 0, 0)
+ return Task.cont
app = MyApp()
app.run()
+ |
bb27d997c728542dd3ec883ba44a3fefb126c42e | scraperwiki/__init__.py | scraperwiki/__init__.py | #!/usr/bin/env python2
# Thomas Levine, ScraperWiki Limited
'''
Local version of ScraperWiki Utils, documentation here:
https://scraperwiki.com/docs/python/python_help_documentation/
'''
from .utils import scrape, pdftoxml, status
import utils
import sql
# Compatibility
sqlite = sql | #!/usr/bin/env python2
# Thomas Levine, ScraperWiki Limited
'''
Local version of ScraperWiki Utils, documentation here:
https://scraperwiki.com/docs/python/python_help_documentation/
'''
from .utils import scrape, pdftoxml, status
import utils
import sql
# Compatibility
sqlite = sql
class Error(Exception):
"""All ScraperWiki exceptions are instances of this class
(usually via a subclass)."""
pass
class CPUTimeExceededError(Error):
"""CPU time limit exceeded."""
pass
| Add exceptions scraperwiki.CPUTimeExceededError and scraperwiki.Error. This bring the library closer to the classic API, which provided both these exceptions. | Add exceptions scraperwiki.CPUTimeExceededError and scraperwiki.Error.
This bring the library closer to the classic API, which provided
both these exceptions.
| Python | bsd-2-clause | hudsonkeithl/scraperwiki-python,tlevine/scraperwiki-python,scraperwiki/scraperwiki-python,tlevine/scraperwiki-python,scraperwiki/scraperwiki-python,hudsonkeithl/scraperwiki-python | ---
+++
@@ -12,3 +12,12 @@
# Compatibility
sqlite = sql
+
+class Error(Exception):
+ """All ScraperWiki exceptions are instances of this class
+ (usually via a subclass)."""
+ pass
+
+class CPUTimeExceededError(Error):
+ """CPU time limit exceeded."""
+ pass |
2092467a123c380edfadb52aa42ac9f063524f90 | scripts/release_conf.py | scripts/release_conf.py | import os
with open("src/conf.lua.bak") as f:
conf = f.read()
conf = conf.replace("t.release = false",
"t.release = true")
conf = conf.replace("ac1c2db50f1332444fd0cafffd7a5543",
os.environ["MIXPANEL_TOKEN"])
with open("src/conf.lua", "w") as g:
g.write(conf)
| import os
with open("src/conf.lua.bak") as f:
conf = f.read()
conf = conf.replace("t.release = false",
"t.release = true")
if "MIXPANEL_TOKEN" in os.environ:
conf = conf.replace("ac1c2db50f1332444fd0cafffd7a5543",
os.environ["MIXPANEL_TOKEN"])
with open("src/conf.lua", "w") as g:
g.write(conf)
| Build releases even without MIXPANEL_TOKEN | Build releases even without MIXPANEL_TOKEN
| Python | mit | hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua | ---
+++
@@ -5,8 +5,10 @@
conf = conf.replace("t.release = false",
"t.release = true")
- conf = conf.replace("ac1c2db50f1332444fd0cafffd7a5543",
- os.environ["MIXPANEL_TOKEN"])
+
+ if "MIXPANEL_TOKEN" in os.environ:
+ conf = conf.replace("ac1c2db50f1332444fd0cafffd7a5543",
+ os.environ["MIXPANEL_TOKEN"])
with open("src/conf.lua", "w") as g:
g.write(conf) |
1d18cb035e959df3aae2ca867d466fca3c091471 | test/mac/gyptest-rebuild.py | test/mac/gyptest-rebuild.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are rebuilt correctly.
"""
import TestGyp
import os
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir='app-bundle')
test.build('test.gyp', test.ALL, chdir='app-bundle')
# Touch a source file, rebuild, and check that the app target is up-to-date.
os.utime('app-bundle/TestApp/main.m', None)
test.build('test.gyp', test.ALL, chdir='app-bundle')
test.up_to_date('test.gyp', test.ALL, chdir='app-bundle')
test.pass_test()
| #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are rebuilt correctly.
"""
import TestGyp
import os
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir='app-bundle')
test.build('test.gyp', test.ALL, chdir='app-bundle')
# Touch a source file, rebuild, and check that the app target is up-to-date.
test.touch('app-bundle/TestApp/main.m', None)
test.build('test.gyp', test.ALL, chdir='app-bundle')
test.up_to_date('test.gyp', test.ALL, chdir='app-bundle')
test.pass_test()
| Use test.touch() instead of os.utime() in a test. | Use test.touch() instead of os.utime() in a test.
No intended functionality change.
TBR=evan
Review URL: https://chromiumcodereview.appspot.com/9234034 | Python | bsd-3-clause | old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google | ---
+++
@@ -21,7 +21,7 @@
test.build('test.gyp', test.ALL, chdir='app-bundle')
# Touch a source file, rebuild, and check that the app target is up-to-date.
- os.utime('app-bundle/TestApp/main.m', None)
+ test.touch('app-bundle/TestApp/main.m', None)
test.build('test.gyp', test.ALL, chdir='app-bundle')
test.up_to_date('test.gyp', test.ALL, chdir='app-bundle') |
cef38ccaca08b75f271d16a4a007cb5c5f4a93b2 | chunsabot/modules/images.py | chunsabot/modules/images.py | import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
| import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.call(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
| Use subprocess.call rather than run | Use subprocess.call rather than run
| Python | mit | susemeee/Chunsabot-framework | ---
+++
@@ -27,7 +27,7 @@
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
- result = subprocess.run(
+ result = subprocess.call(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
) |
ff6ee622204500101ad5721dccea69a1c62de65f | smbackend/urls.py | smbackend/urls.py | from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all_views as munigeo_views
# from django.contrib import admin
# admin.autodiscover()
router = routers.DefaultRouter()
registered_api_views = set()
for view in services_views + munigeo_views + observations_views:
kwargs = {}
if view['name'] in registered_api_views:
continue
else:
registered_api_views.add(view['name'])
if 'base_name' in view:
kwargs['base_name'] = view['base_name']
router.register(view['name'], view['class'], **kwargs)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'smbackend.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^', include(v1_api.urls)),
# url(r'^admin/', include(admin.site.urls)),
url(r'^open311/', 'services.views.post_service_request', name='services'),
url(r'^v1/', include(router.urls)),
url(r'^v1/api-token-auth/', obtain_auth_token)
)
| from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all_views as munigeo_views
# from django.contrib import admin
# admin.autodiscover()
router = routers.DefaultRouter()
registered_api_views = set()
for view in services_views + munigeo_views + observations_views:
kwargs = {}
if view['name'] in registered_api_views:
continue
else:
registered_api_views.add(view['name'])
if 'base_name' in view:
kwargs['base_name'] = view['base_name']
router.register(view['name'], view['class'], **kwargs)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'smbackend.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^', include(v1_api.urls)),
# url(r'^admin/', include(admin.site.urls)),
url(r'^open311/', 'services.views.post_service_request', name='services'),
url(r'^v1/', include(router.urls)),
url(r'^v1/api-token-auth/', obtain_auth_token, name='api-auth-token')
)
| Add name to api-token-auth url endpoint. | Add name to api-token-auth url endpoint.
| Python | agpl-3.0 | City-of-Helsinki/smbackend,City-of-Helsinki/smbackend | ---
+++
@@ -33,5 +33,5 @@
# url(r'^admin/', include(admin.site.urls)),
url(r'^open311/', 'services.views.post_service_request', name='services'),
url(r'^v1/', include(router.urls)),
- url(r'^v1/api-token-auth/', obtain_auth_token)
+ url(r'^v1/api-token-auth/', obtain_auth_token, name='api-auth-token')
) |
7c6238e51640794b2812eaf6ca22d3c15dfb90fb | troposphere/finspace.py | troposphere/finspace.py | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.1.0
from . import AWSObject, AWSProperty
class FederationParameters(AWSProperty):
props = {
"ApplicationCallBackURL": (str, False),
"AttributeMap": (dict, False),
"FederationProviderName": (str, False),
"FederationURN": (str, False),
"SamlMetadataDocument": (str, False),
"SamlMetadataURL": (str, False),
}
class Environment(AWSObject):
resource_type = "AWS::FinSpace::Environment"
props = {
"Description": (str, False),
"FederationMode": (str, False),
"FederationParameters": (FederationParameters, False),
"KmsKeyId": (str, False),
"Name": (str, True),
}
| # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 49.0.0
from . import AWSObject, AWSProperty
class FederationParameters(AWSProperty):
props = {
"ApplicationCallBackURL": (str, False),
"AttributeMap": (dict, False),
"FederationProviderName": (str, False),
"FederationURN": (str, False),
"SamlMetadataDocument": (str, False),
"SamlMetadataURL": (str, False),
}
class SuperuserParameters(AWSProperty):
props = {
"EmailAddress": (str, False),
"FirstName": (str, False),
"LastName": (str, False),
}
class Environment(AWSObject):
resource_type = "AWS::FinSpace::Environment"
props = {
"DataBundles": ([str], False),
"Description": (str, False),
"FederationMode": (str, False),
"FederationParameters": (FederationParameters, False),
"KmsKeyId": (str, False),
"Name": (str, True),
"SuperuserParameters": (SuperuserParameters, False),
}
| Update FinSpace per 2021-11-18 changes | Update FinSpace per 2021-11-18 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -4,7 +4,7 @@
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
-# Resource specification version: 39.1.0
+# Resource specification version: 49.0.0
from . import AWSObject, AWSProperty
@@ -21,13 +21,23 @@
}
+class SuperuserParameters(AWSProperty):
+ props = {
+ "EmailAddress": (str, False),
+ "FirstName": (str, False),
+ "LastName": (str, False),
+ }
+
+
class Environment(AWSObject):
resource_type = "AWS::FinSpace::Environment"
props = {
+ "DataBundles": ([str], False),
"Description": (str, False),
"FederationMode": (str, False),
"FederationParameters": (FederationParameters, False),
"KmsKeyId": (str, False),
"Name": (str, True),
+ "SuperuserParameters": (SuperuserParameters, False),
} |
17266889388c6ae45ac5235a8e22900bf169eba3 | typhon/__init__.py | typhon/__init__.py | # -*- coding: utf-8 -*-
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spareice
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
| # -*- coding: utf-8 -*-
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
| Revert "Import spareice per default." | Revert "Import spareice per default."
This reverts commit d54042d41b981b3479adb140f2534f76c967fa1c.
| Python | mit | atmtools/typhon,atmtools/typhon | ---
+++
@@ -20,7 +20,6 @@
from . import oem
from . import physics
from . import plots
- from . import spareice
from . import spectroscopy
from . import trees
from . import utils |
1cb052fc829f286ecc6f7ea5b230e2b5f37d2062 | core/apps.py | core/apps.py | from django.apps import AppConfig
from django.db.models.signals import post_delete, post_save
from wagtail.wagtailsearch.backends import get_search_backends
from wagtail.wagtailsearch.index import get_indexed_models
from wagtail.wagtailsearch.signal_handlers import (get_indexed_instance,
post_delete_signal_handler)
def post_save_signal_handler(instance, **kwargs):
update_fields = kwargs.get('update_fields')
if 'cached_last_updated' in update_fields and 'cached_facebook_count' in update_fields:
return # Don't update the search index if we are just updating facebook page counts
indexed_instance = get_indexed_instance(instance)
if indexed_instance:
for backend in get_search_backends(with_auto_update=True):
backend.add(indexed_instance)
def register_signal_handlers():
# Loop through list and register signal handlers for each one
for model in get_indexed_models():
post_save.connect(post_save_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
class CustomWagtailSearchAppConfig(AppConfig):
name = 'wagtail.wagtailsearch'
label = 'wagtailsearch'
verbose_name = "Wagtail search"
def ready(self):
register_signal_handlers()
| from django.apps import AppConfig
from django.db.models.signals import post_delete, post_save
from wagtail.wagtailsearch.backends import get_search_backends
from wagtail.wagtailsearch.index import get_indexed_models
from wagtail.wagtailsearch.signal_handlers import (get_indexed_instance,
post_delete_signal_handler)
def post_save_signal_handler(instance, **kwargs):
update_fields = kwargs.get('update_fields')
social_fields = frozenset(('cached_facebook_count', 'cached_last_updated'))
if update_fields == social_fields:
return # Don't update the search index if we are just updating facebook page counts
indexed_instance = get_indexed_instance(instance)
if indexed_instance:
for backend in get_search_backends(with_auto_update=True):
backend.add(indexed_instance)
def register_signal_handlers():
# Loop through list and register signal handlers for each one
for model in get_indexed_models():
post_save.connect(post_save_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
class CustomWagtailSearchAppConfig(AppConfig):
name = 'wagtail.wagtailsearch'
label = 'wagtailsearch'
verbose_name = "Wagtail search"
def ready(self):
register_signal_handlers()
| Fix the comparison to work more robustly. | Fix the comparison to work more robustly.
| Python | mit | OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website | ---
+++
@@ -9,7 +9,9 @@
def post_save_signal_handler(instance, **kwargs):
update_fields = kwargs.get('update_fields')
- if 'cached_last_updated' in update_fields and 'cached_facebook_count' in update_fields:
+ social_fields = frozenset(('cached_facebook_count', 'cached_last_updated'))
+
+ if update_fields == social_fields:
return # Don't update the search index if we are just updating facebook page counts
indexed_instance = get_indexed_instance(instance) |
b72af894539ca50d08fa1fa78a5c394fa246323d | cfgov/transition_utilities/test_middleware.py | cfgov/transition_utilities/test_middleware.py | from django.test import TestCase
from mock import Mock
from .middleware import RewriteNemoURLsMiddleware
class CartMiddlewareTest(TestCase):
def setUp(self):
self.middleware = RewriteNemoURLsMiddleware()
self.request = Mock()
self.response = Mock()
def test_text_transform(self):
self.response.streaming = False
self.response.content="/wp-content/themes/cfpb_nemo/static.gif"
self.assertIn("/static/nemo/static.gif", self.middleware.process_response(self.request,self.response).content)
| from django.test import TestCase
from mock import Mock
from .middleware import RewriteNemoURLsMiddleware
class RewriteNemoURLSMiddlewareTest(TestCase):
def setUp(self):
self.middleware = RewriteNemoURLsMiddleware()
self.request = Mock()
self.response = Mock()
def test_text_transform(self):
self.response.streaming = False
self.response.content="/wp-content/themes/cfpb_nemo/static.gif"
self.assertIn("/static/nemo/static.gif", self.middleware.process_response(self.request,self.response).content)
| Fix a harmless (but silly) cut-and-paste artifact | Fix a harmless (but silly) cut-and-paste artifact
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | ---
+++
@@ -2,7 +2,7 @@
from mock import Mock
from .middleware import RewriteNemoURLsMiddleware
-class CartMiddlewareTest(TestCase):
+class RewriteNemoURLSMiddlewareTest(TestCase):
def setUp(self):
self.middleware = RewriteNemoURLsMiddleware() |
d4d76ae28ae8aa028c5a06f7499a20644b45b986 | examples/on_startup.py | examples/on_startup.py | """Provides an example of attaching an action on hug server startup"""
import hug
data = []
@hug.startup()
def add_data(api):
"""Adds initial data to the api on startup"""
data.append("It's working")
@hug.startup()
def add_more_data(api):
"""Adds initial data to the api on startup"""
data.append("Even subsequent calls")
@hug.get()
def test():
"""Returns all stored data"""
return data
| """Provides an example of attaching an action on hug server startup"""
import hug
data = []
@hug.startup()
def add_data(api):
"""Adds initial data to the api on startup"""
data.append("It's working")
@hug.startup()
def add_more_data(api):
"""Adds initial data to the api on startup"""
data.append("Even subsequent calls")
@hug.cli()
@hug.get()
def test():
"""Returns all stored data"""
return data
| Update example to demonstrate desired use case | Update example to demonstrate desired use case
| Python | mit | MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,timothycrosley/hug,MuhammadAlkarouri/hug,timothycrosley/hug,timothycrosley/hug | ---
+++
@@ -16,6 +16,7 @@
data.append("Even subsequent calls")
+@hug.cli()
@hug.get()
def test():
"""Returns all stored data""" |
1a96377332df63a0dd6bc62d6856ff8aa0d0a018 | redgreen.py | redgreen.py | #!/usr/bin/env python
import pygame
screen_size = 640, 480
def start():
pygame.init()
screen = pygame.display.set_mode( screen_size )
def black_screen():
pass
def wait():
pass
def shape():
pass
def end():
while True:
evt = pygame.event.wait()
if evt.type == pygame.QUIT:
break
start()
black_screen()
wait()
shape()
end()
| #!/usr/bin/env python
import pygame
screen_size = 640, 480
def start():
pygame.init()
screen = pygame.display.set_mode( screen_size )
def ready_screen():
pass
def wait():
pass
def shape():
pass
def end():
while True:
evt = pygame.event.wait()
if evt.type == pygame.QUIT:
break
start()
ready_screen()
wait()
shape()
end()
| Rename black_screen to ready_screen and make executable | Rename black_screen to ready_screen and make executable
| Python | mit | andybalaam/redgreen | ---
+++
@@ -8,7 +8,7 @@
pygame.init()
screen = pygame.display.set_mode( screen_size )
-def black_screen():
+def ready_screen():
pass
def wait():
@@ -25,7 +25,7 @@
start()
-black_screen()
+ready_screen()
wait()
|
0defb820e6405a792e63347fa2414953b5449bbe | src/bots/inputs/malwaredomains/feed.py | src/bots/inputs/malwaredomains/feed.py | #!/usr/bin/python
import sys
from lib.bot import *
from lib.utils import *
from lib.event import *
from lib.cache import *
import time
class MalwareDomainsBot(Bot):
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 16384)
rep_ascii = report.decode('ascii', 'ignore')
# print report
self.pipeline.send(rep_ascii)
if __name__ == "__main__":
bot = MalwareDomainsBot(sys.argv[1])
bot.start()
| #!/usr/bin/python
import sys
from lib.bot import *
from lib.utils import *
from lib.event import *
from lib.cache import *
import time
class MalwareDomainsBot(Bot):
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 16384)
rep_ascii = report.decode('ascii','ignore')
# [FIXME] crete generic decoder - see above
self.pipeline.send(rep_ascii)
if __name__ == "__main__":
bot = MalwareDomainsBot(sys.argv[1])
bot.start()
| Comment added to create generic decode method | Comment added to create generic decode method
Former-commit-id: 256c0f9cfd1ca0c5982ac9ab001c5ced84a02c32 | Python | agpl-3.0 | robcza/intelmq,robcza/intelmq,robcza/intelmq,aaronkaplan/intelmq,robcza/intelmq,certtools/intelmq,sch3m4/intelmq,sch3m4/intelmq,pkug/intelmq,certtools/intelmq,pkug/intelmq,aaronkaplan/intelmq,certtools/intelmq,pkug/intelmq,aaronkaplan/intelmq,sch3m4/intelmq,pkug/intelmq,sch3m4/intelmq | ---
+++
@@ -12,8 +12,9 @@
def process(self):
url = "http://www.malwaredomainlist.com/updatescsv.php"
report = fetch_url(url, timeout = 60.0, chunk_size = 16384)
- rep_ascii = report.decode('ascii', 'ignore')
-# print report
+
+ rep_ascii = report.decode('ascii','ignore')
+# [FIXME] crete generic decoder - see above
self.pipeline.send(rep_ascii)
|
27f4499dc11628b2520de65c5f8db6b397d19b69 | src/bulksms/settings.py | src/bulksms/settings.py | # BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(BULKSMS_BASE_API_URL), # sends batch SMS's.
'single': '/{}eapi/submission/send_sms/2/2.0'.format(BULKSMS_BASE_API_URL), # sends single SMS.
'credits': '/{}user/get_credits/1/1.1'.format(BULKSMS_BASE_API_URL) # SMS credits balance.
}
# Whether to automatically insert country codes before sending sms.
CLEAN_MSISDN_NUMBER = False
| # BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(BULKSMS_BASE_API_URL), # sends batch SMS's.
'single': '/{}eapi/submission/send_sms/2/2.0'.format(BULKSMS_BASE_API_URL), # sends single SMS.
'credits': '/{}user/get_credits/1/1.1'.format(BULKSMS_BASE_API_URL) # SMS credits balance.
'inbox': '/{}reception/get_inbox/1/1.1'.format(BULKSMS_BASE_API_URL) # get inbox.
}
# Whether to automatically insert country codes before sending sms.
CLEAN_MSISDN_NUMBER = False
| Add url to check for incoming sms's. | Add url to check for incoming sms's.
| Python | mit | tsotetsi/django-bulksms | ---
+++
@@ -12,6 +12,7 @@
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(BULKSMS_BASE_API_URL), # sends batch SMS's.
'single': '/{}eapi/submission/send_sms/2/2.0'.format(BULKSMS_BASE_API_URL), # sends single SMS.
'credits': '/{}user/get_credits/1/1.1'.format(BULKSMS_BASE_API_URL) # SMS credits balance.
+ 'inbox': '/{}reception/get_inbox/1/1.1'.format(BULKSMS_BASE_API_URL) # get inbox.
}
# Whether to automatically insert country codes before sending sms. |
b92e7c281f18dc0a3c9c65a995e132c89d9f82f1 | areaScraper.py | areaScraper.py | # Craigslist City Scraper
# By Marshall Ehlinger
# For sp2015 Systems Analysis and Design
from bs4 import BeautifulSoup
import requests
import re
soup = BeautifulSoup(requests.get("http://www.craigslist.org/about/sites").text, "html.parser")
for columnDiv in soup.h1.next_sibling.next_sibling:
for state in columnDiv.next_sibling.next_sibling:
for city in state:
print(city)
print("\n----Done----\n\n")
| # Craigslist City Scraper
# By Marshall Ehlinger
# For sp2015 Systems Analysis and Design
from bs4 import BeautifulSoup
import requests
import re
soup = BeautifulSoup(requests.get("http://www.craigslist.org/about/sites").text, "html.parser")
for columnDiv in soup.h1.next_sibling.next_sibling:
for state in columnDiv:
for city in state:
print(city)
print("\n----Done----\n\n")
| Fix city scraper, doesn't throw type error | Fix city scraper, doesn't throw type error
City scraper now prints out html for every city and territory in
the us without throwing any error.
| Python | mit | MuSystemsAnalysis/craigslist_area_search,MuSystemsAnalysis/craigslist_area_search | ---
+++
@@ -8,9 +8,8 @@
soup = BeautifulSoup(requests.get("http://www.craigslist.org/about/sites").text, "html.parser")
-
-for columnDiv in soup.h1.next_sibling.next_sibling:
- for state in columnDiv.next_sibling.next_sibling:
+for columnDiv in soup.h1.next_sibling.next_sibling:
+ for state in columnDiv:
for city in state:
print(city)
print("\n----Done----\n\n") |
ac1b0b59482027cf79755519cb39ba2eed01a29e | avatar/urls.py | avatar/urls.py | from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('avatar.views',
url('^add/$', 'add', name='avatar_add'),
url('^change/$', 'change', name='avatar_change'),
url('^delete/$', 'delete', name='avatar_delete'),
url('^render_primary/(?P<user>[\+\w]+)/(?P<size>[\d]+)/$', 'render_primary', name='avatar_render_primary'),
)
| from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('avatar.views',
url('^add/$', 'add', name='avatar_add'),
url('^change/$', 'change', name='avatar_change'),
url('^delete/$', 'delete', name='avatar_delete'),
url('^render_primary/(?P<user>[\w\d\.\-_]{3,30})/(?P<size>[\d]+)/$', 'render_primary', name='avatar_render_primary'),
)
| Support for username with extra chars. | Support for username with extra chars.
| Python | bsd-3-clause | alexlovelltroy/django-avatar | ---
+++
@@ -4,5 +4,5 @@
url('^add/$', 'add', name='avatar_add'),
url('^change/$', 'change', name='avatar_change'),
url('^delete/$', 'delete', name='avatar_delete'),
- url('^render_primary/(?P<user>[\+\w]+)/(?P<size>[\d]+)/$', 'render_primary', name='avatar_render_primary'),
+ url('^render_primary/(?P<user>[\w\d\.\-_]{3,30})/(?P<size>[\d]+)/$', 'render_primary', name='avatar_render_primary'),
) |
97f1d671966917d29d20c0afb554aaed69c4f9af | wysihtml5/tests/__init__.py | wysihtml5/tests/__init__.py | #-*- coding: utf-8 -*-
import os
import sys
import unittest
def setup_django_settings():
os.chdir(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.getcwd())
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"
def run_tests():
if not os.environ.get("DJANGO_SETTINGS_MODULE", False):
setup_django_settings()
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings)
test_suite = TestRunner(verbosity=2, interactive=True, failfast=False)
test_suite.run_tests(["wysihtml5"])
def suite():
if not os.environ.get("DJANGO_SETTINGS_MODULE", False):
setup_django_settings()
else:
from django.db.models.loading import load_app
from django.conf import settings
settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',]
map(load_app, settings.INSTALLED_APPS)
from wysihtml5.tests import fields, widgets
testsuite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromModule(fields),
unittest.TestLoader().loadTestsFromModule(widgets),
])
return testsuite
if __name__ == "__main__":
run_tests()
| #-*- coding: utf-8 -*-
import os
import sys
import unittest
def setup_django_settings():
os.chdir(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.getcwd())
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"
def run_tests():
if not os.environ.get("DJANGO_SETTINGS_MODULE", False):
setup_django_settings()
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings)
test_suite = TestRunner(verbosity=2, interactive=True, failfast=False)
test_suite.run_tests(["wysihtml5"])
def suite():
if not os.environ.get("DJANGO_SETTINGS_MODULE", False):
setup_django_settings()
else:
from django.db.models.loading import load_app
from django.conf import settings
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \
['wysihtml5.tests']
map(load_app, settings.INSTALLED_APPS)
from wysihtml5.tests import fields, widgets
testsuite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromModule(fields),
unittest.TestLoader().loadTestsFromModule(widgets),
])
return testsuite
if __name__ == "__main__":
run_tests()
| Convert INSTALLED_APPS to list before concat | Convert INSTALLED_APPS to list before concat
| Python | bsd-2-clause | danirus/django-wysihtml5,danirus/django-wysihtml5,danirus/django-wysihtml5 | ---
+++
@@ -28,7 +28,8 @@
else:
from django.db.models.loading import load_app
from django.conf import settings
- settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',]
+ settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \
+ ['wysihtml5.tests']
map(load_app, settings.INSTALLED_APPS)
from wysihtml5.tests import fields, widgets |
ab328b71e5ef72211e8ffe8833759854d4342582 | runtests.py | runtests.py | import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="disposable_email_checker.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"disposable_email_checker",
],
SITE_ID=1,
MIDDLEWARE_CLASSES=(),
)
try:
import django
setup = django.setup
except AttributeError:
pass
else:
setup()
except ImportError:
import traceback
traceback.print_exc()
raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests(*sys.argv[1:])
| import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"disposable_email_checker",
],
SITE_ID=1,
MIDDLEWARE_CLASSES=(),
)
try:
import django
setup = django.setup
except AttributeError:
pass
else:
setup()
except ImportError:
import traceback
traceback.print_exc()
raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests(*sys.argv[1:])
| Remove reference to non-existant file. | Remove reference to non-existant file.
| Python | bsd-3-clause | aaronbassett/DisposableEmailChecker | ---
+++
@@ -12,7 +12,6 @@
"ENGINE": "django.db.backends.sqlite3",
}
},
- ROOT_URLCONF="disposable_email_checker.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes", |
91db70d1fc266e3e3925e84fcaf83410e0504e37 | Lib/tkinter/test/test_tkinter/test_font.py | Lib/tkinter/test/test_tkinter/test_font.py | import unittest
import tkinter
from tkinter import font
from test.support import requires, run_unittest
import tkinter.test.support as support
requires('gui')
class FontTest(unittest.TestCase):
def setUp(self):
support.root_deiconify()
def tearDown(self):
support.root_withdraw()
def test_font_eq(self):
font1 = font.nametofont("TkDefaultFont")
font2 = font.nametofont("TkDefaultFont")
self.assertIsNot(font1, font2)
self.assertEqual(font1, font2)
self.assertNotEqual(font1, font1.copy())
self.assertNotEqual(font1, 0)
tests_gui = (FontTest, )
if __name__ == "__main__":
run_unittest(*tests_gui)
| import unittest
import tkinter
from tkinter import font
from test.support import requires, run_unittest
import tkinter.test.support as support
requires('gui')
class FontTest(unittest.TestCase):
def setUp(self):
support.root_deiconify()
def tearDown(self):
support.root_withdraw()
def test_font_eq(self):
fontname = "TkDefaultFont"
try:
f = font.Font(name=fontname, exists=True)
except tkinter._tkinter.TclError:
f = font.Font(name=fontname, exists=False)
font1 = font.nametofont(fontname)
font2 = font.nametofont(fontname)
self.assertIsNot(font1, font2)
self.assertEqual(font1, font2)
self.assertNotEqual(font1, font1.copy())
self.assertNotEqual(font1, 0)
tests_gui = (FontTest, )
if __name__ == "__main__":
run_unittest(*tests_gui)
| Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily. This should fix some buildbot failures. | Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily.
This should fix some buildbot failures.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -15,8 +15,13 @@
support.root_withdraw()
def test_font_eq(self):
- font1 = font.nametofont("TkDefaultFont")
- font2 = font.nametofont("TkDefaultFont")
+ fontname = "TkDefaultFont"
+ try:
+ f = font.Font(name=fontname, exists=True)
+ except tkinter._tkinter.TclError:
+ f = font.Font(name=fontname, exists=False)
+ font1 = font.nametofont(fontname)
+ font2 = font.nametofont(fontname)
self.assertIsNot(font1, font2)
self.assertEqual(font1, font2)
self.assertNotEqual(font1, font1.copy()) |
e01e5cca84c3eeb04d20b3a91bbb44d688418bf3 | pypaas/sshkey.py | pypaas/sshkey.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import sys
from . import util
class SSHKey(object):
@staticmethod
def rebuild_authorized_keys():
lines = []
ssh_dir = os.path.expanduser('~/.ssh')
util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d'))
for name in os.listdir(os.path.join(ssh_dir, 'authorized_keys.d')):
key = open(os.path.join(ssh_dir, 'authorized_keys.d', name)).read()
keyparts = key.split()
assert keyparts[0].startswith('ssh-')
key = ' '.join(keyparts[:2])
name = name.replace('.pub', '')
lines.append(
('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' +
'no-agent-forwarding,no-user-rc,no-X11-forwarding,' +
'no-port-forwarding {key} {name}').format(
pypaas_cmd=os.path.join(
os.path.dirname(sys.executable), 'pypaas'
),
key=key,
name=name
)
)
util.replace_file(os.path.join(ssh_dir, 'authorized_keys'),
'\n'.join(lines)+'\n')
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import sys
from . import util
class SSHKey(object):
@staticmethod
def rebuild_authorized_keys():
lines = []
ssh_dir = os.path.expanduser('~/.ssh')
util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d'))
for name in os.listdir(os.path.join(ssh_dir, 'authorized_keys.d')):
keyfilename = os.path.join(ssh_dir, 'authorized_keys.d', name)
with open(keyfilename) as keyfile:
for key in keyfile:
keyparts = key.split()
assert keyparts[0].startswith('ssh-')
key = ' '.join(keyparts[:2])
name = name.replace('.pub', '')
lines.append(
('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' +
'no-agent-forwarding,no-user-rc,no-X11-forwarding,' +
'no-port-forwarding {key} {name}').format(
pypaas_cmd=os.path.join(
os.path.dirname(sys.executable), 'pypaas'
),
key=key,
name=name
)
)
util.replace_file(os.path.join(ssh_dir, 'authorized_keys'),
'\n'.join(lines)+'\n')
| Allow multiple SSH keys per file | Allow multiple SSH keys per file
| Python | mit | fintura/pyPaaS,fintura/pyPaaS | ---
+++
@@ -15,21 +15,23 @@
util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d'))
for name in os.listdir(os.path.join(ssh_dir, 'authorized_keys.d')):
- key = open(os.path.join(ssh_dir, 'authorized_keys.d', name)).read()
- keyparts = key.split()
- assert keyparts[0].startswith('ssh-')
- key = ' '.join(keyparts[:2])
- name = name.replace('.pub', '')
- lines.append(
- ('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' +
- 'no-agent-forwarding,no-user-rc,no-X11-forwarding,' +
- 'no-port-forwarding {key} {name}').format(
- pypaas_cmd=os.path.join(
- os.path.dirname(sys.executable), 'pypaas'
- ),
- key=key,
- name=name
- )
- )
+ keyfilename = os.path.join(ssh_dir, 'authorized_keys.d', name)
+ with open(keyfilename) as keyfile:
+ for key in keyfile:
+ keyparts = key.split()
+ assert keyparts[0].startswith('ssh-')
+ key = ' '.join(keyparts[:2])
+ name = name.replace('.pub', '')
+ lines.append(
+ ('command="{pypaas_cmd} $SSH_ORIGINAL_COMMAND",' +
+ 'no-agent-forwarding,no-user-rc,no-X11-forwarding,' +
+ 'no-port-forwarding {key} {name}').format(
+ pypaas_cmd=os.path.join(
+ os.path.dirname(sys.executable), 'pypaas'
+ ),
+ key=key,
+ name=name
+ )
+ )
util.replace_file(os.path.join(ssh_dir, 'authorized_keys'),
'\n'.join(lines)+'\n') |
f37d26541d6baf3da47a8f373a8c7a65177067db | push/modules/push_notification.py | push/modules/push_notification.py | # coding=utf-8
import time, os, json
from apns import APNs, Frame, Payload
from push.models import DevelopFileModel, ProductFileModel
from django.conf import settings
PEM_FILE_DIR = settings.BASE_DIR + '/push/files/'
def execute(device_token_lists, notification):
if notification.is_production:
pem_file_name = ProductFileModel.objects.all()[0].production_file_name
apns = APNs(use_sandbox = False, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
else:
pem_file_name = DevelopFileModel.objects.all()[0].development_file_name
apns = APNs(use_sandbox = True, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
token_hex = []
for token in device_token_lists:
token_hex.append(token)
json_data = ''
if notification.json != '':
json_data = json.loads(notification.json)
payload = Payload(alert = notification.message,
sound = notification.sound,
badge = notification.badge,
custom = json_data)
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
for token in token_hex:
frame.add_item(token, payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)
| # coding=utf-8
import time, os, json
from apns import APNs, Frame, Payload
from push.models import DevelopFileModel, ProductFileModel
from django.conf import settings
PEM_FILE_DIR = settings.BASE_DIR + '/push/files/'
def execute(device_token_lists, notification):
if notification.is_production:
pem_file_name = ProductFileModel.objects.all()[0].production_file_name
apns = APNs(use_sandbox = False, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
else:
pem_file_name = DevelopFileModel.objects.all()[0].development_file_name
apns = APNs(use_sandbox = True, cert_file = PEM_FILE_DIR + pem_file_name, enhanced = True)
token_hex = []
for token in device_token_lists:
token_hex.append(token)
json_data = ''
if notification.json != '':
json_data = json.loads(notification.json)
payload = Payload(alert = notification.message,
sound = notification.sound,
badge = notification.badge,
custom = json_data)
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
for token in token_hex:
frame.add_item(token, payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)
notification.is_sent = True
notification.save()
| Send flag when success push notifications | Send flag when success push notifications
| Python | apache-2.0 | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas | ---
+++
@@ -37,3 +37,6 @@
frame.add_item(token, payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)
+
+ notification.is_sent = True
+ notification.save() |
bf2366bf1caae7671fad09199da3c5d6aff1b790 | redash/authentication/org_resolving.py | redash/authentication/org_resolving.py | """
This module implements different strategies to resolve the current Organization we are using.
By default we use the simple single_org strategy, which assumes you have a
single Organization in your installation.
"""
import logging
from flask import request, g
from werkzeug.local import LocalProxy
from redash.models import Organization
def _get_current_org():
slug = request.view_args.get('org_slug', g.get('org_slug', 'default'))
org = Organization.get_by_slug(slug)
logging.debug("Current organization: %s (slug: %s)", org, slug)
return org
# TODO: move to authentication
current_org = LocalProxy(_get_current_org)
| """
This module implements different strategies to resolve the current Organization we are using.
By default we use the simple single_org strategy, which assumes you have a
single Organization in your installation.
"""
import logging
from flask import request, g
from werkzeug.local import LocalProxy
from redash.models import Organization
def _get_current_org():
if 'org' in g:
return g.org
slug = request.view_args.get('org_slug', g.get('org_slug', 'default'))
g.org = Organization.get_by_slug(slug)
logging.debug("Current organization: %s (slug: %s)", g.org, slug)
return g.org
# TODO: move to authentication
current_org = LocalProxy(_get_current_org)
| Make sure organization is fetched only once | Make sure organization is fetched only once
| Python | bsd-2-clause | moritz9/redash,stefanseifert/redash,moritz9/redash,imsally/redash,EverlyWell/redash,crowdworks/redash,crowdworks/redash,hudl/redash,stefanseifert/redash,alexanderlz/redash,rockwotj/redash,chriszs/redash,vishesh92/redash,stefanseifert/redash,imsally/redash,hudl/redash,hudl/redash,vishesh92/redash,getredash/redash,useabode/redash,stefanseifert/redash,useabode/redash,getredash/redash,EverlyWell/redash,denisov-vlad/redash,alexanderlz/redash,hudl/redash,EverlyWell/redash,M32Media/redash,imsally/redash,44px/redash,44px/redash,EverlyWell/redash,amino-data/redash,vishesh92/redash,stefanseifert/redash,44px/redash,rockwotj/redash,getredash/redash,chriszs/redash,alexanderlz/redash,M32Media/redash,chriszs/redash,moritz9/redash,amino-data/redash,amino-data/redash,denisov-vlad/redash,44px/redash,rockwotj/redash,crowdworks/redash,crowdworks/redash,vishesh92/redash,alexanderlz/redash,denisov-vlad/redash,M32Media/redash,moritz9/redash,M32Media/redash,imsally/redash,useabode/redash,getredash/redash,getredash/redash,rockwotj/redash,denisov-vlad/redash,denisov-vlad/redash,useabode/redash,chriszs/redash,amino-data/redash | ---
+++
@@ -14,10 +14,13 @@
def _get_current_org():
+ if 'org' in g:
+ return g.org
+
slug = request.view_args.get('org_slug', g.get('org_slug', 'default'))
- org = Organization.get_by_slug(slug)
- logging.debug("Current organization: %s (slug: %s)", org, slug)
- return org
+ g.org = Organization.get_by_slug(slug)
+ logging.debug("Current organization: %s (slug: %s)", g.org, slug)
+ return g.org
# TODO: move to authentication
current_org = LocalProxy(_get_current_org) |
73660b238067279287f764d001549bf5e940b607 | tests/test_api.py | tests/test_api.py | import os
import sys
import json
import responses
import unittest
CWD = os.path.dirname(os.path.abspath(__file__))
MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Allow import of api.py
if os.path.join(MS_WD, 'utils') not in sys.path:
sys.path.insert(0, os.path.join(MS_WD, 'utils'))
# Use multiscanner in ../
sys.path.insert(0, os.path.dirname(CWD))
import multiscanner
import api
HTTP_OK = 200
HTTP_CREATED = 201
class TestURLCase(unittest.TestCase):
def setUp(self):
self.app = api.app.test_client()
def test_index(self):
expected_response = {'Message': 'True'}
resp = self.app.get('/')
self.assertEqual(resp.status_code, HTTP_OK)
self.assertEqual(json.loads(resp.data), expected_response)
| import os
import sys
import json
import responses
import unittest
CWD = os.path.dirname(os.path.abspath(__file__))
MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Allow import of api.py
if os.path.join(MS_WD, 'utils') not in sys.path:
sys.path.insert(0, os.path.join(MS_WD, 'utils'))
if os.path.join(MS_WD, 'storage') not in sys.path:
sys.path.insert(0, os.path.join(MS_WD, 'storage'))
# Use multiscanner in ../
sys.path.insert(0, os.path.dirname(CWD))
import multiscanner
import api
from sqlite_driver import Database
TEST_DB_PATH = os.path.join(CWD, 'testing.db')
HTTP_OK = 200
HTTP_CREATED = 201
class TestURLCase(unittest.TestCase):
def setUp(self):
self.sql_db = Database(TEST_DB_PATH)
self.sql_db.init_sqlite_db()
self.app = api.app.test_client()
# Replace the real production DB w/ a testing DB
api.db = self.sql_db
def test_index(self):
expected_response = {'Message': 'True'}
resp = self.app.get('/')
self.assertEqual(resp.status_code, HTTP_OK)
self.assertEqual(json.loads(resp.data), expected_response)
def test_empty_db(self):
expected_response = {'Tasks': []}
resp = self.app.get('/api/v1/tasks/list/')
self.assertEqual(resp.status_code, HTTP_OK)
self.assertEqual(json.loads(resp.data), expected_response)
def tearDown(self):
os.remove(TEST_DB_PATH)
| Add unit test for newly initialized db | Add unit test for newly initialized db
| Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,mitre/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner | ---
+++
@@ -10,12 +10,17 @@
# Allow import of api.py
if os.path.join(MS_WD, 'utils') not in sys.path:
sys.path.insert(0, os.path.join(MS_WD, 'utils'))
+if os.path.join(MS_WD, 'storage') not in sys.path:
+ sys.path.insert(0, os.path.join(MS_WD, 'storage'))
# Use multiscanner in ../
sys.path.insert(0, os.path.dirname(CWD))
import multiscanner
import api
+from sqlite_driver import Database
+
+TEST_DB_PATH = os.path.join(CWD, 'testing.db')
HTTP_OK = 200
HTTP_CREATED = 201
@@ -23,10 +28,23 @@
class TestURLCase(unittest.TestCase):
def setUp(self):
+ self.sql_db = Database(TEST_DB_PATH)
+ self.sql_db.init_sqlite_db()
self.app = api.app.test_client()
+ # Replace the real production DB w/ a testing DB
+ api.db = self.sql_db
def test_index(self):
expected_response = {'Message': 'True'}
resp = self.app.get('/')
self.assertEqual(resp.status_code, HTTP_OK)
self.assertEqual(json.loads(resp.data), expected_response)
+
+ def test_empty_db(self):
+ expected_response = {'Tasks': []}
+ resp = self.app.get('/api/v1/tasks/list/')
+ self.assertEqual(resp.status_code, HTTP_OK)
+ self.assertEqual(json.loads(resp.data), expected_response)
+
+ def tearDown(self):
+ os.remove(TEST_DB_PATH) |
bb5c0711880f43dd8c726a9749152246eecccc84 | waterfall_wall/models.py | waterfall_wall/models.py | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]'
# into your database.
from __future__ import unicode_literals
from django.db import models
import django_pgjsonb
class Feed(models.Model):
id = models.AutoField(primary_key=True)
article_id = models.BigIntegerField(unique=True)
article_json = django_pgjsonb.JSONField()
class Meta:
db_table = 'feed'
class Image(models.Model):
id = models.AutoField(primary_key=True)
article = models.ForeignKey(Feed, blank=True, null=True)
url = models.TextField()
nude_percent = models.IntegerField(blank=True, null=True)
path = models.ImageField(null=True)
class Meta:
db_table = 'image'
unique_together = (('url', 'article'),)
| # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]'
# into your database.
from __future__ import unicode_literals
from django.db import models
import django_pgjsonb
class Feed(models.Model):
id = models.AutoField(primary_key=True)
article_id = models.BigIntegerField(unique=True)
article_json = django_pgjsonb.JSONField()
class Meta:
db_table = 'feed'
class Image(models.Model):
id = models.AutoField(primary_key=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
url = models.TextField()
nude_percent = models.IntegerField(blank=True, null=True)
path = models.ImageField(null=True)
class Meta:
db_table = 'image'
unique_together = (('url', 'feed'),)
| Use feed as the foreign key of image | Use feed as the foreign key of image
| Python | mit | carlcarl/rcard,carlcarl/rcard | ---
+++
@@ -24,11 +24,11 @@
class Image(models.Model):
id = models.AutoField(primary_key=True)
- article = models.ForeignKey(Feed, blank=True, null=True)
+ feed = models.ForeignKey(Feed, blank=True, null=True)
url = models.TextField()
nude_percent = models.IntegerField(blank=True, null=True)
path = models.ImageField(null=True)
class Meta:
db_table = 'image'
- unique_together = (('url', 'article'),)
+ unique_together = (('url', 'feed'),) |
3aa327ad470d772c0c487a11e8dce7e256e9f14d | alembic/versions/1c398722878_git_branch.py | alembic/versions/1c398722878_git_branch.py | """git_branch
Revision ID: 1c398722878
Revises: f8d315a31e
Create Date: 2015-10-18 00:38:22.737519
"""
# revision identifiers, used by Alembic.
revision = '1c398722878'
down_revision = 'f8d315a31e'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('job', sa.Column('git_branch', sa.Text(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('job', 'git_branch')
### end Alembic commands ###
| """git_branch
Revision ID: 1c398722878
Revises: 224302e491d
Create Date: 2015-10-18 00:38:22.737519
"""
# revision identifiers, used by Alembic.
revision = '1c398722878'
down_revision = '224302e491d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('job', sa.Column('git_branch', sa.Text(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('job', 'git_branch')
### end Alembic commands ###
| Fix migration for squashed init | Fix migration for squashed init
| Python | isc | RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI,RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI-Agent,RickyCook/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI | ---
+++
@@ -1,14 +1,14 @@
"""git_branch
Revision ID: 1c398722878
-Revises: f8d315a31e
+Revises: 224302e491d
Create Date: 2015-10-18 00:38:22.737519
"""
# revision identifiers, used by Alembic.
revision = '1c398722878'
-down_revision = 'f8d315a31e'
+down_revision = '224302e491d'
branch_labels = None
depends_on = None
|
dd0ceaaadbdb401e2423fbc3b7c395a117a2ef79 | Command_Line_Interface/__init__.py | Command_Line_Interface/__init__.py | __author__ = "Jarrod N. Bakker"
__status__ = "development"
| # Copyright 2015 Jarrod N. Bakker
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################
| Revert "Added to allow local imports." | Revert "Added to allow local imports."
This reverts commit b1f8344f1525b97a73619fbd84ec26c72829eb7d.
| Python | apache-2.0 | bakkerjarr/ACLSwitch,bakkerjarr/ACLSwitch | ---
+++
@@ -1,2 +1,14 @@
-__author__ = "Jarrod N. Bakker"
-__status__ = "development"
+# Copyright 2015 Jarrod N. Bakker
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+########################################################################### |
13b76c32d387e6074719818bc72847afece0080a | prompter.py | prompter.py | def prompt_for_answer(question=""):
""" Prompts the user for an answer
Args:
question (String): The question to be displayed to the user
Returns:
String: The user's answer
"""
# TODO Change to verify answer here
response = ""
while response == "":
response = input(question)
return response
| import science_utils
def prompt_for_answer(question=""):
""" Prompts the user for an answer
Args:
question (String): The question to be displayed to the user
Returns:
String: The user's answer
"""
# TODO Change to verify answer here
is_acceptable = False
while not is_acceptable:
response = input(question)
try:
science_utils.convert_to_scientific_notation(response)
is_acceptable = True
except ValueError as ve:
print("{}. Please try again. \n".format(ve.args[0]))
return response
| Add verfication loop to prompt_for_answer | Add verfication loop to prompt_for_answer
| Python | mit | dpeters19/webassign2 | ---
+++
@@ -1,3 +1,6 @@
+import science_utils
+
+
def prompt_for_answer(question=""):
""" Prompts the user for an answer
Args:
@@ -8,7 +11,13 @@
"""
# TODO Change to verify answer here
- response = ""
- while response == "":
+ is_acceptable = False
+ while not is_acceptable:
response = input(question)
+ try:
+ science_utils.convert_to_scientific_notation(response)
+ is_acceptable = True
+ except ValueError as ve:
+ print("{}. Please try again. \n".format(ve.args[0]))
+
return response |
9b968e8cf4c5fd8e4bd120255b8eb3c7bc4e6943 | mygpoauth/authorization/admin.py | mygpoauth/authorization/admin.py | from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
pass
| from django.contrib import admin
from .models import Authorization
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
def scope_list(self, app):
return ', '.join(app.scopes)
list_display = ['user', 'application', 'scope_list']
list_select_related = ['user', 'application']
readonly_fields = ['user']
fields = ['user', 'application', 'scopes', 'code']
| Improve Admin for Authorization objects | Improve Admin for Authorization objects
| Python | agpl-3.0 | gpodder/mygpo-auth,gpodder/mygpo-auth | ---
+++
@@ -4,4 +4,14 @@
@admin.register(Authorization)
class ApplicationAdmin(admin.ModelAdmin):
- pass
+
+ def scope_list(self, app):
+ return ', '.join(app.scopes)
+
+ list_display = ['user', 'application', 'scope_list']
+
+ list_select_related = ['user', 'application']
+
+ readonly_fields = ['user']
+
+ fields = ['user', 'application', 'scopes', 'code'] |
b178b2622aff7da7e7d4b6730f5d1c98680b1266 | txircd/modbase.py | txircd/modbase.py | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
def hook(self, base):
self.ircd = base
return self
class Mode(object):
def hook(self, base):
self.ircd = base
return self
def checkSet(self, user, target, param):
return [True, param]
def checkUnset(self, user, target, param):
return [True, param]
def showParam(self, user, target, param):
return param
def onJoin(self, channel, user, params):
return "pass"
def checkPermission(self, user, cmd, data):
return data
def onMessage(self, sender, target, message):
return ["pass"]
def onPart(self, channel, user, reason):
pass
def onTopicChange(self, channel, user, topic):
pass
def namesListEntry(self, recipient, channel, user, representation):
return representation
def commandData(self, command, *args):
pass
class Command(object):
def hook(self, base):
self.ircd = base
return self
def onUse(self, user, data):
pass
def processParams(self, user, params):
return {
"user": user,
"params": params
}
def updateActivity(self, user):
user.lastactivity = now() | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
def hook(self, base):
self.ircd = base
return self
class Mode(object):
def hook(self, base):
self.ircd = base
return self
def checkSet(self, user, target, param):
return [True, param]
def checkUnset(self, user, target, param):
return [True, param]
def showParam(self, user, target, param):
return param
def checkPermission(self, user, cmd, data):
return data
def namesListEntry(self, recipient, channel, user, representation):
return representation
class Command(object):
def hook(self, base):
self.ircd = base
return self
def onUse(self, user, data):
pass
def processParams(self, user, params):
return {
"user": user,
"params": params
}
def updateActivity(self, user):
user.lastactivity = now() | Remove unused functions from the Mode base object | Remove unused functions from the Mode base object
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd | ---
+++
@@ -20,20 +20,10 @@
return [True, param]
def showParam(self, user, target, param):
return param
- def onJoin(self, channel, user, params):
- return "pass"
def checkPermission(self, user, cmd, data):
return data
- def onMessage(self, sender, target, message):
- return ["pass"]
- def onPart(self, channel, user, reason):
- pass
- def onTopicChange(self, channel, user, topic):
- pass
def namesListEntry(self, recipient, channel, user, representation):
return representation
- def commandData(self, command, *args):
- pass
class Command(object):
def hook(self, base): |
f6b76e77d4b3a3dae3420296811891585700f220 | nodewatcher/web/sanitize-dump.py | nodewatcher/web/sanitize-dump.py | #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.argv[0]
exit(1)
if sys.argv[1] not in ('json', 'xml'):
print "Invalid format '%s'! Valid formats are: json xml" % sys.argv[1]
exit(1)
def object_transformator():
# Read all objects one by one
for holder in serializers.deserialize(sys.argv[1], open(sys.argv[2], 'r')):
name = holder.object.__class__.__name__
object = holder.object
# Some objects need to be sanitized
if name == 'Node':
object.notes = ''
elif name == 'UserAccount':
object.vpn_password = 'XXX'
object.phone = '5551234'
elif name == 'User':
object.password = 'XXX'
elif name == 'Profile':
object.root_pass = 'XXX'
elif name == 'StatsSolar':
continue
yield holder.object
# Write transformed objects out
out = open(sys.argv[3], 'w')
serializers.serialize(sys.argv[1], object_transformator(), stream = out)
out.close()
| #!/usr/bin/python
# Setup import paths, since we are using Django models
import sys, os
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wlanlj.settings_production'
# Imports
from django.core import serializers
if len(sys.argv) != 4:
print "Usage: %s format input-file output-file" % sys.argv[0]
exit(1)
if sys.argv[1] not in ('json', 'xml'):
print "Invalid format '%s'! Valid formats are: json xml" % sys.argv[1]
exit(1)
def object_transformator():
# Read all objects one by one
for holder in serializers.deserialize(sys.argv[1], open(sys.argv[2], 'r')):
name = holder.object.__class__.__name__
object = holder.object
# Some objects need to be sanitized
if name == 'Node':
object.notes = ''
elif name == 'UserAccount':
object.vpn_password = 'XXX'
object.phone = '5551234'
elif name == 'User':
object.password = '$1$1qL5F...$ZPQdHpHMsvNQGI4rIbAG70'
elif name == 'Profile':
object.root_pass = 'XXX'
elif name == 'StatsSolar':
continue
yield holder.object
# Write transformed objects out
out = open(sys.argv[3], 'w')
serializers.serialize(sys.argv[1], object_transformator(), stream = out)
out.close()
| Set user password for all sanitized users to '123'. | Set user password for all sanitized users to '123'.
| Python | agpl-3.0 | galaxor/Nodewatcher,galaxor/Nodewatcher,galaxor/Nodewatcher,galaxor/Nodewatcher | ---
+++
@@ -29,7 +29,7 @@
object.vpn_password = 'XXX'
object.phone = '5551234'
elif name == 'User':
- object.password = 'XXX'
+ object.password = '$1$1qL5F...$ZPQdHpHMsvNQGI4rIbAG70'
elif name == 'Profile':
object.root_pass = 'XXX'
elif name == 'StatsSolar': |
7b413a262a4400aa8dee45596a19930329490e6d | alembic/versions/2c48009040da_bug_958558_migration_for_update_product_.py | alembic/versions/2c48009040da_bug_958558_migration_for_update_product_.py | """bug 958558 migration for update_product_version() and friends
Revision ID: 2c48009040da
Revises: 48e9a4366530
Create Date: 2014-01-13 12:54:13.988864
"""
# revision identifiers, used by Alembic.
revision = '2c48009040da'
down_revision = '4cacd567770f'
from alembic import op
from socorro.lib import citexttype, jsontype, buildtype
from socorro.lib.migrations import fix_permissions, load_stored_proc
import sqlalchemy as sa
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql import table, column
def upgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
'sunset_date.sql'])
def downgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
'sunset_date.sql'])
| """bug 958558 migration for update_product_version() and friends
Revision ID: 2c48009040da
Revises: 48e9a4366530
Create Date: 2014-01-13 12:54:13.988864
"""
# revision identifiers, used by Alembic.
revision = '2c48009040da'
down_revision = '4cacd567770f'
from alembic import op
from socorro.lib import citexttype, jsontype, buildtype
from socorro.lib.migrations import fix_permissions, load_stored_proc
import sqlalchemy as sa
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql import table, column
def upgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
'sunset_date.sql',
'update_tcbs.sql'
])
def downgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
'sunset_date.sql',
'update_tcbs.sql'
])
| Add update_tcbs.sql to the mix | Add update_tcbs.sql to the mix
| Python | mpl-2.0 | yglazko/socorro,Tayamarn/socorro,mozilla/socorro,KaiRo-at/socorro,bsmedberg/socorro,twobraids/socorro,mozilla/socorro,mozilla/socorro,rhelmer/socorro,rhelmer/socorro,cliqz/socorro,lonnen/socorro,cliqz/socorro,m8ttyB/socorro,cliqz/socorro,yglazko/socorro,bsmedberg/socorro,spthaolt/socorro,Tchanders/socorro,AdrianGaudebert/socorro,adngdb/socorro,linearregression/socorro,adngdb/socorro,bsmedberg/socorro,bsmedberg/socorro,rhelmer/socorro,luser/socorro,luser/socorro,Tchanders/socorro,Tayamarn/socorro,luser/socorro,lonnen/socorro,mozilla/socorro,m8ttyB/socorro,KaiRo-at/socorro,Tayamarn/socorro,yglazko/socorro,yglazko/socorro,AdrianGaudebert/socorro,Tayamarn/socorro,luser/socorro,spthaolt/socorro,adngdb/socorro,KaiRo-at/socorro,Serg09/socorro,Serg09/socorro,Tchanders/socorro,twobraids/socorro,rhelmer/socorro,bsmedberg/socorro,yglazko/socorro,rhelmer/socorro,pcabido/socorro,cliqz/socorro,pcabido/socorro,Serg09/socorro,m8ttyB/socorro,twobraids/socorro,linearregression/socorro,Tchanders/socorro,linearregression/socorro,KaiRo-at/socorro,cliqz/socorro,lonnen/socorro,cliqz/socorro,lonnen/socorro,adngdb/socorro,KaiRo-at/socorro,AdrianGaudebert/socorro,spthaolt/socorro,twobraids/socorro,AdrianGaudebert/socorro,luser/socorro,m8ttyB/socorro,Tayamarn/socorro,Serg09/socorro,twobraids/socorro,m8ttyB/socorro,spthaolt/socorro,Serg09/socorro,linearregression/socorro,AdrianGaudebert/socorro,linearregression/socorro,luser/socorro,mozilla/socorro,Tayamarn/socorro,spthaolt/socorro,m8ttyB/socorro,linearregression/socorro,adngdb/socorro,pcabido/socorro,rhelmer/socorro,yglazko/socorro,twobraids/socorro,KaiRo-at/socorro,pcabido/socorro,pcabido/socorro,AdrianGaudebert/socorro,mozilla/socorro,pcabido/socorro,spthaolt/socorro,Tchanders/socorro,Tchanders/socorro,Serg09/socorro,adngdb/socorro | ---
+++
@@ -23,10 +23,14 @@
def upgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
- 'sunset_date.sql'])
+ 'sunset_date.sql',
+ 'update_tcbs.sql'
+ ])
def downgrade():
load_stored_proc(op, ['update_product_versions.sql',
'is_rapid_beta.sql',
- 'sunset_date.sql'])
+ 'sunset_date.sql',
+ 'update_tcbs.sql'
+ ]) |
2a3dece4337f8c8fb1531769413bb514252a0f56 | benchbuild/environments/adapters/podman.py | benchbuild/environments/adapters/podman.py | import logging
import os
from plumbum.commands.base import BaseCommand
from benchbuild.settings import CFG
from benchbuild.utils.cmd import podman
LOG = logging.getLogger(__name__)
PODMAN_DEFAULT_OPTS = [
'--root',
os.path.abspath(str(CFG['container']['root'])), '--runroot',
os.path.abspath(str(CFG['container']['runroot']))
]
def bb_podman() -> BaseCommand:
return podman[PODMAN_DEFAULT_OPTS]
BB_PODMAN_CONTAINER_START: BaseCommand = bb_podman()['container', 'start']
BB_PODMAN_CREATE: BaseCommand = bb_podman()['create']
BB_PODMAN_RM: BaseCommand = bb_podman()['rm']
def create_container(image_id: str, container_name: str) -> str:
container_id = str(
BB_PODMAN_CREATE(
'--replace', '--name', container_name.lower(), image_id
)
).strip()
LOG.debug('created container: %s', container_id)
return container_id
def run_container(name: str) -> None:
LOG.debug('running container: %s', name)
BB_PODMAN_CONTAINER_START['-ai', name].run_tee()
def remove_container(container_id: str) -> None:
BB_PODMAN_RM(container_id)
| import logging
import os
from plumbum.commands.base import BaseCommand
from benchbuild.settings import CFG
from benchbuild.utils.cmd import podman
LOG = logging.getLogger(__name__)
PODMAN_DEFAULT_OPTS = [
'--root',
os.path.abspath(str(CFG['container']['root'])), '--runroot',
os.path.abspath(str(CFG['container']['runroot']))
]
def bb_podman() -> BaseCommand:
return podman[PODMAN_DEFAULT_OPTS]
BB_PODMAN_CONTAINER_START: BaseCommand = bb_podman()['container', 'start']
BB_PODMAN_CREATE: BaseCommand = bb_podman()['create']
BB_PODMAN_RM: BaseCommand = bb_podman()['rm']
def create_container(image_id: str, container_name: str) -> str:
container_id = str(
BB_PODMAN_CREATE(
'--replace', '--name', container_name.lower(), image_id.lower()
)
).strip()
LOG.debug('created container: %s', container_id)
return container_id
def run_container(name: str) -> None:
LOG.debug('running container: %s', name)
BB_PODMAN_CONTAINER_START['-ai', name].run_tee()
def remove_container(container_id: str) -> None:
BB_PODMAN_RM(container_id)
| Add missing lower() in create_container() | Add missing lower() in create_container()
| Python | mit | PolyJIT/benchbuild,PolyJIT/benchbuild,PolyJIT/benchbuild,PolyJIT/benchbuild | ---
+++
@@ -26,7 +26,7 @@
def create_container(image_id: str, container_name: str) -> str:
container_id = str(
BB_PODMAN_CREATE(
- '--replace', '--name', container_name.lower(), image_id
+ '--replace', '--name', container_name.lower(), image_id.lower()
)
).strip()
|
8a83c67c76d2a96fc9a70f2057787efcd9250e0e | versebot/regex.py | versebot/regex.py | """
VerseBot for reddit
By Matthieu Grieger
regex.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*(?P<translation>[\w\-\d]+)?(?=\])")
return re.findall(regex, message_body)
| """
VerseBot for reddit
By Matthieu Grieger
regex.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
import re
def find_verses(message_body):
""" Uses regex to search comment body for verse quotations. Returns
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
+ r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
return re.findall(regex, message_body)
| Add optional parentheses for translation | Add optional parentheses for translation
| Python | mit | Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot | ---
+++
@@ -12,6 +12,6 @@
a list of matches if found, None otherwise. """
regex = (r"(?<=\[)(?P<book>[\d\w\s]+)(?P<chapter>\d+)\:?(?P<verse>\d+"
- + r"\-?\d*)?\s*(?P<translation>[\w\-\d]+)?(?=\])")
+ + r"\-?\d*)?\s*\(?(?P<translation>[\w\-\d]+)?\)?(?=\])")
return re.findall(regex, message_body) |
211665a4163801b68d90cbefd5d896f28f374f6f | settings.py | settings.py | # Put your device token here. To get a device token, register at http://stage.cloud4rpi.io
DeviceToken = ""
| # Put your device token here. To get a device token, register at http://stage.cloud4rpi.io
DeviceToken = "YOUR_DEVICE_TOKEN"
| Add a placeholder to device token | Add a placeholder to device token
| Python | mit | cloud4rpi/cloud4rpi | ---
+++
@@ -1,2 +1,2 @@
# Put your device token here. To get a device token, register at http://stage.cloud4rpi.io
-DeviceToken = ""
+DeviceToken = "YOUR_DEVICE_TOKEN" |
7440f8d3b6b4f2b1022d445fda943e981e6ab890 | flask_resty/spec/plugin.py | flask_resty/spec/plugin.py | from collections import defaultdict
from flask import current_app
from .operation import Operation
from .utils import flask_path_to_swagger, get_state
rules = {}
def schema_path_helper(spec, path, view, **kwargs):
"""Path helper that uses resty views
:param view: an `ApiView` object
"""
resource = get_state(current_app).views[view]
rule = rules[resource.rule]
operations = defaultdict(Operation)
view_instance = view()
view_instance.spec_declaration(view, operations, spec)
# add path arguments
parameters = []
for arg in rule.arguments:
parameters.append({
'name': arg,
'in': 'path',
'required': True,
'type': 'string',
})
if parameters:
path['parameters'] = parameters
path.path = flask_path_to_swagger(resource.rule)
path.operations = dict(**operations)
def setup(spec):
"""Setup for the marshmallow plugin."""
spec.register_path_helper(schema_path_helper)
global rules
rules = {
rule.rule: rule for rule in current_app.url_map.iter_rules()
}
| from collections import defaultdict
from flask import current_app
from .operation import Operation
from .utils import flask_path_to_swagger, get_state
rules = {}
def schema_path_helper(spec, path, view, **kwargs):
"""Path helper that uses resty views
:param view: an `ApiView` object
"""
resource = get_state(current_app).views[view]
rule = rules[resource.rule]
operations = defaultdict(Operation)
view_instance = view()
view_instance.spec_declaration(view, operations, spec)
# add path arguments
parameters = []
for arg in rule.arguments:
parameters.append({
'name': arg,
'in': 'path',
'required': True,
'type': 'string',
})
if parameters:
operations['parameters'] = parameters
path.path = flask_path_to_swagger(resource.rule)
path.operations = dict(**operations)
def setup(spec):
"""Setup for the marshmallow plugin."""
spec.register_path_helper(schema_path_helper)
global rules
rules = {
rule.rule: rule for rule in current_app.url_map.iter_rules()
}
| Fix compatibility with newer apispec | Fix compatibility with newer apispec
| Python | mit | taion/flask-jsonapiview,4Catalyzer/flask-jsonapiview,4Catalyzer/flask-resty | ---
+++
@@ -30,7 +30,7 @@
'type': 'string',
})
if parameters:
- path['parameters'] = parameters
+ operations['parameters'] = parameters
path.path = flask_path_to_swagger(resource.rule)
path.operations = dict(**operations) |
9787fb3a78d681aff25c6cbaac2c1ba842c4c7db | manila_ui/api/network.py | manila_ui/api/network.py | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.api import base
from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
from openstack_dashboard.api import nova
def _nova_network_list(request):
nets = nova.novaclient(request).networks.list()
for net in nets:
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return nets
def _nova_network_get(request, nova_net_id):
net = nova.novaclient(request).networks.get(nova_net_id)
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return net
class NetworkClient(network.NetworkClient):
def __init__(self, request):
super(NetworkClient, self).__init__(request)
if base.is_service_enabled(request, 'network'):
self.network_list = neutron.network_list
self.network_get = neutron.network_get
else:
self.network_list = _nova_network_list
self.network_get = _nova_network_get
def network_list(request):
return NetworkClient(request).network_list(request)
def network_get(request, net_id):
return NetworkClient(request).network_get(request, net_id)
| # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.api import neutron
def network_list(request):
return neutron.network_list(request)
def network_get(request, net_id):
return neutron.network_get(request, net_id)
| Fix compatibility with latest horizon | Fix compatibility with latest horizon
Class "NetworkClient" from "openstack_dashboards.api.network" module
was removed from horizon repo. So, remove its usage and use neutron
directly.
Change-Id: Idcf51553f64fae2254c224d4c6ef4fbb94e6f279
Closes-Bug: #1691466
| Python | apache-2.0 | openstack/manila-ui,openstack/manila-ui,openstack/manila-ui | ---
+++
@@ -13,39 +13,12 @@
# License for the specific language governing permissions and limitations
# under the License.
-from openstack_dashboard.api import base
-from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
-from openstack_dashboard.api import nova
-
-
-def _nova_network_list(request):
- nets = nova.novaclient(request).networks.list()
- for net in nets:
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return nets
-
-
-def _nova_network_get(request, nova_net_id):
- net = nova.novaclient(request).networks.get(nova_net_id)
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return net
-
-
-class NetworkClient(network.NetworkClient):
- def __init__(self, request):
- super(NetworkClient, self).__init__(request)
- if base.is_service_enabled(request, 'network'):
- self.network_list = neutron.network_list
- self.network_get = neutron.network_get
- else:
- self.network_list = _nova_network_list
- self.network_get = _nova_network_get
def network_list(request):
- return NetworkClient(request).network_list(request)
+ return neutron.network_list(request)
def network_get(request, net_id):
- return NetworkClient(request).network_get(request, net_id)
+ return neutron.network_get(request, net_id) |
8a6725554451e8df61c60184d41f618a8cd5c7aa | tests/appservice_integrations_tests.py | tests/appservice_integrations_tests.py | import os
from arteria.web.app import AppService
from unittest import TestCase
class AppServiceTest(TestCase):
this_file_path = os.path.dirname(os.path.realpath(__file__))
def test_can_load_configuration(self):
app_svc = AppService.create(
product_name="arteria-test",
config_root="{}/../templates/".format(self.this_file_path))
self.assertIsNotNone(app_svc.config_svc)
app_config = app_svc.config_svc.get_app_config()
logger_config = app_svc.config_svc.get_logger_config()
self.assertEquals(app_config["port"], 10000)
self.assertEquals(logger_config["version"], 1)
| import os
from arteria.web.app import AppService
from unittest import TestCase
class AppServiceTest(TestCase):
this_file_path = os.path.dirname(os.path.realpath(__file__))
def test_can_load_configuration(self):
app_svc = AppService.create(
product_name="arteria-test",
config_root="{}/../templates/".format(self.this_file_path))
self.assertIsNotNone(app_svc.config_svc)
app_config = app_svc.config_svc.get_app_config()
logger_config = app_svc.config_svc.get_logger_config()
self.assertEquals(app_config["port"], 10000)
self.assertEquals(logger_config["version"], 1)
def test_can_use_args(self):
app_svc = AppService.create(
product_name="arteria-test",
config_root="{}/../templates/".format(self.this_file_path),
args=['--port', '1234'])
self.assertEquals(app_svc._port, 1234)
| Test extra args are used | Test extra args are used
| Python | mit | arteria-project/arteria-core | ---
+++
@@ -18,3 +18,11 @@
self.assertEquals(app_config["port"], 10000)
self.assertEquals(logger_config["version"], 1)
+
+ def test_can_use_args(self):
+ app_svc = AppService.create(
+ product_name="arteria-test",
+ config_root="{}/../templates/".format(self.this_file_path),
+ args=['--port', '1234'])
+
+ self.assertEquals(app_svc._port, 1234) |
a9307e1ac7778f6073d275a4822bc5f1df9c45fb | termedit.py | termedit.py | #!/usr/bin/env python3
import os
import sys
import neovim
files = {os.path.abspath(arg) for arg in sys.argv[1:]}
if not files:
sys.exit(1)
addr = os.environ.get('NVIM_LISTEN_ADDRESS', None)
if not addr:
os.execvp('nvim', files)
nvim = neovim.attach('socket', path=addr)
tbuf = nvim.current.buffer
for fname in files:
nvim.command('drop {}'.format(fname))
nvim.command('autocmd BufUnload <buffer> silent! call rpcnotify({}, "m")'
.format(nvim.channel_id))
while files:
try:
nvim.session.next_message()
except:
pass
files.pop()
nvim.current.buffer = tbuf
nvim.input('i')
| #!/usr/bin/env python3
import os
import sys
import neovim
files = [os.path.abspath(arg) for arg in sys.argv[1:]]
if not files:
sys.exit(1)
addr = os.environ.get('NVIM_LISTEN_ADDRESS', None)
if not addr:
os.execvp('nvim', files)
nvim = neovim.attach('socket', path=addr)
tbuf = nvim.current.buffer
for fname in files:
fname = nvim.eval('fnameescape("{}")'.format(fname)).decode('utf-8')
nvim.command('drop {}'.format(fname))
nvim.command('autocmd BufUnload <buffer> silent! call rpcnotify({}, "m")'
.format(nvim.channel_id))
while files:
try:
nvim.session.next_message()
except:
pass
files.pop()
nvim.current.buffer = tbuf
nvim.input('i')
| Fix not opening paths with spaces. | Fix not opening paths with spaces.
| Python | apache-2.0 | rliang/termedit.nvim | ---
+++
@@ -4,7 +4,7 @@
import sys
import neovim
-files = {os.path.abspath(arg) for arg in sys.argv[1:]}
+files = [os.path.abspath(arg) for arg in sys.argv[1:]]
if not files:
sys.exit(1)
@@ -16,6 +16,7 @@
tbuf = nvim.current.buffer
for fname in files:
+ fname = nvim.eval('fnameescape("{}")'.format(fname)).decode('utf-8')
nvim.command('drop {}'.format(fname))
nvim.command('autocmd BufUnload <buffer> silent! call rpcnotify({}, "m")'
.format(nvim.channel_id)) |
c7b7e62cb2585f6109d70b27564617b0be4c8c33 | tests/test_daterange.py | tests/test_daterange.py | import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
| import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(
os.path.dirname(__file__),
'../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (
time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
| Update code for PEP8 compliance | Update code for PEP8 compliance
| Python | mit | sendgrid/python-http-client,sendgrid/python-http-client | ---
+++
@@ -6,10 +6,14 @@
except ImportError:
import unittest
+
class DateRangeTest(unittest.TestCase):
def setUp(self):
- self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt')
- self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y"))
+ self.openlicensefile = os.path.join(
+ os.path.dirname(__file__),
+ '../LICENSE.txt')
+ self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (
+ time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self): |
029e31b9f28e2d9882f7453b538eb2c9299ca185 | programs/buck_logging.py | programs/buck_logging.py | #!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
logger = logging.getLogger()
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}
level = level_name_to_level.get(level_name.upper(), logging.INFO)
logger.setLevel(level)
# Set formatter for log messages.
console_handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
| #!/usr/bin/env python
from __future__ import print_function
import logging
import os
def setup_logging():
# Set log level of the messages to show.
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}
level = level_name_to_level.get(level_name.upper(), logging.INFO)
logging.basicConfig(
level=level,
format=(
'%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s'
))
| Make buck wrapper logs human-readable. | Make buck wrapper logs human-readable.
Summary: Simplify logging setup and make its format human-readable
Test Plan:
$ BUCK_WRAPPER_LOG_LEVEL=DEBUG buck run buck -- --version
buck version 64999e5d3b446c062da5c3cc282a2e78ce133c92
2017-12-05 14:08:08,073 [DEBUG][buck.py:80] [Errno 2] No such file or directory
perviously it would produce:
buck version 64999e5d3b446c062da5c3cc282a2e78ce133c92
[Errno 2] No such file or directory
which does not leave much to investigate
Reviewed By: sbalabanov
fbshipit-source-id: 2d0b977
| Python | apache-2.0 | kageiit/buck,facebook/buck,rmaz/buck,clonetwin26/buck,JoelMarcey/buck,clonetwin26/buck,shs96c/buck,clonetwin26/buck,Addepar/buck,romanoid/buck,SeleniumHQ/buck,clonetwin26/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,romanoid/buck,Addepar/buck,JoelMarcey/buck,zpao/buck,shs96c/buck,JoelMarcey/buck,rmaz/buck,SeleniumHQ/buck,Addepar/buck,clonetwin26/buck,rmaz/buck,romanoid/buck,clonetwin26/buck,brettwooldridge/buck,facebook/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,SeleniumHQ/buck,nguyentruongtho/buck,romanoid/buck,rmaz/buck,shs96c/buck,LegNeato/buck,clonetwin26/buck,shs96c/buck,kageiit/buck,shs96c/buck,zpao/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,JoelMarcey/buck,rmaz/buck,facebook/buck,zpao/buck,Addepar/buck,brettwooldridge/buck,romanoid/buck,JoelMarcey/buck,shs96c/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,zpao/buck,LegNeato/buck,nguyentruongtho/buck,SeleniumHQ/buck,LegNeato/buck,romanoid/buck,SeleniumHQ/buck,romanoid/buck,kageiit/buck,facebook/buck,nguyentruongtho/buck,shs96c/buck,brettwooldridge/buck,JoelMarcey/buck,shs96c/buck,nguyentruongtho/buck,SeleniumHQ/buck,rmaz/buck,LegNeato/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,facebook/buck,romanoid/buck,ilya-klyuchnikov/buck,rmaz/buck,JoelMarcey/buck,LegNeato/buck,JoelMarcey/buck,rmaz/buck,SeleniumHQ/buck,rmaz/buck,LegNeato/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,Addepar/buck,shs96c/buck,SeleniumHQ/buck,Addepar/buck,facebook/buck,clonetwin26/buck,clonetwin26/buck,romanoid/buck,clonetwin26/buck,Addepar/buck,brettwooldridge/buck,rmaz/buck,clonetwin26/buck,romanoid/buck,JoelMarcey/buck,Addepar/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,rmaz/buck,facebook/buck,LegNeato/buck,LegNeato/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,JoelMarcey/buck,Addepar/buck,shs96c/buck,brettwooldridge/buck,ilya-klyuchnikov/buck,zpao/buck,brettwooldridge/buck,Addepar/buck,zpao/buck,LegNeato/buck,nguyentruongtho/buck,zpao/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,LegNeato/buck,rmaz/buck,romanoid/buck,nguyentruongtho/buck,shs96c/buck,rmaz/buck,ilya-klyuchnikov/buck,kageiit/buck,clonetwin26/buck,JoelMarcey/buck,nguyentruongtho/buck,brettwooldridge/buck,romanoid/buck,kageiit/buck,brettwooldridge/buck,Addepar/buck,kageiit/buck,LegNeato/buck,shs96c/buck,brettwooldridge/buck,LegNeato/buck,LegNeato/buck,romanoid/buck,shs96c/buck,brettwooldridge/buck,Addepar/buck,brettwooldridge/buck,clonetwin26/buck | ---
+++
@@ -6,7 +6,7 @@
def setup_logging():
# Set log level of the messages to show.
- logger = logging.getLogger()
+
level_name = os.environ.get('BUCK_WRAPPER_LOG_LEVEL', 'INFO')
level_name_to_level = {
'CRITICAL': logging.CRITICAL,
@@ -17,9 +17,8 @@
'NOTSET': logging.NOTSET,
}
level = level_name_to_level.get(level_name.upper(), logging.INFO)
- logger.setLevel(level)
- # Set formatter for log messages.
- console_handler = logging.StreamHandler()
- formatter = logging.Formatter('%(message)s')
- console_handler.setFormatter(formatter)
- logger.addHandler(console_handler)
+ logging.basicConfig(
+ level=level,
+ format=(
+ '%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s'
+ )) |
f01921e6e2fbac76dc41e354b84f970b1591193d | nsone/rest/monitoring.py | nsone/rest/monitoring.py | #
# Copyright (c) 2014 NSONE, Inc.
#
# License under The MIT License (MIT). See LICENSE in project root.
#
from . import resource
class Monitors(resource.BaseResource):
ROOT = 'monitoring/jobs'
PASSTHRU_FIELDS = ['name', 'config']
def list(self, callback=None, errback=None):
return self._make_request('GET', '%s' % (self.ROOT),
callback=callback,
errback=errback)
def update(self, jobid, body, callback=None, errback=None, **kwargs):
self._buildStdBody(body, kwargs)
return self._make_request('POST',
'%s/%s' % (self.ROOT, jobid),
body=body,
callback=callback,
errback=errback)
def create(self,body, callback=None, errback=None):
return self._make_request('PUT', '%s' % (self.ROOT), body=body,
callback=callback,
errback=errback)
def retrieve(self, jobid, callback=None, errback=None):
return self._make_request('GET', '%s/%s' % (self.ROOT, jobid),
callback=callback,
errback=errback)
| #
# Copyright (c) 2014 NSONE, Inc.
#
# License under The MIT License (MIT). See LICENSE in project root.
#
from . import resource
class Monitors(resource.BaseResource):
ROOT = 'monitoring/jobs'
PASSTHRU_FIELDS = ['name', 'config']
def list(self, callback=None, errback=None):
return self._make_request('GET', '%s' % (self.ROOT),
callback=callback,
errback=errback)
def update(self, jobid, body, callback=None, errback=None, **kwargs):
self._buildStdBody(body, kwargs)
return self._make_request('POST',
'%s/%s' % (self.ROOT, jobid),
body=body,
callback=callback,
errback=errback)
def create(self,body, callback=None, errback=None):
return self._make_request('PUT', '%s' % (self.ROOT), body=body,
callback=callback,
errback=errback)
def retrieve(self, jobid, callback=None, errback=None):
return self._make_request('GET', '%s/%s' % (self.ROOT, jobid),
callback=callback,
errback=errback)
def delete(self, jobid, callback=None, errback=None):
return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid),
callback=callback,
errback=errback)
| Add support for monitor deletion | Add support for monitor deletion
| Python | mit | nsone/nsone-python,ns1/nsone-python | ---
+++
@@ -22,7 +22,7 @@
'%s/%s' % (self.ROOT, jobid),
body=body,
callback=callback,
- errback=errback)
+ errback=errback)
def create(self,body, callback=None, errback=None):
return self._make_request('PUT', '%s' % (self.ROOT), body=body,
@@ -33,3 +33,8 @@
return self._make_request('GET', '%s/%s' % (self.ROOT, jobid),
callback=callback,
errback=errback)
+
+ def delete(self, jobid, callback=None, errback=None):
+ return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid),
+ callback=callback,
+ errback=errback) |
5cbee0f9fb7ba360e00fbcf94c2c2a7a331dd1b6 | bayesian_jobs/handlers/sync_to_graph.py | bayesian_jobs/handlers/sync_to_graph.py | import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
GraphImporterTask.create_test_instance().execute(arguments)
del entry
| import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
format(**arguments))
del entry
| Handle errors in sync job | Handle errors in sync job
| Python | apache-2.0 | fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs | ---
+++
@@ -28,5 +28,10 @@
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
- GraphImporterTask.create_test_instance().execute(arguments)
+ try:
+ log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
+ GraphImporterTask.create_test_instance().execute(arguments)
+ except Exception as e:
+ self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
+ format(**arguments))
del entry |
bc70f78ef90f1758581dd7f3a8f8b5b2801375a6 | buildserver/config.buildserver.py | buildserver/config.buildserver.py | sdk_path = "/home/vagrant/android-sdk"
ndk_paths = {
'r9b': "/home/vagrant/android-ndk/r9b",
'r10e': "/home/vagrant/android-ndk/r10e",
}
build_tools = "22.0.1"
ant = "ant"
mvn3 = "mvn"
gradle = "gradle"
| sdk_path = "/home/vagrant/android-sdk"
ndk_paths = {
'r9b': "/home/vagrant/android-ndk/r9b",
'r10e': "/home/vagrant/android-ndk/r10e",
}
| Remove default config settings from the BS | Remove default config settings from the BS
| Python | agpl-3.0 | fdroidtravis/fdroidserver,fdroidtravis/fdroidserver,f-droid/fdroid-server,fdroidtravis/fdroidserver,f-droid/fdroidserver,matlink/fdroidserver,f-droid/fdroid-server,f-droid/fdroidserver,fdroidtravis/fdroidserver,f-droid/fdroid-server,f-droid/fdroidserver,f-droid/fdroid-server,f-droid/fdroidserver,matlink/fdroidserver,f-droid/fdroid-server,matlink/fdroidserver,f-droid/fdroidserver,matlink/fdroidserver,matlink/fdroidserver | ---
+++
@@ -3,7 +3,3 @@
'r9b': "/home/vagrant/android-ndk/r9b",
'r10e': "/home/vagrant/android-ndk/r10e",
}
-build_tools = "22.0.1"
-ant = "ant"
-mvn3 = "mvn"
-gradle = "gradle" |
6ef5a1a91e78c877a099b8c55df2f3f4d84686bb | bluesky/tests/test_vertical_integration.py | bluesky/tests/test_vertical_integration.py | from collections import defaultdict
from bluesky.examples import stepscan, det, motor
from bluesky.callbacks.broker import post_run, verify_files_saved
from functools import partial
def test_scan_and_get_data(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.mds.insert)
uid, = RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
db.fetch_events(hdr)
def test_post_run(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.mds.insert)
output = defaultdict(list)
def do_nothing(doctype, doc):
output[doctype].append(doc)
RE.ignore_callback_exceptions = False
RE(stepscan(det, motor), subs={'stop': [post_run(do_nothing, db=db)]})
assert len(output)
assert len(output['start']) == 1
assert len(output['stop']) == 1
assert len(output['descriptor']) == 1
assert len(output['event']) == 10
def test_verify_files_saved(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.mds.insert)
vfs = partial(verify_files_saved, db=db)
RE(stepscan(det, motor), subs={'stop': vfs})
| from collections import defaultdict
from bluesky.examples import stepscan, det, motor
from bluesky.callbacks.broker import post_run, verify_files_saved
from functools import partial
def test_scan_and_get_data(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.insert)
uid, = RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
list(hdr.events())
def test_post_run(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.insert)
output = defaultdict(list)
def do_nothing(doctype, doc):
output[doctype].append(doc)
RE(stepscan(det, motor), subs={'stop': [post_run(do_nothing, db=db)]})
assert len(output)
assert len(output['start']) == 1
assert len(output['stop']) == 1
assert len(output['descriptor']) == 1
assert len(output['event']) == 10
def test_verify_files_saved(fresh_RE, db):
RE = fresh_RE
RE.subscribe(db.insert)
vfs = partial(verify_files_saved, db=db)
RE(stepscan(det, motor), subs={'stop': vfs})
| Update to new databroker API. | TST: Update to new databroker API.
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky | ---
+++
@@ -6,23 +6,21 @@
def test_scan_and_get_data(fresh_RE, db):
RE = fresh_RE
- RE.subscribe(db.mds.insert)
+ RE.subscribe(db.insert)
uid, = RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
- db.fetch_events(hdr)
+ list(hdr.events())
def test_post_run(fresh_RE, db):
RE = fresh_RE
- RE.subscribe(db.mds.insert)
+ RE.subscribe(db.insert)
output = defaultdict(list)
def do_nothing(doctype, doc):
output[doctype].append(doc)
-
- RE.ignore_callback_exceptions = False
RE(stepscan(det, motor), subs={'stop': [post_run(do_nothing, db=db)]})
assert len(output)
@@ -34,7 +32,7 @@
def test_verify_files_saved(fresh_RE, db):
RE = fresh_RE
- RE.subscribe(db.mds.insert)
+ RE.subscribe(db.insert)
vfs = partial(verify_files_saved, db=db)
RE(stepscan(det, motor), subs={'stop': vfs}) |
b68576d307474eaf6bd8a8853bee767c391d28b9 | conjure/connection.py | conjure/connection.py | from .exceptions import ConnectionError
from pymongo import MongoClient
from pymongo.uri_parser import parse_uri
_connections = {}
try:
import gevent
except ImportError:
gevent = None
def _get_connection(uri):
global _connections
parsed_uri = parse_uri(uri)
hosts = parsed_uri['nodelist']
hosts = ['%s:%d' % host for host in hosts]
key = ','.join(hosts)
connection = _connections.get(key)
if connection is None:
try:
connection = _connections[key] = MongoClient(uri)
except Exception as e:
raise ConnectionError(e.message)
return connection
def connect(uri):
parsed_uri = parse_uri(uri)
username = parsed_uri['username']
password = parsed_uri['password']
database = parsed_uri['database']
db = _get_connection(uri)[database]
if username and password:
db.authenticate(username, password)
return db
| from .exceptions import ConnectionError
from pymongo import MongoClient
from pymongo.uri_parser import parse_uri
_connections = {}
try:
import gevent
except ImportError:
gevent = None
def _get_connection(uri):
global _connections
parsed_uri = parse_uri(uri)
hosts = parsed_uri['nodelist']
hosts = ['%s:%d' % host for host in hosts]
key = ','.join(hosts)
connection = _connections.get(key)
if connection is None:
try:
connection = _connections[key] = MongoClient(uri)
except Exception as e:
raise ConnectionError(e.message)
return connection
def connect(uri):
parsed_uri = parse_uri(uri)
username = parsed_uri['username']
password = parsed_uri['password']
database = parsed_uri['database']
db = _get_connection(uri)[database]
return db
| Remove authenticate call to fix issues with pymongo 3.7 | Remove authenticate call to fix issues with pymongo 3.7
| Python | mit | GGOutfitters/conjure | ---
+++
@@ -39,7 +39,4 @@
db = _get_connection(uri)[database]
- if username and password:
- db.authenticate(username, password)
-
return db |
0ae6b19f69976d2bcff4a0206ec97c6f9198eaa1 | whip/web.py | whip/web.py | """
Whip's REST API
"""
# pylint: disable=missing-docstring
import socket
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
key = socket.inet_aton(ip)
except socket.error:
abort(400)
dt = request.args.get('datetime')
if dt:
dt = dt.encode('ascii')
else:
dt = None # account for empty parameter value
info_as_json = db.lookup(key, dt)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
| """
Whip's REST API
"""
# pylint: disable=missing-docstring
import socket
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
key = socket.inet_aton(ip)
except socket.error:
abort(400)
dt = request.args.get('datetime')
info_as_json = db.lookup(key, dt)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
| Fix time-based lookups in REST API | Fix time-based lookups in REST API
Don't encode the datetime argument to bytes; the underlying function
expects a string argument.
| Python | bsd-3-clause | wbolster/whip | ---
+++
@@ -31,10 +31,6 @@
abort(400)
dt = request.args.get('datetime')
- if dt:
- dt = dt.encode('ascii')
- else:
- dt = None # account for empty parameter value
info_as_json = db.lookup(key, dt)
if info_as_json is None: |
fb8fbdedd28eddf55a4846c4af5f0137cad9adfb | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port"
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://hidemy.name/en/proxy-list/?country=US&type=h#list
* http://proxyservers.pro/proxy/list/protocol/http/country/US/
"""
PROXY_LIST = {
# "example1": "35.196.26.166:3128", # (Example) - set your own proxy here
# "example2": "208.95.62.81:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port"
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://hidemy.name/en/proxy-list/?country=US&type=h#list
* http://proxyservers.pro/proxy/list/protocol/http/country/US/
"""
PROXY_LIST = {
# "example1": "35.196.26.166:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| Remove an example proxy server definition | Remove an example proxy server definition
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,mdmintz/seleniumspot | ---
+++
@@ -19,7 +19,6 @@
PROXY_LIST = {
# "example1": "35.196.26.166:3128", # (Example) - set your own proxy here
- # "example2": "208.95.62.81:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None, |
881a133d30ab750368343d964f6b7110373cd9c5 | bazaar/goods/views.py | bazaar/goods/views.py | from django.views import generic
from ..mixins import BazaarPrefixMixin
from .models import Product
class ProductListView(BazaarPrefixMixin, generic.ListView):
model = Product
class ProductCreateView(BazaarPrefixMixin, generic.CreateView):
model = Product
| from django.views import generic
from ..mixins import BazaarPrefixMixin
from .models import Product
class ProductListView(BazaarPrefixMixin, generic.ListView):
model = Product
paginate_by = 20
class ProductCreateView(BazaarPrefixMixin, generic.CreateView):
model = Product
| Add pagination to product list view | Add pagination to product list view
| Python | bsd-2-clause | meghabhoj/NEWBAZAAR,meghabhoj/NEWBAZAAR,evonove/django-bazaar,meghabhoj/NEWBAZAAR,evonove/django-bazaar,evonove/django-bazaar | ---
+++
@@ -6,6 +6,7 @@
class ProductListView(BazaarPrefixMixin, generic.ListView):
model = Product
+ paginate_by = 20
class ProductCreateView(BazaarPrefixMixin, generic.CreateView): |
c6ab73a718d7f8c948ba79071993cd7a8f484ab5 | rm/userprofiles/views.py | rm/userprofiles/views.py | """
Views that allow us to edit user profile data
"""
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import UpdateView
from rm.userprofiles.forms import ProfileForm
from rm.userprofiles.models import RMUser
class RMUserUpdate(UpdateView):
model = RMUser
form_class = ProfileForm
success_url = reverse_lazy('account-edit')
def get_object(self, *args, **kwargs):
"""
Override the default get object to return the currently
logged in user.
"""
return self.request.user
| """
Views that allow us to edit user profile data
"""
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import UpdateView
from rm.http import LoginRequiredMixin
from rm.userprofiles.forms import ProfileForm
from rm.userprofiles.models import RMUser
class RMUserUpdate(LoginRequiredMixin, UpdateView):
model = RMUser
form_class = ProfileForm
success_url = reverse_lazy('account-edit')
def get_object(self, *args, **kwargs):
"""
Override the default get object to return the currently
logged in user.
"""
return self.request.user
| Make our account pages require a logged in user. | Make our account pages require a logged in user.
closes #221
| Python | agpl-3.0 | openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me | ---
+++
@@ -4,11 +4,12 @@
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import UpdateView
+from rm.http import LoginRequiredMixin
from rm.userprofiles.forms import ProfileForm
from rm.userprofiles.models import RMUser
-class RMUserUpdate(UpdateView):
+class RMUserUpdate(LoginRequiredMixin, UpdateView):
model = RMUser
form_class = ProfileForm
success_url = reverse_lazy('account-edit') |
d02e021a68333c52adff38cc869bf217deebfc5c | run.py | run.py | #!/usr/bin/env python3
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import pygame
from constants import *
from music_maker import *
from tkinter import Tk
def main():
# initialize game engine
pygame.init()
# We only use pygame for drawing, and mixer will hog cpu otherwise
# https://github.com/pygame/pygame/issues/331
pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE)
pygame.display.set_caption('Some digital instrument thing')
root = Tk()
root.withdraw() # won't need this
while get_font() == None:
init_font()
MusicMaker(screen)
# close the window and quit
pygame.quit()
print("Finished.")
if __name__ == '__main__':
main()
| Fix pygame mixer init hogging cpu | Fix pygame mixer init hogging cpu
| Python | mit | kenanbit/loopsichord | ---
+++
@@ -9,6 +9,10 @@
# initialize game engine
pygame.init()
+
+ # We only use pygame for drawing, and mixer will hog cpu otherwise
+ # https://github.com/pygame/pygame/issues/331
+ pygame.mixer.quit()
# set screen width/height and caption
screen = pygame.display.set_mode(SCREEN_DIM, pygame.RESIZABLE) |
0c60995d56f57a379438036c2775460268caa03b | settings.py | settings.py | import dj_database_url
DEBUG = True
TEMPLATE_DEBUG = True
SECRET_KEY = 'this is my secret key' # NOQA
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {
'default': dj_database_url.config(default='postgres:///psqlextra')
}
DATABASES['default']['ENGINE'] = 'psqlextra.backend'
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', 'English'),
('ro', 'Romanian'),
('nl', 'Dutch')
)
INSTALLED_APPS = (
'tests',
)
| import dj_database_url
DEBUG = True
TEMPLATE_DEBUG = True
SECRET_KEY = 'this is my secret key' # NOQA
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost:5434/psqlextra')
}
DATABASES['default']['ENGINE'] = 'psqlextra.backend'
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', 'English'),
('ro', 'Romanian'),
('nl', 'Dutch')
)
INSTALLED_APPS = (
'tests',
)
| Use last version of PostgreSQL on CI | Use last version of PostgreSQL on CI
| Python | mit | SectorLabs/django-postgres-extra | ---
+++
@@ -8,7 +8,7 @@
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
DATABASES = {
- 'default': dj_database_url.config(default='postgres:///psqlextra')
+ 'default': dj_database_url.config(default='postgres://localhost:5434/psqlextra')
}
DATABASES['default']['ENGINE'] = 'psqlextra.backend' |
844a165267e50d92b59c7c8fea97edcb1c8acf79 | judge/views/status.py | judge/views/status.py | from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.models import Judge
__all__ = ['status', 'status_table']
def status(request):
return render_to_response('judge_status.jade', {
'judges': Judge.objects.all(),
'title': 'Status',
}, context_instance=RequestContext(request))
def status_table(request):
return render_to_response('judge_status_table.jade', {
'judges': Judge.objects.all(),
}, context_instance=RequestContext(request))
| from django.shortcuts import render_to_response
from django.template import RequestContext
from judge.models import Judge
__all__ = ['status', 'status_table']
def status(request):
return render_to_response('judge_status.jade', {
'judges': Judge.objects.all(),
'title': 'Status',
}, context_instance=RequestContext(request))
def status_table(request):
return render_to_response('judge_status_table.jade', {
'judges': Judge.objects.all().order_by('load'),
}, context_instance=RequestContext(request))
| Order judge list by load | Order judge list by load
| Python | agpl-3.0 | Phoenix1369/site,Phoenix1369/site,DMOJ/site,Minkov/site,DMOJ/site,Phoenix1369/site,monouno/site,monouno/site,DMOJ/site,Minkov/site,monouno/site,Minkov/site,Minkov/site,monouno/site,Phoenix1369/site,DMOJ/site,monouno/site | ---
+++
@@ -15,5 +15,5 @@
def status_table(request):
return render_to_response('judge_status_table.jade', {
- 'judges': Judge.objects.all(),
+ 'judges': Judge.objects.all().order_by('load'),
}, context_instance=RequestContext(request)) |
3fbb013e8446af0be5013abec86c5503b9343d8e | kaf2html.py | kaf2html.py | """Script to generate an HTML page from a KAF file that shows the text contents
including line numbers.
"""
from bs4 import BeautifulSoup
with open('data/minnenijd.kaf') as f:
xml_doc = BeautifulSoup(f)
output_html = ['<html><head>',
'<meta http-equiv="Content-Type" content="text/html; ' \
'charset=utf-8">', '</head>', '<body>', '<p>']
current_para = 1
new_para = False
current_sent = 0
for token in xml_doc('wf'):
if int(token['para']) > current_para:
current_para = int(token['para'])
output_html.append('</p><p>')
new_para = True
if int(token['sent']) > current_sent:
current_sent = int(token['sent'])
if not new_para:
output_html.append('<br>')
output_html.append(str(current_sent))
output_html.append(': ')
new_para = False
output_html.append(token.text)
output_html.append('</p>')
html = BeautifulSoup(' '.join(output_html))
print html.prettify().encode('utf-8')
| """Script to generate an HTML page from a KAF file that shows the text contents
including line numbers.
"""
from bs4 import BeautifulSoup
with open('data/minnenijd.kaf') as f:
xml_doc = BeautifulSoup(f)
output_html = ['<html><head>',
'<meta http-equiv="Content-Type" content="text/html; '
'charset=utf-8">', '</head>', '<body>', '<p>']
current_para = None
new_para = False
current_sent = None
for token in xml_doc('wf'):
if token['para'] != current_para:
current_para = token['para']
output_html.append('</p><p>')
new_para = True
if token['sent'] != current_sent:
current_sent = token['sent']
if not new_para:
output_html.append('<br>')
output_html.append(str(current_sent))
output_html.append(': ')
new_para = False
# exctract text from cdata (waarom is dat nou weer zo!)
output_html.append(token.text)
output_html.append('</p>')
html = BeautifulSoup(' '.join(output_html))
print html.prettify().encode('utf-8')
| Change script to accept non-number versions of sent and para attributes | Change script to accept non-number versions of sent and para attributes
The script relied on numeric sent and para attributes. The code was
changed to also accept non-numeric sent and para attributes. In some
cases, the sent and para attributes returned by tools are not numeric.
| Python | apache-2.0 | NLeSC/embodied-emotions-scripts,NLeSC/embodied-emotions-scripts | ---
+++
@@ -8,25 +8,27 @@
xml_doc = BeautifulSoup(f)
output_html = ['<html><head>',
- '<meta http-equiv="Content-Type" content="text/html; ' \
+ '<meta http-equiv="Content-Type" content="text/html; '
'charset=utf-8">', '</head>', '<body>', '<p>']
-current_para = 1
+current_para = None
new_para = False
-current_sent = 0
+current_sent = None
for token in xml_doc('wf'):
- if int(token['para']) > current_para:
- current_para = int(token['para'])
+ if token['para'] != current_para:
+ current_para = token['para']
output_html.append('</p><p>')
new_para = True
- if int(token['sent']) > current_sent:
- current_sent = int(token['sent'])
+ if token['sent'] != current_sent:
+ current_sent = token['sent']
if not new_para:
output_html.append('<br>')
output_html.append(str(current_sent))
output_html.append(': ')
new_para = False
+
+ # exctract text from cdata (waarom is dat nou weer zo!)
output_html.append(token.text)
output_html.append('</p>') |
220f0199c97494e7b8a8ec913cf5251206f15550 | project/scripts/dates.py | project/scripts/dates.py | # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch
"""
return int(date.timestamp())
| # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timezone, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch (at exactly midnight utc on day of timestamp)
"""
year, month, day = date.year, date.month, date.day
dt = datetime(year=year, month=month, day=day)
utc_time = dt.replace(tzinfo = timezone.utc)
utc_dt = utc_time.timestamp()
return int(utc_dt)
| Fix date to epoch converter to timestamp at exactly midnight | Fix date to epoch converter to timestamp at exactly midnight
| Python | apache-2.0 | googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks | ---
+++
@@ -3,7 +3,7 @@
#!/usr/bin/env python3
-from datetime import datetime, timedelta
+from datetime import datetime, timezone, timedelta
import pytz
@@ -35,6 +35,11 @@
def date_to_epoch(date):
"""
- converts date object back into epoch
+ converts date object back into epoch (at exactly midnight utc on day of timestamp)
"""
- return int(date.timestamp())
+ year, month, day = date.year, date.month, date.day
+ dt = datetime(year=year, month=month, day=day)
+ utc_time = dt.replace(tzinfo = timezone.utc)
+ utc_dt = utc_time.timestamp()
+ return int(utc_dt)
+ |
fae7cd0a40d338f82404522a282b71a1cb4d84b1 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from os.path import abspath, dirname
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
ROOT_URLCONF='simple_history.tests.urls',
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'simple_history',
'simple_history.tests'
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
)
def main():
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import sys
from os.path import abspath, dirname
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
ROOT_URLCONF='simple_history.tests.urls',
STATIC_URL='/static/',
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'simple_history',
'simple_history.tests'
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
)
def main():
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
main()
| Fix STATIC_URL (for Django 1.5 admin tests) | Fix STATIC_URL (for Django 1.5 admin tests)
| Python | bsd-3-clause | luzfcb/django-simple-history,luzfcb/django-simple-history,pombredanne/django-simple-history,emergence/django-simple-history,treyhunner/django-simple-history,pombredanne/django-simple-history,treyhunner/django-simple-history,emergence/django-simple-history | ---
+++
@@ -11,6 +11,7 @@
if not settings.configured:
settings.configure(
ROOT_URLCONF='simple_history.tests.urls',
+ STATIC_URL='/static/',
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.auth', |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.