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 |
|---|---|---|---|---|---|---|---|---|---|---|
03d942731f970984bf039c531bff080affbb3b34 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Rajat Agarwal
from setuptools import setup, find_packages
import sqoot
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs')
codecs.register(func)
setup(
name='sqoot',
version='20140727',
author='Rajat Agarwal',
author_email='rajatagarwal@alumni.purdue.edu',
url='https://github.com/ragarwal6397',
description='Sqoot wrapper library',
long_description=open('./README.txt', 'r').read(),
download_url='https://github.com/ragarwal6397/sqoot/tarball/master',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'License :: OSI Approved :: MIT License',
],
packages=find_packages(),
install_requires=[
'requests>=2.1',
],
license='MIT License',
keywords='sqoot api',
include_package_data=True,
zip_safe=True,
)
| #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Rajat Agarwal
from setuptools import setup, find_packages
import sqoot
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs')
codecs.register(func)
setup(
name='sqoot',
version='20140923',
author='Rajat Agarwal',
author_email='rajatagarwal@alumni.purdue.edu',
url='https://github.com/ragarwal6397',
description='Sqoot wrapper library',
long_description=open('./README.txt', 'r').read(),
download_url='https://github.com/ragarwal6397/sqoot/tarball/master',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'License :: OSI Approved :: MIT License',
],
packages=find_packages(),
install_requires=[
'requests>=2.1',
],
license='MIT License',
keywords='sqoot api',
include_package_data=True,
zip_safe=True,
)
| Update the version number after last change | Update the version number after last change
| Python | mit | ragarwal6397/sqoot | ---
+++
@@ -18,7 +18,7 @@
setup(
name='sqoot',
- version='20140727',
+ version='20140923',
author='Rajat Agarwal',
author_email='rajatagarwal@alumni.purdue.edu',
url='https://github.com/ragarwal6397', |
841cb6e54c40ee745e69f8e0d538024a40e113c2 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-template-tests',
url="https://chris-lamb.co.uk/projects/django-template-tests",
version='1.0.0',
description="Performs some quick static analysis on your templates",
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
license="BSD",
packages=find_packages(),
include_package_data=True,
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-template-tests',
url="https://chris-lamb.co.uk/projects/django-template-tests",
version='1.0.0',
description="Performs some quick static analysis on your templates",
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=(
'Django>=1.8',
),
)
| Update Django requirement to latest LTS | Update Django requirement to latest LTS
| Python | bsd-3-clause | lamby/django-template-tests | ---
+++
@@ -15,4 +15,8 @@
packages=find_packages(),
include_package_data=True,
+
+ install_requires=(
+ 'Django>=1.8',
+ ),
) |
6f3b45cd6b5558a7d81472c0298aae7d04f64846 | jsonit/utils.py | jsonit/utils.py | import os
from django.http import HttpResponse
from django.template import RequestContext, loader
def ajax_aware_render(request, template_list, extra_context=None, **kwargs):
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
new_template_list = []
for name in template_list:
new_template_list.append('%s.ajax.%s' % os.path.splitext(name))
new_template_list.append(name)
template_list = new_template_list
c = RequestContext(request, extra_context)
t = loader.select_template(template_list)
return HttpResponse(t.render(c), **kwargs)
| import os
from django.http import HttpResponse
from django.template import RequestContext, loader
def ajax_aware_render(request, template_list, extra_context=None, **kwargs):
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
ajax_template_list = []
for name in template_list:
ajax_template_list.append('%s.ajax.%s' % os.path.splitext(name))
template_list = ajax_template_list + list(template_list)
c = RequestContext(request, extra_context)
t = loader.select_template(template_list)
return HttpResponse(t.render(c), **kwargs)
| Change the ordering of templates to pick from for the ajax render helper | Change the ordering of templates to pick from for the ajax render helper
| Python | bsd-3-clause | lincolnloop/django-jsonit | ---
+++
@@ -8,11 +8,10 @@
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
- new_template_list = []
+ ajax_template_list = []
for name in template_list:
- new_template_list.append('%s.ajax.%s' % os.path.splitext(name))
- new_template_list.append(name)
- template_list = new_template_list
+ ajax_template_list.append('%s.ajax.%s' % os.path.splitext(name))
+ template_list = ajax_template_list + list(template_list)
c = RequestContext(request, extra_context)
t = loader.select_template(template_list)
return HttpResponse(t.render(c), **kwargs) |
253e4e9df1b6a6cec7c20bc34a8ccf9423c8018e | scripts/create_neurohdf.py | scripts/create_neurohdf.py | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 1
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile:
mesh=hfile.create_group('meshes')
midline=mesh.create_group('midline')
midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) )
# faces are coded according to the three.js JSONLoader standard.
# See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js
midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
| #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile:
mesh=hfile.create_group('meshes')
midline=mesh.create_group('midline')
midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) )
# faces are coded according to the three.js JSONLoader standard.
# See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js
midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) )
| Change in coordinates in the NeuroHDF create | Change in coordinates in the NeuroHDF create
| Python | agpl-3.0 | htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID | ---
+++
@@ -9,13 +9,13 @@
import numpy as np
project_id = 1
-stack_id = 1
+stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile:
mesh=hfile.create_group('meshes')
midline=mesh.create_group('midline')
- midline.create_dataset("vertices", data=np.array( [4900, 40, 0, 5230, 70, 4131, 5250,7620,4131, 4820,7630,0] , dtype = np.float32 ) )
+ midline.create_dataset("vertices", data=np.array( [61200, 15200, 26750,63920, 26400, 76800, 66800,57600,76800, 69200,53120,26750] , dtype = np.float32 ) )
# faces are coded according to the three.js JSONLoader standard.
# See https://github.com/mrdoob/three.js/blob/master/src/extras/loaders/JSONLoader.js
midline.create_dataset("faces", data=np.array( [0, 0, 1, 2, 0,2,3,0] , dtype = np.uint32 ) ) |
a134179d143f05842315a134f0a744f61003d2ca | tests.py | tests.py | #!/usr/bin/env python
from datetime import date
import os
import sys
argv = sys.argv
if '-w' not in argv and '--where' not in argv:
argv[1:1] = ['-w', 'tests']
if '--logging-level' not in argv:
argv[1:1] = ['--logging-level', 'INFO']
try:
import nose
except ImportError:
print('Could not find the nose test runner.')
sys.exit(1)
print('Running nosetests %s' % ' '.join(argv[1:]))
nose.run(argv=argv)
| #!/usr/bin/env python
from datetime import date
import os
import sys
argv = sys.argv
if '-w' not in argv and '--where' not in argv:
argv[1:1] = ['-w', 'tests']
if '--logging-level' not in argv:
argv[1:1] = ['--logging-level', 'INFO']
try:
import nose
except ImportError:
print('Could not find the nose test runner.')
sys.exit(1)
print('Running nosetests %s' % ' '.join(argv[1:]))
nose.main(argv=argv)
| Use nose.main instead of nose.run. | Use nose.main instead of nose.run.
| Python | apache-2.0 | mikekap/batchy | ---
+++
@@ -16,4 +16,4 @@
sys.exit(1)
print('Running nosetests %s' % ' '.join(argv[1:]))
-nose.run(argv=argv)
+nose.main(argv=argv) |
f06c7813663dc9ac4bf63601574617acf5d7324d | tests.py | tests.py | from models import AuthenticationError,AuthenticationRequired
import trello
import unittest
import os
class TestTrello(unittest.TestCase):
def test_login(self):
username = os.environ['TRELLO_TEST_USER']
password = os.environ['TRELLO_TEST_PASS']
try:
trello.login(username, password)
except AuthenticationError:
self.fail("Could not authenticate")
except Exception as e:
self.fail("Unknown error: "+str(e))
if __name__ == "__main__":
unittest.main()
| from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class BoardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
print "list boards"
self.assertEquals(
len(self._trello.list_boards()),
int(os.environ['TRELLO_TEST_BOARD_COUNT']))
def test02_board_attrs(self):
print "board attrs"
boards = self._trello.list_boards()
for b in boards:
self.assertIsNotNone(b['_id'], msg="_id not provided")
self.assertIsNotNone(b['name'], msg="name not provided")
self.assertIsNotNone(b['closed'], msg="closed not provided")
class CardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
if __name__ == "__main__":
unittest.main()
| Add some more test cases | Add some more test cases
| Python | bsd-3-clause | mehdy/py-trello,sarumont/py-trello,nMustaki/py-trello,Wooble/py-trello,ntrepid8/py-trello,WoLpH/py-trello,portante/py-trello,merlinpatt/py-trello,gchp/py-trello | ---
+++
@@ -1,19 +1,32 @@
from models import AuthenticationError,AuthenticationRequired
-import trello
+from trello import Trello
import unittest
import os
-class TestTrello(unittest.TestCase):
+class BoardTestCase(unittest.TestCase):
- def test_login(self):
- username = os.environ['TRELLO_TEST_USER']
- password = os.environ['TRELLO_TEST_PASS']
- try:
- trello.login(username, password)
- except AuthenticationError:
- self.fail("Could not authenticate")
- except Exception as e:
- self.fail("Unknown error: "+str(e))
+ def setUp(self):
+ self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
+
+ def test01_list_boards(self):
+ print "list boards"
+ self.assertEquals(
+ len(self._trello.list_boards()),
+ int(os.environ['TRELLO_TEST_BOARD_COUNT']))
+
+ def test02_board_attrs(self):
+ print "board attrs"
+ boards = self._trello.list_boards()
+ for b in boards:
+ self.assertIsNotNone(b['_id'], msg="_id not provided")
+ self.assertIsNotNone(b['name'], msg="name not provided")
+ self.assertIsNotNone(b['closed'], msg="closed not provided")
+
+class CardTestCase(unittest.TestCase):
+ def setUp(self):
+ self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
+
+
if __name__ == "__main__":
unittest.main() |
14f3df107a2b129ff7f22c849de2aa19326db074 | worker.py | worker.py | import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
self.fn()
exit(0)
else:
return 0
except Exception as e:
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail
return 1
| import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
self.fn()
exit(0)
else:
return 0
except Exception as e:
#TODO logging the error message
print(str(e))
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail
return 1
| Add temporary error logging for debugging | Add temporary error logging for debugging
Now just print out the Exception message for debugging,
it will change to logging in the future
| Python | apache-2.0 | stvreumi/electronic-blackboard,stvreumi/electronic-blackboard,stvreumi/electronic-blackboard,SWLBot/electronic-blackboard,Billy4195/electronic-blackboard,Billy4195/electronic-blackboard,SWLBot/electronic-blackboard,stvreumi/electronic-blackboard,SWLBot/electronic-blackboard,SWLBot/electronic-blackboard,Billy4195/electronic-blackboard,Billy4195/electronic-blackboard | ---
+++
@@ -16,6 +16,8 @@
else:
return 0
except Exception as e:
+ #TODO logging the error message
+ print(str(e))
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail |
f2ef48c3b1753e4b53b86c1f9d7a3da517a6d136 | web/impact/impact/models/utils.py | web/impact/impact/models/utils.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import re
LABEL_LENGTH = 255
def is_managed(db_table):
return False
def model_name_to_snake(value):
original_model_string = re.findall('[A-Z][^A-Z]*', value)
holder = ""
for word in original_model_string:
holder += word.lower() + "_"
new_model_string = holder[:-1]
return new_model_string
def snake_to_model_name(value):
old_value = value.split('_')
new_value = ""
for word in old_value:
new_value += (word[0].upper() + word[1:])
return new_value
| # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import re
from django.utils.text import camel_case_to_spaces
LABEL_LENGTH = 255
def is_managed(db_table):
return False
def model_name_to_snake(value):
original_model_string = camel_case_to_spaces(value)
new_model_string = original_model_string.replace(" ", "_")
return new_model_string
def snake_to_model_name(value):
old_value = value.split('_')
new_value = ""
for word in old_value:
new_value += (word[0].upper() + word[1:])
return new_value
| Remove Custom Reegex And Use Django Util For Case Conversion | [AC-5010] Remove Custom Reegex And Use Django Util For Case Conversion
This commit uses the django built in to switch from camel case to lower case. Then the loop was removed in favor of replace().
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -2,6 +2,7 @@
# Copyright (c) 2017 MassChallenge, Inc.
import re
+from django.utils.text import camel_case_to_spaces
LABEL_LENGTH = 255
@@ -11,11 +12,8 @@
def model_name_to_snake(value):
- original_model_string = re.findall('[A-Z][^A-Z]*', value)
- holder = ""
- for word in original_model_string:
- holder += word.lower() + "_"
- new_model_string = holder[:-1]
+ original_model_string = camel_case_to_spaces(value)
+ new_model_string = original_model_string.replace(" ", "_")
return new_model_string
|
28bf565f30a6d9b25bd6bc24ce5958a98a106161 | mpi/__init__.py | mpi/__init__.py | #! /usr/bin/env python
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def finalize():
return MPI.Finalize()
| #! /usr/bin/env python
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def host_rank_mapping():
"""Get host to rank mapping
Return dictionary mapping ranks to host
"""
d = {}
for (host, rank) in comm.allgather((get_host(), get_rank())):
if host not in d:
d[host] = []
d[host].append(rank)
return d
def finalize():
return MPI.Finalize()
| Add function to get the host-rank mapping of mpi tasks | Add function to get the host-rank mapping of mpi tasks
| Python | mit | IanLee1521/utilities | ---
+++
@@ -14,5 +14,18 @@
return comm.Get_rank()
+def host_rank_mapping():
+ """Get host to rank mapping
+
+ Return dictionary mapping ranks to host
+ """
+ d = {}
+ for (host, rank) in comm.allgather((get_host(), get_rank())):
+ if host not in d:
+ d[host] = []
+ d[host].append(rank)
+ return d
+
+
def finalize():
return MPI.Finalize() |
67a5eb0921f746c205e555ae296b6c15e4eb7eab | property_transformation.py | property_transformation.py | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
results[key] = source_properties[value]
else:
raise PropertyMappingFailedException("property %s not found in source feature" %
(value))
elif type(value) == dict:
if "static" in value:
results[key] = value["static"]
elif "mapping" in value:
if not "key" in value:
raise PropertyMappingFailedException(
"Found mapping, but no key specified to map")
source_value = source_properties[value['key']]
if source_value in value['mapping']:
results[key] = value['mapping'][source_value]
else:
raise PropertyMappingFailedException(
"value:%s not found in mapping for key:%s" %
(source_value, key))
else:
raise PropertyMappingFailedException(
"Failed to find key for mapping in dict for field:%s" %
(key,))
else:
raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" %
(key, type(value)))
return results
| from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
results[key] = source_properties[value]
else:
raise PropertyMappingFailedException("property %s not found in source feature" %
(value))
elif type(value) == dict:
if "static" in value:
results[key] = value["static"]
elif "mapping" in value:
if not "key" in value:
raise PropertyMappingFailedException(
"Found mapping, but no key specified to map")
source_value = source_properties[value['key']]
if source_value is None:
source_value = "null"
if source_value in value['mapping']:
results[key] = value['mapping'][source_value]
else:
raise PropertyMappingFailedException(
"value:%s not found in mapping for key:%s" %
(source_value, key))
else:
raise PropertyMappingFailedException(
"Failed to find key for mapping in dict for field:%s" %
(key,))
else:
raise PropertyMappingFailedException("Unhandled mapping for key:%s value type:%s" %
(key, type(value)))
return results
| Add support for null values in property mapping | Add support for null values in property mapping
| Python | mit | OpenBounds/Processing | ---
+++
@@ -20,6 +20,8 @@
raise PropertyMappingFailedException(
"Found mapping, but no key specified to map")
source_value = source_properties[value['key']]
+ if source_value is None:
+ source_value = "null"
if source_value in value['mapping']:
results[key] = value['mapping'][source_value]
else: |
71a417d2558776cd29195c1a1b905070a08407b5 | proteus/config/__init__.py | proteus/config/__init__.py | import platform
if platform.node().startswith('garnet') or platform.node().startswith('copper'):
from garnet import *
else:
from default import * | import os
if 'HOSTNAME' in os.environ:
if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'):
from garnet import *
else:
from default import * | Correct detection on Garnet/Copper compute nodes | Correct detection on Garnet/Copper compute nodes
| Python | mit | erdc/proteus,erdc/proteus,erdc/proteus,erdc/proteus | ---
+++
@@ -1,6 +1,7 @@
-import platform
+import os
-if platform.node().startswith('garnet') or platform.node().startswith('copper'):
- from garnet import *
+if 'HOSTNAME' in os.environ:
+ if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'):
+ from garnet import *
else:
from default import * |
633c52cf90655981d1adc962d7571d5d67619ccb | genome_designer/genome_finish/contig_display_utils.py | genome_designer/genome_finish/contig_display_utils.py | from collections import namedtuple
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
return (contig.parent_reference_genome.get_client_jbrowse_link() +
'&loc=' + str(loc))
def decorate_with_link_to_loc(contig, loc, text):
return ('<a href="' + get_ref_jbrowse_link(contig, loc) +
'&tracks=' + contig.get_contig_reads_track() +
'" target="_blank">' + text + '</a>')
def make_html_list(li, css_class='list-unstyled'):
return ('<ul class="' + css_class + '"><li>' +
'</li><li>'.join(li) +
'</li></ul>')
def create_contig_junction_links(contig, junctions):
link_list = ['<span>→</span>'.join(
[decorate_with_link_to_loc(contig, j.ref,
'%s(%s)' % (j.ref, j.ref_count)),
'%s(%s)' % (j.contig, j.contig_count)])
for j in map(Junction._make, junctions)]
return make_html_list(link_list)
| from collections import namedtuple
import settings
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
sample_alignment = contig.experiment_sample_to_alignment
bam_dataset = sample_alignment.dataset_set.get(
type='BWA BAM')
sample_bam_track = '_'.join([
bam_dataset.internal_string(sample_alignment.experiment_sample),
str(sample_alignment.alignment_group.uid)])
track_labels = settings.JBROWSE_DEFAULT_TRACKS + [sample_bam_track]
return (contig.parent_reference_genome.get_client_jbrowse_link() +
'&loc=' + str(loc) +
'&tracks=' + ','.join(track_labels))
def decorate_with_link_to_loc(contig, loc, text):
return ('<a href="' + get_ref_jbrowse_link(contig, loc) +
',' + contig.get_contig_reads_track() +
'" target="_blank">' + text + '</a>')
def make_html_list(li, css_class='list-unstyled'):
return ('<ul class="' + css_class + '"><li>' +
'</li><li>'.join(li) +
'</li></ul>')
def create_contig_junction_links(contig, junctions):
link_list = ['<span>→</span>'.join(
[decorate_with_link_to_loc(contig, j.ref,
'%s(%s)' % (j.ref, j.ref_count)),
'%s(%s)' % (j.contig, j.contig_count)])
for j in map(Junction._make, junctions)]
return make_html_list(link_list)
| Include more tracks in jbrowsing of junctions | Include more tracks in jbrowsing of junctions
| Python | mit | churchlab/millstone,churchlab/millstone,woodymit/millstone,woodymit/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone,churchlab/millstone | ---
+++
@@ -1,17 +1,30 @@
from collections import namedtuple
+
+import settings
+
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
- return (contig.parent_reference_genome.get_client_jbrowse_link() +
- '&loc=' + str(loc))
+ sample_alignment = contig.experiment_sample_to_alignment
+ bam_dataset = sample_alignment.dataset_set.get(
+ type='BWA BAM')
+
+ sample_bam_track = '_'.join([
+ bam_dataset.internal_string(sample_alignment.experiment_sample),
+ str(sample_alignment.alignment_group.uid)])
+
+ track_labels = settings.JBROWSE_DEFAULT_TRACKS + [sample_bam_track]
+ return (contig.parent_reference_genome.get_client_jbrowse_link() +
+ '&loc=' + str(loc) +
+ '&tracks=' + ','.join(track_labels))
def decorate_with_link_to_loc(contig, loc, text):
return ('<a href="' + get_ref_jbrowse_link(contig, loc) +
- '&tracks=' + contig.get_contig_reads_track() +
+ ',' + contig.get_contig_reads_track() +
'" target="_blank">' + text + '</a>')
|
bbe425da10607692c1aace560b1b61b089137704 | frappe/patches/v12_0/rename_events_repeat_on.py | frappe/patches/v12_0/rename_events_repeat_on.py | import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", "doctype", "event")
# Initially Daily Events had option to choose days, but now Weekly does, so just changing from Daily -> Weekly does the job
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Day'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Week'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Monthly' WHERE `tabEvent`.repeat_on='Every Month'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Yearly' WHERE `tabEvent`.repeat_on='Every Year'""")
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.{0}=1 WHERE `tabEvent`.name='{1}'""".format(weekdays[get_datetime(weekly_event.starts_on).weekday()], weekly_event.name))
| import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", "doctype", "event")
# Initially Daily Events had option to choose days, but now Weekly does, so just changing from Daily -> Weekly does the job
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Day'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Weekly' WHERE `tabEvent`.repeat_on='Every Week'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Monthly' WHERE `tabEvent`.repeat_on='Every Month'""")
frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.repeat_on='Yearly' WHERE `tabEvent`.repeat_on='Every Year'""")
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
frappe.db.set_value('Event', weekly_event.name, weekdays[get_datetime(weekly_event.starts_on).weekday()], 1, update_modified=1)
| Convert to SQL to set_value | fix: Convert to SQL to set_value | Python | mit | mhbu50/frappe,saurabh6790/frappe,vjFaLk/frappe,almeidapaulopt/frappe,vjFaLk/frappe,frappe/frappe,almeidapaulopt/frappe,vjFaLk/frappe,mhbu50/frappe,mhbu50/frappe,StrellaGroup/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,yashodhank/frappe,StrellaGroup/frappe,adityahase/frappe,saurabh6790/frappe,vjFaLk/frappe,adityahase/frappe,frappe/frappe,saurabh6790/frappe,yashodhank/frappe,frappe/frappe,yashodhank/frappe,saurabh6790/frappe | ---
+++
@@ -15,4 +15,4 @@
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
- frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.{0}=1 WHERE `tabEvent`.name='{1}'""".format(weekdays[get_datetime(weekly_event.starts_on).weekday()], weekly_event.name))
+ frappe.db.set_value('Event', weekly_event.name, weekdays[get_datetime(weekly_event.starts_on).weekday()], 1, update_modified=1) |
468f41f0bf734cdbb27dea7b5d910b6234f4c21a | homedisplay/control_milight/management/commands/run_timed.py | homedisplay/control_milight/management/commands/run_timed.py | from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Command(BaseCommand):
args = ''
help = 'Run timed transitions'
def handle(self, *args, **options):
redis_instance = redis.StrictRedis()
led = LedController(settings.MILIGHT_IP)
time = datetime.datetime.now()
hour = datetime.time(time.hour, time.minute)
for item in LightAutomation.objects.filter(running=True):
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
if item.action == "evening":
print "Setting evening brightness to", ((1-percent_done)*100)
led.set_brightness(int((1-percent_done)*100))
elif item.action == "morning":
print "Setting morning brightness to", ((percent_done)*100)
led.set_brightness(int((percent_done)*100))
led.white()
# update_lightstate(transition.group.group_id, transition.to_brightness, transition.to_color)
| from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Command(BaseCommand):
args = ''
help = 'Run timed transitions'
def handle(self, *args, **options):
redis_instance = redis.StrictRedis()
led = LedController(settings.MILIGHT_IP)
time = datetime.datetime.now()
hour = datetime.time(time.hour, time.minute)
for item in LightAutomation.objects.filter(running=True):
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
if item.action == "evening" or item.action == "evening-weekend":
print "Setting evening brightness to", ((1-percent_done)*100)
led.set_brightness(int((1-percent_done)*100))
elif item.action == "morning" or item.action == "morning-weekend":
print "Setting morning brightness to", ((percent_done)*100)
led.set_brightness(int((percent_done)*100))
led.white()
# update_lightstate(transition.group.group_id, transition.to_brightness, transition.to_color)
| Add support for weekend animations | Add support for weekend animations
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | ---
+++
@@ -21,10 +21,10 @@
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
- if item.action == "evening":
+ if item.action == "evening" or item.action == "evening-weekend":
print "Setting evening brightness to", ((1-percent_done)*100)
led.set_brightness(int((1-percent_done)*100))
- elif item.action == "morning":
+ elif item.action == "morning" or item.action == "morning-weekend":
print "Setting morning brightness to", ((percent_done)*100)
led.set_brightness(int((percent_done)*100))
led.white() |
18a3b758311174d0be2519789f985d8113438c90 | tests/test_dirty_mark.py | tests/test_dirty_mark.py | def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
def test_set_parent(nested_config):
nested_config.root.value += 1
assert nested_config.is_dirty()
def test_set_child(nested_config):
nested_config.root.a.value += 1
assert nested_config.is_dirty()
assert nested_config['a'].is_dirty()
assert not nested_config['a2'].is_dirty()
def test_mark_clean(nested_config):
nested_config.root.a.value += 1
nested_config.mark_clean()
test_not_dirty_by_default(nested_config)
| from confetti import Config
def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
def test_set_parent(nested_config):
nested_config.root.value += 1
assert nested_config.is_dirty()
def test_set_child(nested_config):
nested_config.root.a.value += 1
assert nested_config.is_dirty()
assert nested_config['a'].is_dirty()
assert not nested_config['a2'].is_dirty()
def test_mark_clean(nested_config):
nested_config.root.a.value += 1
nested_config.mark_clean()
test_not_dirty_by_default(nested_config)
def test_extending_doesnt_count_as_dirty(nested_config):
nested_config.extend(Config({
'new_value': 2}))
assert not nested_config.is_dirty()
| Add test for extending not being marked as dirty | Add test for extending not being marked as dirty
| Python | bsd-3-clause | vmalloc/confetti | ---
+++
@@ -1,3 +1,6 @@
+from confetti import Config
+
+
def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
@@ -7,13 +10,21 @@
nested_config.root.value += 1
assert nested_config.is_dirty()
+
def test_set_child(nested_config):
nested_config.root.a.value += 1
assert nested_config.is_dirty()
assert nested_config['a'].is_dirty()
assert not nested_config['a2'].is_dirty()
+
def test_mark_clean(nested_config):
nested_config.root.a.value += 1
nested_config.mark_clean()
test_not_dirty_by_default(nested_config)
+
+
+def test_extending_doesnt_count_as_dirty(nested_config):
+ nested_config.extend(Config({
+ 'new_value': 2}))
+ assert not nested_config.is_dirty() |
22e41d02d9c877703f21c5121202d295cb5fbcb0 | test/swig/canvas.py | test/swig/canvas.py | # RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
mgr = uwhd.GameModelManager()
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))
print('# SET-TIME: %d' % (time,))
mgr.setGameStateFirstHalf()
mgr.setBlackScore(black_score)
mgr.setWhiteScore(white_score)
mgr.setGameClock(time)
canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
uwhd.renderGameDisplay(1, mgr.getModel(), canvas)
ppmstr = uwhd.asPPMString(canvas)
print(ppmstr)
if __name__ == '__main__':
main()
| # RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
# Build a GameModelManager with a known state:
mgr = uwhd.GameModelManager()
mgr.setGameStateFirstHalf()
mgr.setBlackScore(black_score)
mgr.setWhiteScore(white_score)
mgr.setGameClock(time)
# Render that state to a canvas:
canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
uwhd.renderGameDisplay(version, mgr.getModel(), canvas)
# Print out the expected and actual display state
# for display-check to verify:
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))
print('# SET-TIME: %d' % (time,))
print(uwhd.asPPMString(canvas))
if __name__ == '__main__':
main()
| Clean up the SWIG test. Add comments. NFC | [tests] Clean up the SWIG test. Add comments. NFC
| Python | bsd-3-clause | Navisjon/uwh-display,Navisjon/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,jroelofs/uwh-display | ---
+++
@@ -8,24 +8,25 @@
white_score = 5
time = 42
+ # Build a GameModelManager with a known state:
mgr = uwhd.GameModelManager()
+ mgr.setGameStateFirstHalf()
+ mgr.setBlackScore(black_score)
+ mgr.setWhiteScore(white_score)
+ mgr.setGameClock(time)
+ # Render that state to a canvas:
+ canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
+ uwhd.renderGameDisplay(version, mgr.getModel(), canvas)
+
+ # Print out the expected and actual display state
+ # for display-check to verify:
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))
print('# SET-TIME: %d' % (time,))
-
- mgr.setGameStateFirstHalf()
- mgr.setBlackScore(black_score)
- mgr.setWhiteScore(white_score)
- mgr.setGameClock(time)
-
- canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
- uwhd.renderGameDisplay(1, mgr.getModel(), canvas)
- ppmstr = uwhd.asPPMString(canvas)
-
- print(ppmstr)
+ print(uwhd.asPPMString(canvas))
if __name__ == '__main__':
main() |
02d7f2b946293169e3d46f84f50f2fa801a33c95 | distarray/tests/test_client.py | distarray/tests/test_client.py | import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
if __name__ == '__main__':
unittest.main(verbosity=2)
| import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
if __name__ == '__main__':
unittest.main(verbosity=2)
| Add simple failing test for DistArrayProxy getitem. | Add simple failing test for DistArrayProxy getitem. | Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray | ---
+++
@@ -1,4 +1,5 @@
import unittest
+import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
@@ -20,5 +21,18 @@
self.assertIs(dac.view, self.dv)
+class TestDistArrayProxy(unittest.TestCase):
+
+ def setUp(self):
+ self.client = Client()
+ self.dv = self.client[:]
+ self.dac = DistArrayContext(self.dv)
+
+ self.dap = self.dac.fromndarray(np.arange(100))
+
+ def test_getitem(self):
+ self.assertEqual(self.dap[55], 55)
+
+
if __name__ == '__main__':
unittest.main(verbosity=2) |
e99f7b6d25464f36accc2f04899edfa9e982bee2 | tests/cpydiff/core_fstring_concat.py | tests/cpydiff/core_fstring_concat.py | """
categories: Core
description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces
cause: MicroPython is optimised for code space.
workaround: Use the + operator between literal strings when either is an f-string
"""
x = 1
print("aa" f"{x}")
print(f"{x}" "ab")
print("a{}a" f"{x}")
print(f"{x}" "a{}b")
| """
categories: Core
description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces or are f-strings
cause: MicroPython is optimised for code space.
workaround: Use the + operator between literal strings when either or both are f-strings
"""
x, y = 1, 2
print("aa" f"{x}") # works
print(f"{x}" "ab") # works
print("a{}a" f"{x}") # fails
print(f"{x}" "a{}b") # fails
print(f"{x}" f"{y}") # fails
| Clarify f-string diffs regarding concatenation. | tests/cpydiff: Clarify f-string diffs regarding concatenation.
Concatenation of any literals (including f-strings) should be avoided.
Signed-off-by: Jim Mussared <e84f5c941266186d0c97dcc873413469b954847e@gmail.com>
| Python | mit | adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython | ---
+++
@@ -1,12 +1,13 @@
"""
categories: Core
-description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces
+description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces or are f-strings
cause: MicroPython is optimised for code space.
-workaround: Use the + operator between literal strings when either is an f-string
+workaround: Use the + operator between literal strings when either or both are f-strings
"""
-x = 1
-print("aa" f"{x}")
-print(f"{x}" "ab")
-print("a{}a" f"{x}")
-print(f"{x}" "a{}b")
+x, y = 1, 2
+print("aa" f"{x}") # works
+print(f"{x}" "ab") # works
+print("a{}a" f"{x}") # fails
+print(f"{x}" "a{}b") # fails
+print(f"{x}" f"{y}") # fails |
55b0d7eba281fc2c13505c956f5c23bb49b34988 | tests/test_qiniu.py | tests/test_qiniu.py | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token()
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err) | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
text = text[:len(text)/10]
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token()
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err) | Test with even smaller files | Test with even smaller files
| Python | mit | glasslion/django-qiniu-storage,jeffrey4l/django-qiniu-storage,Mark-Shine/django-qiniu-storage,jackeyGao/django-qiniu-storage | ---
+++
@@ -22,6 +22,7 @@
ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
+ text = text[:len(text)/10]
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token() |
f67704c271b8b88ba97d1b44c73552119d79b048 | tests/test_utils.py | tests/test_utils.py | import pickle
from six.moves import range
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_pickable", "bulky_attr")
class TestClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_pickable = lambda x: x
def test_do_not_pickle_attributes():
cl = TestClass()
dump = pickle.dumps(cl)
loaded = pickle.loads(dump)
assert loaded.bulky_attr == list(range(100))
assert loaded.non_pickable is not None
| from numpy.testing import assert_raises, assert_equal
from six.moves import range, cPickle
from fuel.iterator import DataIterator
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_picklable", "bulky_attr")
class DummyClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_picklable = lambda x: x
class FaultyClass(object):
pass
@do_not_pickle_attributes("iterator")
class UnpicklableClass(object):
def __init__(self):
self.load()
def load(self):
self.iterator = DataIterator(None)
@do_not_pickle_attributes("attribute")
class NonLoadingClass(object):
def load(self):
pass
class TestDoNotPickleAttributes(object):
def test_load(self):
instance = cPickle.loads(cPickle.dumps(DummyClass()))
assert_equal(instance.bulky_attr, list(range(100)))
assert instance.non_picklable is not None
def test_value_error_no_load_method(self):
assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass)
def test_value_error_iterator(self):
assert_raises(ValueError, cPickle.dumps, UnpicklableClass())
def test_value_error_attribute_non_loaded(self):
assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute')
| Increase test coverage in utils.py | Increase test coverage in utils.py
| Python | mit | chrishokamp/fuel,ejls/fuel,harmdevries89/fuel,glewis17/fuel,EderSantana/fuel,rodrigob/fuel,markusnagel/fuel,bouthilx/fuel,janchorowski/fuel,aalmah/fuel,vdumoulin/fuel,rodrigob/fuel,orhanf/fuel,laurent-dinh/fuel,rizar/fuel,capybaralet/fuel,aalmah/fuel,hantek/fuel,mila-udem/fuel,janchorowski/fuel,hantek/fuel,dmitriy-serdyuk/fuel,rizar/fuel,dwf/fuel,dhruvparamhans/fuel,chrishokamp/fuel,harmdevries89/fuel,dhruvparamhans/fuel,markusnagel/fuel,mjwillson/fuel,mila-udem/fuel,jbornschein/fuel,udibr/fuel,orhanf/fuel,glewis17/fuel,bouthilx/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,dwf/fuel,dribnet/fuel,mjwillson/fuel,jbornschein/fuel,ejls/fuel,laurent-dinh/fuel,vdumoulin/fuel,dribnet/fuel,lamblin/fuel,capybaralet/fuel,codeaudit/fuel,EderSantana/fuel,udibr/fuel,lamblin/fuel | ---
+++
@@ -1,24 +1,50 @@
-import pickle
-from six.moves import range
+from numpy.testing import assert_raises, assert_equal
+from six.moves import range, cPickle
+from fuel.iterator import DataIterator
from fuel.utils import do_not_pickle_attributes
-@do_not_pickle_attributes("non_pickable", "bulky_attr")
-class TestClass(object):
+@do_not_pickle_attributes("non_picklable", "bulky_attr")
+class DummyClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
- self.non_pickable = lambda x: x
+ self.non_picklable = lambda x: x
-def test_do_not_pickle_attributes():
- cl = TestClass()
+class FaultyClass(object):
+ pass
- dump = pickle.dumps(cl)
- loaded = pickle.loads(dump)
- assert loaded.bulky_attr == list(range(100))
- assert loaded.non_pickable is not None
+@do_not_pickle_attributes("iterator")
+class UnpicklableClass(object):
+ def __init__(self):
+ self.load()
+
+ def load(self):
+ self.iterator = DataIterator(None)
+
+
+@do_not_pickle_attributes("attribute")
+class NonLoadingClass(object):
+ def load(self):
+ pass
+
+
+class TestDoNotPickleAttributes(object):
+ def test_load(self):
+ instance = cPickle.loads(cPickle.dumps(DummyClass()))
+ assert_equal(instance.bulky_attr, list(range(100)))
+ assert instance.non_picklable is not None
+
+ def test_value_error_no_load_method(self):
+ assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass)
+
+ def test_value_error_iterator(self):
+ assert_raises(ValueError, cPickle.dumps, UnpicklableClass())
+
+ def test_value_error_attribute_non_loaded(self):
+ assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute') |
527d460289cb574528f70a2a6c530e86627eb81a | framework/archiver/listeners.py | framework/archiver/listeners.py | from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyError
from website.project import signals as project_signals
@project_signals.after_create_registration.connect
def archive_node(src, dst, user):
"""Blinker listener for registration initiations. Enqueqes an archive task
:param src: Node being registered
:param dst: registration Node
:param user: registration initiator
"""
link_archive_provider(dst, user)
enqueue_task(archive.si(src._id, dst._id, user._id))
@project_signals.archive_callback.connect
def archive_callback(dst):
"""Blinker listener for updates to the archive task. When no tasks are
pending, either fail the registration or send a success email
:param dst: registration Node
"""
if not dst.archiving:
return
pending = {key: value for key, value in dst.archived_providers.iteritems() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)}
if not len(pending):
dst.archiving = False
dst.save()
if ARCHIVER_FAILURE in [value['status'] for value in dst.archived_providers.values()]:
raise ArchiverCopyError(dst.registered_from, dst, dst.creator, dst.archived_providers)
else:
send_success_message.delay(dst._id)
| from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyError
from website.project import signals as project_signals
@project_signals.after_create_registration.connect
def archive_node(src, dst, user):
"""Blinker listener for registration initiations. Enqueqes an archive task
:param src: Node being registered
:param dst: registration Node
:param user: registration initiator
"""
link_archive_provider(dst, user)
enqueue_task(archive.si(src._id, dst._id, user._id))
@project_signals.archive_callback.connect
def archive_callback(dst):
"""Blinker listener for updates to the archive task. When no tasks are
pending, either fail the registration or send a success email
:param dst: registration Node
"""
if not dst.archiving:
return
pending = [value for value in dst.archived_providers.values() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)]
if not pending:
dst.archiving = False
dst.save()
if ARCHIVER_FAILURE in [value['status'] for value in dst.archived_providers.values()]:
raise ArchiverCopyError(dst.registered_from, dst, dst.creator, dst.archived_providers)
else:
send_success_message.delay(dst._id)
| Use list comp instead of unnecessary dict comp | Use list comp instead of unnecessary dict comp
| Python | apache-2.0 | pattisdr/osf.io,ticklemepierce/osf.io,billyhunt/osf.io,wearpants/osf.io,mluo613/osf.io,ckc6cz/osf.io,doublebits/osf.io,aaxelb/osf.io,chrisseto/osf.io,amyshi188/osf.io,abought/osf.io,DanielSBrown/osf.io,adlius/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,kwierman/osf.io,amyshi188/osf.io,reinaH/osf.io,petermalcolm/osf.io,caseyrygt/osf.io,dplorimer/osf,hmoco/osf.io,chennan47/osf.io,brianjgeiger/osf.io,arpitar/osf.io,brianjgeiger/osf.io,jnayak1/osf.io,petermalcolm/osf.io,samchrisinger/osf.io,ckc6cz/osf.io,leb2dg/osf.io,mluo613/osf.io,acshi/osf.io,MerlinZhang/osf.io,jmcarp/osf.io,mluke93/osf.io,emetsger/osf.io,KAsante95/osf.io,acshi/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,KAsante95/osf.io,mluo613/osf.io,RomanZWang/osf.io,bdyetton/prettychart,hmoco/osf.io,acshi/osf.io,sloria/osf.io,TomBaxter/osf.io,jnayak1/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,Nesiehr/osf.io,mluo613/osf.io,cwisecarver/osf.io,alexschiller/osf.io,felliott/osf.io,kch8qx/osf.io,adlius/osf.io,DanielSBrown/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,jinluyuan/osf.io,dplorimer/osf,ticklemepierce/osf.io,zamattiac/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,samchrisinger/osf.io,asanfilippo7/osf.io,chennan47/osf.io,jolene-esposito/osf.io,asanfilippo7/osf.io,mluke93/osf.io,chrisseto/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,icereval/osf.io,zachjanicki/osf.io,asanfilippo7/osf.io,MerlinZhang/osf.io,rdhyee/osf.io,KAsante95/osf.io,alexschiller/osf.io,zachjanicki/osf.io,samanehsan/osf.io,jmcarp/osf.io,dplorimer/osf,HarryRybacki/osf.io,fabianvf/osf.io,danielneis/osf.io,jmcarp/osf.io,Ghalko/osf.io,caseyrygt/osf.io,samanehsan/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,wearpants/osf.io,Ghalko/osf.io,Johnetordoff/osf.io,ZobairAlijan/osf.io,reinaH/osf.io,cldershem/osf.io,caneruguz/osf.io,emetsger/osf.io,icereval/osf.io,KAsante95/osf.io,danielneis/osf.io,wearpants/osf.io,fabianvf/osf.io,petermalcolm/osf.io,saradbowman/osf.io,mluke93/osf.io,sbt9uc/osf.io,njantrania/osf.io,amyshi188/osf.io,Ghalko/osf.io,emetsger/osf.io,rdhyee/osf.io,mattclark/osf.io,kch8qx/osf.io,baylee-d/osf.io,arpitar/osf.io,cslzchen/osf.io,binoculars/osf.io,emetsger/osf.io,cosenal/osf.io,erinspace/osf.io,alexschiller/osf.io,acshi/osf.io,lyndsysimon/osf.io,sloria/osf.io,caseyrygt/osf.io,binoculars/osf.io,TomHeatwole/osf.io,brianjgeiger/osf.io,HarryRybacki/osf.io,SSJohns/osf.io,amyshi188/osf.io,jinluyuan/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,erinspace/osf.io,bdyetton/prettychart,acshi/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,KAsante95/osf.io,SSJohns/osf.io,jeffreyliu3230/osf.io,brandonPurvis/osf.io,danielneis/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,lyndsysimon/osf.io,zamattiac/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,bdyetton/prettychart,jnayak1/osf.io,dplorimer/osf,rdhyee/osf.io,jolene-esposito/osf.io,TomBaxter/osf.io,GageGaskins/osf.io,abought/osf.io,cwisecarver/osf.io,cslzchen/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,samchrisinger/osf.io,alexschiller/osf.io,jeffreyliu3230/osf.io,pattisdr/osf.io,saradbowman/osf.io,adlius/osf.io,cosenal/osf.io,samanehsan/osf.io,lyndsysimon/osf.io,chrisseto/osf.io,cosenal/osf.io,Nesiehr/osf.io,Ghalko/osf.io,RomanZWang/osf.io,crcresearch/osf.io,adlius/osf.io,njantrania/osf.io,DanielSBrown/osf.io,MerlinZhang/osf.io,danielneis/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,reinaH/osf.io,mfraezz/osf.io,mluo613/osf.io,billyhunt/osf.io,icereval/osf.io,wearpants/osf.io,bdyetton/prettychart,monikagrabowska/osf.io,binoculars/osf.io,chrisseto/osf.io,mattclark/osf.io,chennan47/osf.io,rdhyee/osf.io,caneruguz/osf.io,aaxelb/osf.io,GageGaskins/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,erinspace/osf.io,leb2dg/osf.io,ZobairAlijan/osf.io,CenterForOpenScience/osf.io,jeffreyliu3230/osf.io,doublebits/osf.io,reinaH/osf.io,fabianvf/osf.io,ZobairAlijan/osf.io,cslzchen/osf.io,doublebits/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,jinluyuan/osf.io,DanielSBrown/osf.io,doublebits/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,kch8qx/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,njantrania/osf.io,zachjanicki/osf.io,billyhunt/osf.io,haoyuchen1992/osf.io,jolene-esposito/osf.io,cosenal/osf.io,cwisecarver/osf.io,abought/osf.io,MerlinZhang/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,mluke93/osf.io,ticklemepierce/osf.io,TomBaxter/osf.io,jinluyuan/osf.io,brandonPurvis/osf.io,jeffreyliu3230/osf.io,haoyuchen1992/osf.io,ckc6cz/osf.io,cldershem/osf.io,brandonPurvis/osf.io,fabianvf/osf.io,laurenrevere/osf.io,HarryRybacki/osf.io,caneruguz/osf.io,felliott/osf.io,crcresearch/osf.io,sbt9uc/osf.io,baylee-d/osf.io,hmoco/osf.io,njantrania/osf.io,crcresearch/osf.io,aaxelb/osf.io,sloria/osf.io,SSJohns/osf.io,kwierman/osf.io,arpitar/osf.io,ckc6cz/osf.io,billyhunt/osf.io,doublebits/osf.io,cldershem/osf.io,caseyrygt/osf.io,haoyuchen1992/osf.io,arpitar/osf.io,lyndsysimon/osf.io,felliott/osf.io,asanfilippo7/osf.io,zamattiac/osf.io,abought/osf.io,sbt9uc/osf.io,jmcarp/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,HarryRybacki/osf.io,caneruguz/osf.io,samchrisinger/osf.io,baylee-d/osf.io,felliott/osf.io,cldershem/osf.io,mattclark/osf.io,kwierman/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,billyhunt/osf.io,leb2dg/osf.io,samanehsan/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,kch8qx/osf.io,aaxelb/osf.io,RomanZWang/osf.io | ---
+++
@@ -31,8 +31,8 @@
"""
if not dst.archiving:
return
- pending = {key: value for key, value in dst.archived_providers.iteritems() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)}
- if not len(pending):
+ pending = [value for value in dst.archived_providers.values() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)]
+ if not pending:
dst.archiving = False
dst.save()
if ARCHIVER_FAILURE in [value['status'] for value in dst.archived_providers.values()]: |
8a80e33c80732fc03ba2293e1b1219407c3c634c | frameworks/Perl/dancer/setup.py | frameworks/Perl/dancer/setup.py | import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks", "server unix:" + args.fwroot)
try:
subprocess.Popen("plackup -E production -s Starman --workers=" + str(args.max_threads) + " -l $TROOT/frameworks-benchmark.sock -a ./app.pl", shell=True, cwd="dancer", stderr=errfile, stdout=logfile)
subprocess.check_call("sudo /usr/local/nginx/sbin/nginx -c $TROOT/nginx.conf", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
subprocess.call("sudo /usr/local/nginx/sbin/nginx -s stop", shell=True)
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'starman' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 15)
return 0
except subprocess.CalledProcessError:
return 1
| import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks/dancer", "server unix:" + args.troot)
try:
subprocess.Popen("plackup -E production -s Starman --workers=" + str(args.max_threads) + " -l $TROOT/frameworks-benchmark.sock -a ./app.pl", shell=True, cwd="dancer", stderr=errfile, stdout=logfile)
subprocess.check_call("sudo /usr/local/nginx/sbin/nginx -c $TROOT/nginx.conf", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
subprocess.call("sudo /usr/local/nginx/sbin/nginx -s stop", shell=True)
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'starman' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 15)
return 0
except subprocess.CalledProcessError:
return 1
| Update dancer's nginx.conf to find new test root | Update dancer's nginx.conf to find new test root
| Python | bsd-3-clause | joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,testn/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,valyala/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,methane/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zapov/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,grob/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,herloct/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sxend/FrameworkBenchmarks,torhve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sxend/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sgml/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,actframework/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,methane/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,torhve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,joshk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sxend/FrameworkBenchmarks,methane/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Verber/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,doom369/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,testn/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,khellang/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,methane/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zapov/FrameworkBenchmarks,methane/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,testn/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sxend/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,joshk/FrameworkBenchmarks,grob/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sgml/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,khellang/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,herloct/FrameworkBenchmarks,herloct/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,herloct/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zloster/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,denkab/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zloster/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,doom369/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,methane/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,denkab/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,torhve/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,herloct/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sgml/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sgml/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,herloct/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,valyala/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,actframework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zloster/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sgml/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sxend/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,actframework/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,testn/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,torhve/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jamming/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,grob/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zloster/FrameworkBenchmarks,grob/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,denkab/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,herloct/FrameworkBenchmarks,testn/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,joshk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sxend/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zloster/FrameworkBenchmarks,testn/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jamming/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zapov/FrameworkBenchmarks,valyala/FrameworkBenchmarks,herloct/FrameworkBenchmarks,doom369/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,valyala/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,testn/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zapov/FrameworkBenchmarks,testn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sgml/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,herloct/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,grob/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,doom369/FrameworkBenchmarks,doom369/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,testn/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sgml/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,testn/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zapov/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,torhve/FrameworkBenchmarks,valyala/FrameworkBenchmarks,khellang/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,joshk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,actframework/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,grob/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,khellang/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,doom369/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,khellang/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,khellang/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,grob/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sxend/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,testn/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Verber/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,grob/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,testn/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,actframework/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,grob/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,grob/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,sxend/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sgml/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,torhve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,herloct/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Verber/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zapov/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,actframework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,valyala/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,actframework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,joshk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,methane/FrameworkBenchmarks,zloster/FrameworkBenchmarks,joshk/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Verber/FrameworkBenchmarks,methane/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,herloct/FrameworkBenchmarks,doom369/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,methane/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,doom369/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,denkab/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zloster/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,khellang/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,denkab/FrameworkBenchmarks,testn/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,khellang/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,denkab/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,grob/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,actframework/FrameworkBenchmarks,torhve/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jamming/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,actframework/FrameworkBenchmarks,denkab/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,grob/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zapov/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,methane/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,doom369/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zapov/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,khellang/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jamming/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,actframework/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zapov/FrameworkBenchmarks,methane/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,grob/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,testn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,herloct/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Verber/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Verber/FrameworkBenchmarks,denkab/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,grob/FrameworkBenchmarks | ---
+++
@@ -8,7 +8,7 @@
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
- setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks", "server unix:" + args.fwroot)
+ setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks/dancer", "server unix:" + args.troot)
try:
subprocess.Popen("plackup -E production -s Starman --workers=" + str(args.max_threads) + " -l $TROOT/frameworks-benchmark.sock -a ./app.pl", shell=True, cwd="dancer", stderr=errfile, stdout=logfile) |
7932f3b5c3be34a37c82b1b6f08db63dc2f0eee7 | lib/rapidsms/webui/urls.py | lib/rapidsms/webui/urls.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
urlpatterns = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
# iterate each of the active rapidsms apps (from the ini),
# and (attempt to) import the urls.py from each. it's okay
# if this fails, since not all apps have a webui
for rs_app in conf["rapidsms"]["apps"]:
try:
package_name = "apps.%s.urls" % (rs_app["type"])
module = __import__(package_name, {}, {}, ["urlpatterns"])
urlpatterns += module.urlpatterns
except Exception, e:
continue
| #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os, sys
urlpatterns = []
loaded = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
# iterate each of the active rapidsms apps (from the ini),
# and (attempt to) import the urls.py from each. it's okay
# if this fails, since not all apps have a webui
for rs_app in conf["rapidsms"]["apps"]:
try:
package_name = "apps.%s.urls" % (rs_app["type"])
module = __import__(package_name, {}, {}, ["urlpatterns"])
urlpatterns += module.urlpatterns
loaded += [rs_app["type"]]
except Exception, e:
continue
print >>sys.stderr, "Loaded url patterns from %s" % ", ".join(loaded)
| Print a list of which URLs got loaded. This doesn't help that much when trying to debug errors that keep URLs from getting loaded. But it's a start. | Print a list of which URLs got loaded. This doesn't help that much when
trying to debug errors that keep URLs from getting loaded. But it's a
start.
| Python | bsd-3-clause | dimagi/rapidsms-core-dev,eHealthAfrica/rapidsms,unicefuganda/edtrac,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,unicefuganda/edtrac,ken-muturi/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,caktus/rapidsms,dimagi/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev,peterayeni/rapidsms,eHealthAfrica/rapidsms,peterayeni/rapidsms,rapidsms/rapidsms-core-dev,dimagi/rapidsms,caktus/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,ken-muturi/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,ken-muturi/rapidsms,catalpainternational/rapidsms,caktus/rapidsms,unicefuganda/edtrac,catalpainternational/rapidsms,peterayeni/rapidsms | ---
+++
@@ -1,16 +1,14 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
-import os
-
+import os, sys
urlpatterns = []
-
+loaded = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
-
# iterate each of the active rapidsms apps (from the ini),
# and (attempt to) import the urls.py from each. it's okay
@@ -21,6 +19,8 @@
package_name = "apps.%s.urls" % (rs_app["type"])
module = __import__(package_name, {}, {}, ["urlpatterns"])
urlpatterns += module.urlpatterns
+ loaded += [rs_app["type"]]
except Exception, e:
continue
+print >>sys.stderr, "Loaded url patterns from %s" % ", ".join(loaded) |
1e082f8c39dd1a1d41064f522db10478b0c820e1 | icekit/page_types/layout_page/page_type_plugins.py | icekit/page_types/layout_page/page_type_plugins.py | from django.conf.urls import patterns, url
from fluent_pages.extensions import page_type_pool
from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin
from fluent_pages.models import UrlNode
from . import admin, models
# Register this plugin to the page plugin pool.
@page_type_pool.register
class LayoutPagePlugin(FluentContentsPagePlugin):
model = models.LayoutPage
model_admin = admin.LayoutPageAdmin
| from django.conf.urls import patterns, url
from fluent_pages.extensions import page_type_pool
from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin
from fluent_pages.models import UrlNode
from . import admin, models
# Register this plugin to the page plugin pool.
@page_type_pool.register
class LayoutPagePlugin(FluentContentsPagePlugin):
model = models.LayoutPage
model_admin = admin.LayoutPageAdmin
def get_render_template(self, request, fluentpage, **kwargs):
# Allow subclasses to easily override it by specifying `render_template` after all.
# The default, is to use the template_path from the layout object.
return self.render_template or fluentpage.layout.template_name
| Add smart template render method to LayoutPage | Add smart template render method to LayoutPage
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -12,3 +12,8 @@
model = models.LayoutPage
model_admin = admin.LayoutPageAdmin
+ def get_render_template(self, request, fluentpage, **kwargs):
+ # Allow subclasses to easily override it by specifying `render_template` after all.
+ # The default, is to use the template_path from the layout object.
+ return self.render_template or fluentpage.layout.template_name
+ |
95b6035b82ffeee73bbde953e5d036c50fa4fa8c | unit_tests/test_analyse_idynomics.py | unit_tests/test_analyse_idynomics.py | from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
self.analysis = AnalyseiDynomics(self.directory)
def test_init(self):
assert_is(self.directory, self.analysis.directory)
def test_solute_names(self):
actual_solutes = self.analysis.solute_names
assert_list_equal(self.expected_solutes, actual_solutes)
def test_species_names(self):
actual_species = self.analysis.species_names
assert_list_equal(self.expected_species, actual_species)
| from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
expected_timesteps = 2
expected_dimensions = (20.0, 20.0, 2.0)
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
self.analysis = AnalyseiDynomics(self.directory)
def test_init(self):
assert_is(self.directory, self.analysis.directory)
def test_solute_names(self):
actual_solutes = self.analysis.solute_names
assert_list_equal(self.expected_solutes, actual_solutes)
def test_species_names(self):
actual_species = self.analysis.species_names
assert_list_equal(self.expected_species, actual_species)
def test_total_timesteps(self):
actual_timesteps = self.analysis.total_timesteps
assert_equals(self.expected_timesteps, actual_timesteps)
def test_world_dimensions(self):
actual_dimensions = self.analysis.world_dimensions
assert_equal(self.expected_dimensions, actual_dimensions)
| Add unit tests for timesteps and dimensions | Add unit tests for timesteps and dimensions
| Python | mit | fophillips/pyDynoMiCS | ---
+++
@@ -5,6 +5,8 @@
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
+ expected_timesteps = 2
+ expected_dimensions = (20.0, 20.0, 2.0)
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
@@ -20,3 +22,11 @@
def test_species_names(self):
actual_species = self.analysis.species_names
assert_list_equal(self.expected_species, actual_species)
+
+ def test_total_timesteps(self):
+ actual_timesteps = self.analysis.total_timesteps
+ assert_equals(self.expected_timesteps, actual_timesteps)
+
+ def test_world_dimensions(self):
+ actual_dimensions = self.analysis.world_dimensions
+ assert_equal(self.expected_dimensions, actual_dimensions) |
d5a00553101dd3d431dd79494b9b57cfa56cb4be | worker.py | worker.py | import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
q = Queue(name=queue_name, connection=Redis())
def enqueue(*args, **kwargs):
q.enqueue(*args, **kwargs)
| import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
# `srm` can take a long time on large files, so allow it run for up to an hour
q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enqueue(*args, **kwargs):
q.enqueue(*args, **kwargs)
| Increase job timeout for securely deleting files | Increase job timeout for securely deleting files
| Python | agpl-3.0 | mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code | ---
+++
@@ -5,7 +5,8 @@
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
-q = Queue(name=queue_name, connection=Redis())
+# `srm` can take a long time on large files, so allow it run for up to an hour
+q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enqueue(*args, **kwargs):
q.enqueue(*args, **kwargs) |
d32e1d8349c115027e3095d61f8fa882fca1ab52 | functions/test_lambda.py | functions/test_lambda.py | """ Explore how python works with lambda expressions. """
import unittest
import string
import random
class TestGetWebsites(unittest.TestCase):
def test_closure(self, m):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
return ''.join([random.choice(string.ascii_letters) for i in range(20)])
value1 = gibberish()
value2 = gibberish()
result = (lambda x: lambda y: x)(value1)(value2)
self.assertEqual(result, value1)
if __name__ == "__main__":
unittest.main() | """ Explore how python works with lambda expressions. """
import unittest
import string
import random
class TestGetWebsites(unittest.TestCase):
def test_closure(self):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
return ''.join([random.choice(string.ascii_letters) for i in range(20)])
value1 = gibberish()
result = (lambda x: lambda: x)(value1)()
self.assertEqual(result, value1)
def test_closure_ids(self):
""" Show how a variable passed to a function remains in scope
even after it returns """
def make_lambdas(num):
""" Build a lambda generator """
for i in range(num):
func = lambda x: lambda: x
yield func(i)
functions = list(make_lambdas(random.randint(1, 10)))
random_index = random.randint(0, len(functions)-1)
random_function = functions[random_index]()
print("{0} equals {1}".format(random_index, random_function))
self.assertEqual(random_function, random_index)
if __name__ == "__main__":
unittest.main() | Add a test to generate a range of functions with closures. Check if it returns the expected value | Add a test to generate a range of functions with closures. Check if it returns the expected value
| Python | mit | b-ritter/python-notes,b-ritter/python-notes | ---
+++
@@ -5,15 +5,28 @@
class TestGetWebsites(unittest.TestCase):
- def test_closure(self, m):
+ def test_closure(self):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
return ''.join([random.choice(string.ascii_letters) for i in range(20)])
value1 = gibberish()
- value2 = gibberish()
- result = (lambda x: lambda y: x)(value1)(value2)
+ result = (lambda x: lambda: x)(value1)()
self.assertEqual(result, value1)
+
+ def test_closure_ids(self):
+ """ Show how a variable passed to a function remains in scope
+ even after it returns """
+ def make_lambdas(num):
+ """ Build a lambda generator """
+ for i in range(num):
+ func = lambda x: lambda: x
+ yield func(i)
+ functions = list(make_lambdas(random.randint(1, 10)))
+ random_index = random.randint(0, len(functions)-1)
+ random_function = functions[random_index]()
+ print("{0} equals {1}".format(random_index, random_function))
+ self.assertEqual(random_function, random_index)
if __name__ == "__main__":
unittest.main() |
670a5ffe8de9f21fbb2fe65e72e006d143bfa8e3 | pirx/utils.py | pirx/utils.py | import os
def path(*p):
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p)
| import os
def path(*p):
"""Return full path of a directory inside project's root"""
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p)
| Set docstring for "path" function | Set docstring for "path" function
| Python | mit | piotrekw/pirx | ---
+++
@@ -2,6 +2,7 @@
def path(*p):
+ """Return full path of a directory inside project's root"""
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p) |
d0b0a89a7149c5853e0e827fa819deb17699bf55 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.9.3"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.9.4"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.9.4 | Increment version number to 0.9.4
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.9.3"
+__version__ = "0.9.4"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
384f7a8da21ca5e4ffa529e0e5f9407ce2ec0142 | backend/unichat/models/user.py | backend/unichat/models/user.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
password = models.CharField(
max_length=100,
help_text=("The user's password.")
)
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
cookie = models.CharField(
default='',
max_length=100,
db_index=True,
help_text=("The user's active cookie.")
)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
help_text=("The user's academic email.")
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
date_joined = models.DateTimeField(
auto_now_add=True,
help_text=("The date the user joined")
)
is_active = models.BooleanField(
default=True,
help_text=("The user active state")
)
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unichat.School')
gender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The user's gender, by default UNDEFINED, unless otherwise "
"explicitly specified by the user.")
)
interestedInGender = models.IntegerField(
default=0,
choices=GENDER_CHOICES,
help_text=("The gender that the user is interested in talking to, by "
"default UNDEFINED.")
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
| Change User to use Django's AbstractBaseUser | Change User to use Django's AbstractBaseUser
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | ---
+++
@@ -1,9 +1,36 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
+from django.contrib.auth.models import PermissionsMixin
+from django.contrib.auth.base_user import AbstractBaseUser
+from .managers import UserManager
-class User(models.Model):
+class User(AbstractBaseUser, PermissionsMixin):
+ email = models.EmailField(
+ unique=True,
+ help_text=("The user's academic email.")
+ )
+
+ objects = UserManager()
+
+ USERNAME_FIELD = 'email'
+ REQUIRED_FIELDS = []
+
+ class Meta:
+ verbose_name = 'user'
+ verbose_name_plural = 'users'
+
+ date_joined = models.DateTimeField(
+ auto_now_add=True,
+ help_text=("The date the user joined")
+ )
+
+ is_active = models.BooleanField(
+ default=True,
+ help_text=("The user active state")
+ )
+
MALE = -1
UNDEFINED = 0
FEMALE = 1
@@ -14,16 +41,6 @@
)
school = models.ForeignKey('unichat.School')
-
- email = models.EmailField(
- unique=True,
- help_text=("The user's academic email.")
- )
-
- password = models.CharField(
- max_length=100,
- help_text=("The user's password.")
- )
gender = models.IntegerField(
default=0,
@@ -40,10 +57,3 @@
)
interestedInSchools = models.ManyToManyField('unichat.School', related_name='user_interested_schools')
-
- cookie = models.CharField(
- default='',
- max_length=100,
- db_index=True,
- help_text=("The user's active cookie.")
- ) |
b59d1dd5afd63422cd478d8ee519347bd1c43e3b | project/urls.py | project/urls.py | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url, include
from django.conf import settings
from django.views.generic.base import RedirectView
from revproxy.views import ProxyView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include('api.urls', namespace='api')),
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^accounts/', include('allauth.urls')),
url(r'^(?P<path>app/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)),
url(r'^$', RedirectView.as_view(url='app/discover')),
]
| """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url, include
from django.conf import settings
from django.views.generic.base import RedirectView
from revproxy.views import ProxyView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include('api.urls', namespace='api')),
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^accounts/', include('allauth.urls')),
url(r'^(?P<path>share/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)),
url(r'^$', RedirectView.as_view(url='share/')),
]
| Change ember app prefix to 'share/' | Change ember app prefix to 'share/'
| Python | apache-2.0 | CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE | ---
+++
@@ -26,6 +26,6 @@
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^accounts/', include('allauth.urls')),
- url(r'^(?P<path>app/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)),
- url(r'^$', RedirectView.as_view(url='app/discover')),
+ url(r'^(?P<path>share/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)),
+ url(r'^$', RedirectView.as_view(url='share/')),
] |
048f2d9469b3f9eb266a343602ddf608e3bd6d86 | highton/models/email_address.py | highton/models/email_address.py | from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION)
self.address = fields.StringField(name=HightonConstants.ADDRESS)
super().__init__(**kwargs)
| from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar address: fields.StringField(name=HightonConstants.ADDRESS)
"""
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs)
| Set EmailAddress Things to required | Set EmailAddress Things to required
| Python | apache-2.0 | seibert-media/Highton,seibert-media/Highton | ---
+++
@@ -14,7 +14,7 @@
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
- self.location = fields.StringField(name=HightonConstants.LOCATION)
- self.address = fields.StringField(name=HightonConstants.ADDRESS)
+ self.location = fields.StringField(name=HightonConstants.LOCATION, required=True)
+ self.address = fields.StringField(name=HightonConstants.ADDRESS, required=True)
super().__init__(**kwargs) |
a651e748164865a8ca658085819c1d978338824c | angular_flask/__init__.py | angular_flask/__init__.py | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = '/home/alex/dev/blog/angular_flask/static/img'
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
| import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img')
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
| Fix path for saving imgs | Fix path for saving imgs
| Python | mit | Clarity-89/blog,Clarity-89/blog,Clarity-89/blog | ---
+++
@@ -5,12 +5,12 @@
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
-
+basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
-app.config['UPLOAD_FOLDER'] = '/home/alex/dev/blog/angular_flask/static/img'
+app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img')
import angular_flask.core
import angular_flask.models |
01847c64869298a436980eb17c549d49f09d6a91 | src/nodeconductor_openstack/openstack_tenant/perms.py | src/nodeconductor_openstack/openstack_tenant/perms.py | from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic),
)
| from nodeconductor.core.permissions import StaffPermissionLogic
from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic),
('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)),
)
| Add permissions to service properties | Add permissions to service properties
- wal-94
| Python | mit | opennode/nodeconductor-openstack | ---
+++
@@ -1,7 +1,12 @@
+from nodeconductor.core.permissions import StaffPermissionLogic
from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic),
+ ('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)),
+ ('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)),
+ ('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)),
+ ('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)),
) |
95d80b076d374ab8552e292014f9fbed08e7b6e1 | ibmcnx/menu/MenuClass.py | ibmcnx/menu/MenuClass.py | ######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
# Function to add menuitems
def AddItem( self, text, function ):
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
def Show( menutitle, self ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n'
for self.l in self.menuitems:
print '\t',
print self.c, self.l['text']
self.c += 1
print
def Do( self, n ):
self.menuitems[n]["func"]()
| ######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
# Function to add menuitems
def AddItem( self, text, function ):
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
def Show( self, menutitle ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n'
for self.l in self.menuitems:
print '\t',
print self.c, self.l['text']
self.c += 1
print
def Do( self, n ):
self.menuitems[n]["func"]()
| Test all scripts on Windows | 10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -19,7 +19,7 @@
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
- def Show( menutitle, self ):
+ def Show( self, menutitle ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n' |
f463247198354b0af1d0b8a4ff63c0757d4c2839 | regression.py | regression.py | import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
| import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
| Exclude the testing module from coverage results. | Exclude the testing module from coverage results.
| Python | bsd-3-clause | cmorgan/toyplot,cmorgan/toyplot | ---
+++
@@ -1,6 +1,6 @@
import subprocess
-subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
-subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
+subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
+subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"]) |
c458b78ccecc28971ef239de5a5366bd56d2562e | web/portal/views/home.py | web/portal/views/home.py | from flask import redirect, url_for
from portal import app
@app.route('/', methods=['GET'])
def index():
return redirect(url_for('practices_index', _external=True))
| from flask import redirect, url_for
from portal import app
@app.route('/', methods=['GET'])
def index():
return redirect(url_for('practices_index', _external=True, _scheme="https"))
| Fix incorrect protocol being using when behin reverse proxy | Fix incorrect protocol being using when behin reverse proxy
| Python | mit | LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal | ---
+++
@@ -3,4 +3,4 @@
@app.route('/', methods=['GET'])
def index():
- return redirect(url_for('practices_index', _external=True))
+ return redirect(url_for('practices_index', _external=True, _scheme="https")) |
8f2cf9f30b5748117a6cc98d74aa0c8493f21852 | sft/agent/ah/RunningAvg.py | sft/agent/ah/RunningAvg.py | import theano
from sft import Size
from sft.Actions import Actions
from sft.agent.ah.ActionHistory import ActionHistory
import numpy as np
class RunningAvg(ActionHistory):
def __init__(self, logger, n, factor):
self.logger = logger
self.n = n
self.factor = factor
self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
def get_size(self):
return Size(self.n, self.ACTION_WIDTH)
def get_history(self, all_actions):
return self.actions
def new_action(self, a):
for i in range(1, self.n):
self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1]
self.actions[0, :] = Actions.get_one_hot(a)
self.logger.log_parameter("actions", str(self.actions))
def new_episode(self):
self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
| import theano
from sft import Size
from sft.Actions import Actions
from sft.agent.ah.ActionHistory import ActionHistory
import numpy as np
class RunningAvg(ActionHistory):
def __init__(self, logger, n, factor):
self.logger = logger
self.n = n
self.factor = factor
self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
def get_size(self):
return Size(self.n, self.ACTION_WIDTH)
def get_history(self, all_actions):
return self.actions
def new_action(self, a):
for i in range(1, self.n)[::-1]:
self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1]
self.actions[0, :] = Actions.get_one_hot(a)
self.logger.log_parameter("actions", str(self.actions))
def new_episode(self):
self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
| Fix running average action history | Fix running average action history
| Python | mit | kevinkepp/search-for-this | ---
+++
@@ -21,7 +21,7 @@
return self.actions
def new_action(self, a):
- for i in range(1, self.n):
+ for i in range(1, self.n)[::-1]:
self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1]
self.actions[0, :] = Actions.get_one_hot(a)
self.logger.log_parameter("actions", str(self.actions)) |
813ddc03b652d0594bc9cb540a5a5f50a196a073 | fjord/urls.py | fjord/urls.py | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus
admin.site = AdminSitePlus()
admin.autodiscover()
urlpatterns = patterns('',
(r'', include('fjord.analytics.urls')),
(r'', include('fjord.base.urls')),
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
(r'^robots\.txt$',
lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow',
mimetype="text/plain"
)
),
(r'^browserid/', include('django_browserid.urls')),
(r'^admin/', include(admin.site.urls)),
)
## In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
| from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus
admin.site = AdminSitePlus()
admin.autodiscover()
urlpatterns = patterns('',
(r'', include('fjord.analytics.urls')),
(r'', include('fjord.base.urls')),
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
# TODO: Remove this stub. /about and /search point to it.
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
(r'^robots\.txt$',
lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow',
mimetype="text/plain"
)
),
(r'^browserid/', include('django_browserid.urls')),
(r'^admin/', include(admin.site.urls)),
)
# In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
| Add TODO for removing stubs | Add TODO for removing stubs
| Python | bsd-3-clause | Ritsyy/fjord,mozilla/fjord,mozilla/fjord,mozilla/fjord,rlr/fjord,DESHRAJ/fjord,Ritsyy/fjord,staranjeet/fjord,Ritsyy/fjord,staranjeet/fjord,hoosteeno/fjord,rlr/fjord,mozilla/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,rlr/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,hoosteeno/fjord,staranjeet/fjord,staranjeet/fjord,Ritsyy/fjord,lgp171188/fjord,rlr/fjord,lgp171188/fjord | ---
+++
@@ -20,6 +20,7 @@
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
+ # TODO: Remove this stub. /about and /search point to it.
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
@@ -36,6 +37,6 @@
)
-## In DEBUG mode, serve media files through Django.
+# In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns() |
980a1a40aeb5f76bc8675890237f5624920b7602 | pinax/stripe/management/commands/init_customers.py | pinax/stripe/management/commands/init_customers.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
for user in User.objects.filter(customer__isnull=True):
customers.create(user=user)
self.stdout.write("Created customer for {0}\n".format(user.email))
| from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
for user in User.objects.filter(customer__isnull=True):
customers.create(user=user, charge_immediately=False)
self.stdout.write("Created customer for {0}\n".format(user.email))
| Make sure the customer has no plan nor is charged | Make sure the customer has no plan nor is charged
Stripe throws an error because we try to make a charge without having a card. Because we don't have a card for this user yet, it doesn't make sense to charge them immediately. | Python | mit | pinax/django-stripe-payments | ---
+++
@@ -11,5 +11,5 @@
def handle(self, *args, **options):
User = get_user_model()
for user in User.objects.filter(customer__isnull=True):
- customers.create(user=user)
+ customers.create(user=user, charge_immediately=False)
self.stdout.write("Created customer for {0}\n".format(user.email)) |
e8708c28e79a9063469e684b5583114c69ec425f | datadog_checks_dev/datadog_checks/dev/spec.py | datadog_checks_dev/datadog_checks/dev/spec.py | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
assets = manifest.get('assets', {})
if 'integration' in assets:
relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
else:
relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| Fix CI for logs E2E with v2 manifests | Fix CI for logs E2E with v2 manifests | Python | bsd-3-clause | DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core | ---
+++
@@ -15,7 +15,11 @@
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
- relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
+ assets = manifest.get('assets', {})
+ if 'integration' in assets:
+ relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
+ else:
+ relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
|
a41d2e79dcf83793dab5c37c4a4b46ad6225d719 | anchor/names.py | anchor/names.py | """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = '~0'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE = '~1'
# The density is split between 0 and 1
BOTH_ONE_ZERO = 'bimodal'
# Cannot decide on one of the above models (the null model fits better) so use
# this model instead
NULL_MODEL = 'ambivalent'
| """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = 'excluded'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE = 'included'
# The density is split between 0 and 1
BOTH_ONE_ZERO = 'bimodal'
# Cannot decide on one of the above models (the null model fits better) so use
# this model instead
NULL_MODEL = 'ambivalent'
| Use words for near zero and near one | Use words for near zero and near one
| Python | bsd-3-clause | YeoLab/anchor | ---
+++
@@ -6,13 +6,13 @@
# as variables rather than strings
# Most of the density is at 0
-NEAR_ZERO = '~0'
+NEAR_ZERO = 'excluded'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
-NEAR_ONE = '~1'
+NEAR_ONE = 'included'
# The density is split between 0 and 1
BOTH_ONE_ZERO = 'bimodal' |
1c14d45ba620118401728c56e5ef3a189f9b4145 | samples/fire.py | samples/fire.py | from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
effects = [
Print(screen,
Fire(screen.height, 80,
Figlet(font="banner", width=200).renderText("ASCIIMATICS"),
100),
0,
speed=1,
transparent=False),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9, x=3,
colour=Screen.COLOUR_BLACK,
speed=1),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9,
colour=Screen.COLOUR_WHITE,
speed=1),
]
scenes.append(Scene(effects, 600))
screen.play(scenes, stop_on_resize=True)
if __name__ == "__main__":
while True:
try:
Screen.wrapper(demo)
sys.exit(0)
except ResizeScreenError:
pass
| from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
text = Figlet(font="banner", width=200).renderText("ASCIIMATICS")
width = max([len(x) for x in text.split("\n")])
effects = [
Print(screen,
Fire(screen.height, 80, text, 100),
0,
speed=1,
transparent=False),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9, x=(screen.width - width) // 2 + 1,
colour=Screen.COLOUR_BLACK,
speed=1),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9,
colour=Screen.COLOUR_WHITE,
speed=1),
]
scenes.append(Scene(effects, 600))
screen.play(scenes, stop_on_resize=True)
if __name__ == "__main__":
while True:
try:
Screen.wrapper(demo)
sys.exit(0)
except ResizeScreenError:
pass
| Fix shadow for wide screens. | Fix shadow for wide screens.
| Python | apache-2.0 | peterbrittain/asciimatics,peterbrittain/asciimatics | ---
+++
@@ -10,17 +10,18 @@
def demo(screen):
scenes = []
+ text = Figlet(font="banner", width=200).renderText("ASCIIMATICS")
+ width = max([len(x) for x in text.split("\n")])
+
effects = [
Print(screen,
- Fire(screen.height, 80,
- Figlet(font="banner", width=200).renderText("ASCIIMATICS"),
- 100),
+ Fire(screen.height, 80, text, 100),
0,
speed=1,
transparent=False),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
- screen.height - 9, x=3,
+ screen.height - 9, x=(screen.width - width) // 2 + 1,
colour=Screen.COLOUR_BLACK,
speed=1),
Print(screen, |
f7a8c4a293538c4cd592ba23860b873cb378f28f | pyaxiom/netcdf/dataset.py | pyaxiom/netcdf/dataset.py | #!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.variables:
var = self.variables[vname]
for k, v in kwargs.iteritems():
if hasattr(var, k) and getattr(var, k) == v:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
vs.append(self.variables[vname])
return vs
| #!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.variables:
var = self.variables[vname]
for k, v in kwargs.iteritems():
if hasattr(var, k) and getattr(var, k) == v:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
vs.append(self.variables[vname])
return vs
def close(self):
try:
self.sync()
self.close()
except RuntimeError:
pass
| Add a close method to EnhancedDataset that won't raise a RuntimeError | Add a close method to EnhancedDataset that won't raise a RuntimeError
| Python | mit | axiom-data-science/pyaxiom,ocefpaf/pyaxiom,ocefpaf/pyaxiom,axiom-data-science/pyaxiom | ---
+++
@@ -24,3 +24,10 @@
vs.append(self.variables[vname])
return vs
+
+ def close(self):
+ try:
+ self.sync()
+ self.close()
+ except RuntimeError:
+ pass |
86968b5bc34a0c7f75ff04ad261ee59da8dcf94f | app/soc/models/host.py | app/soc/models/host.py | #!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the Host Model."""
__authors__ = [
'"Todd Larsen" <tlarsen@google.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
import soc.models.role
import soc.models.sponsor
class Host(soc.models.role.Role):
"""Host details for a specific Program.
"""
pass
| #!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the Model for Host."""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext import db
from django.utils.translation import ugettext
import soc.models.base
class Host(soc.models.base.ModelWithFieldAttributes):
"""Model containing host specific data.
The User entity corresponding to this host will be the parent of this entity.
"""
notify_slot_transfer = db.BooleanProperty(required=False, default=True,
verbose_name=ugettext('Notify of slot transfer updates'))
notify_slot_transfer.help_text = ugettext(
'Whether to send an email notification when slot transfer requests '
'are made or updated.')
notify_slot_transfer.group = ugettext("1. Notification settings")
| Replace the old Host model with a new one. | Replace the old Host model with a new one.
The new Host model doesn't need the host user to have a profile.
Instead it will contain the user to whom the Host entity belongs
to as the parent of the Host entity to maintain transactionality
between User and Host updates.
--HG--
extra : rebase_source : cee68153ab1cfdb77cc955f14ae8f7ef02d5157a
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -14,20 +14,29 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""This module contains the Host Model."""
+"""This module contains the Model for Host."""
__authors__ = [
- '"Todd Larsen" <tlarsen@google.com>',
- '"Sverre Rabbelier" <sverre@rabbelier.nl>',
+ '"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
-import soc.models.role
-import soc.models.sponsor
+from google.appengine.ext import db
+
+from django.utils.translation import ugettext
+
+import soc.models.base
-class Host(soc.models.role.Role):
- """Host details for a specific Program.
+class Host(soc.models.base.ModelWithFieldAttributes):
+ """Model containing host specific data.
+
+ The User entity corresponding to this host will be the parent of this entity.
"""
- pass
+ notify_slot_transfer = db.BooleanProperty(required=False, default=True,
+ verbose_name=ugettext('Notify of slot transfer updates'))
+ notify_slot_transfer.help_text = ugettext(
+ 'Whether to send an email notification when slot transfer requests '
+ 'are made or updated.')
+ notify_slot_transfer.group = ugettext("1. Notification settings") |
f023d6e112638c58ed1e0adc764263b64f50e15a | apps/documents/urls.py | apps/documents/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^chapters/(?P<pk>\d+)/$',
views.ChapterDetailView.as_view(),
name='chapter-detail'
),
url(
r'^paragraphs/(?P<pk>\d+)/$',
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
),
# url(r'^chapters/(?P<pk>\d+)/$'
url(
r'^manage/chapter/(?P<pk>\d+)/$',
views.ChapterManagementView.as_view(),
name='chapter-management'
),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^chapters/(?P<pk>\d+)/$',
views.ChapterDetailView.as_view(),
name='chapter-detail'
),
url(
r'^paragraphs/(?P<pk>\d+)/$',
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
),
url(
r'^manage/chapters/(?P<pk>\d+)/$',
views.ChapterManagementView.as_view(),
name='chapter-management'
),
]
| Unify url routes to plural | Unify url routes to plural
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -13,9 +13,8 @@
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
),
- # url(r'^chapters/(?P<pk>\d+)/$'
url(
- r'^manage/chapter/(?P<pk>\d+)/$',
+ r'^manage/chapters/(?P<pk>\d+)/$',
views.ChapterManagementView.as_view(),
name='chapter-management'
), |
17f3a2a491f8e4d1b1b6c2644a1642f02cfada17 | apps/i4p_base/views.py | apps/i4p_base/views.py | # -*- coding: utf-8 -*-
from django.http import QueryDict
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils import translation
from apps.project_sheet.models import I4pProject
from apps.project_sheet.utils import get_project_translations_from_parents, build_filters_and_context
def homepage(request):
"""
I4P Homepage
"""
project_sheets = I4pProject.objects.filter(best_of=True).order_by('?')[:14]
project_translations = get_project_translations_from_parents(project_sheets,
language_code=translation.get_language()
)
data = request.GET
if not data :
data = QueryDict('best_of=on')
context = {'project_sheets': project_sheets,
'project_translations': project_translations,
'about_tab_selected' : True}
filter_forms, extra_context = build_filters_and_context(data)
context.update(filter_forms)
context.update(extra_context)
return render_to_response(template_name='homepage.html',
dictionary=context,
context_instance=RequestContext(request)
)
| # -*- coding: utf-8 -*-
from django.http import QueryDict
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils import translation
from apps.project_sheet.models import I4pProject
from apps.project_sheet.utils import get_project_translations_from_parents, build_filters_and_context
def homepage(request):
"""
I4P Homepage
"""
project_sheets = I4pProject.objects.filter(best_of=True).order_by('?')[:14]
project_translations = get_project_translations_from_parents(project_sheets,
language_code=translation.get_language()
)
data = request.GET
context = {'project_sheets': project_sheets,
'project_translations': project_translations,
'about_tab_selected' : True}
filter_forms, extra_context = build_filters_and_context(data)
context.update(filter_forms)
context.update(extra_context)
return render_to_response(template_name='homepage.html',
dictionary=context,
context_instance=RequestContext(request)
)
| Remove pre-selection of best-on filter | Remove pre-selection of best-on filter
| Python | agpl-3.0 | ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople | ---
+++
@@ -17,8 +17,6 @@
language_code=translation.get_language()
)
data = request.GET
- if not data :
- data = QueryDict('best_of=on')
context = {'project_sheets': project_sheets,
'project_translations': project_translations, |
d7b3579edf9efb48fc80290fe0cf1c9c6db3b7bc | run-quince.py | run-quince.py | #!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import *
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--measFile', type=str, help='Measurement Library File')
parser.add_argument('-s', '--sweepFile', type=str, help='Sweep Library File')
parser.add_argument('-i', '--instrFile', type=str, help='Instrument Library File')
args = parser.parse_args()
print(args.instrFile)
app = QApplication([])
window = NodeWindow()
window.load_pyqlab(measFile=args.measFile, sweepFile=args.sweepFile, instrFile=args.instrFile)
app.aboutToQuit.connect(window.cleanup)
window.show()
sys.exit(app.exec_())
| #!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
# Use PyQt5 by default
import os
os.environ["QT_API"] = 'pyqt5'
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import *
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--measFile', type=str, help='Measurement Library File')
parser.add_argument('-s', '--sweepFile', type=str, help='Sweep Library File')
parser.add_argument('-i', '--instrFile', type=str, help='Instrument Library File')
args = parser.parse_args()
print(args.instrFile)
app = QApplication([])
window = NodeWindow()
window.load_pyqlab(measFile=args.measFile, sweepFile=args.sweepFile, instrFile=args.instrFile)
app.aboutToQuit.connect(window.cleanup)
window.show()
sys.exit(app.exec_())
| Set desired qt version explicitly in run_quince.py | Set desired qt version explicitly in run_quince.py
| Python | apache-2.0 | BBN-Q/Quince | ---
+++
@@ -4,6 +4,10 @@
# Contributiors: Graham Rowlands
#
# This file runs the main loop
+
+# Use PyQt5 by default
+import os
+os.environ["QT_API"] = 'pyqt5'
from qtpy.QtWidgets import QApplication
import sys |
3b5e66f8051043e8b6863fe1b3c9fc81a13fc38c | bash_kernel/install.py | bash_kernel/install.py | import json
import os
import sys
from IPython.kernel.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"],
"display_name":"Bash",
"language":"bash",
"codemirror_mode":"shell",
"env":{"PS1": "$"}
}
def install_my_kernel_spec(user=True):
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy resources once they're specified
print('Installing IPython kernel spec')
install_kernel_spec(td, 'bash', user=user, replace=True)
def _is_root():
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms
def main(argv=[]):
user = '--user' in argv or not _is_root()
install_my_kernel_spec(user=user)
if __name__ == '__main__':
main(argv=sys.argv)
| import json
import os
import sys
from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"],
"display_name":"Bash",
"language":"bash",
"codemirror_mode":"shell",
"env":{"PS1": "$"}
}
def install_my_kernel_spec(user=True):
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy resources once they're specified
print('Installing IPython kernel spec')
install_kernel_spec(td, 'bash', user=user, replace=True)
def _is_root():
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms
def main(argv=[]):
user = '--user' in argv or not _is_root()
install_my_kernel_spec(user=user)
if __name__ == '__main__':
main(argv=sys.argv)
| Remove warning from jupyter 4 | Remove warning from jupyter 4
| Python | bsd-3-clause | newtux/KdbQ_kernel | ---
+++
@@ -2,7 +2,7 @@
import os
import sys
-from IPython.kernel.kernelspec import install_kernel_spec
+from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"], |
4965511fdb9843233e84a8aa9aa0414bf1c02133 | mail/views.py | mail/views.py | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = request.POST.get("to_address", "").split(',')
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
csrf_token = request.POST.get("csrfmiddlewaretoken", "")
email = EmailMessage(subject,
message_body,
'noreply@openstax.org',
to_address,
reply_to=[from_string])
email.send(fail_silently=False)
#return redirect('/contact-thank-you')
data = {'subject': subject,
'message_body': message_body,
'to_address': to_address,
'reply_to': [from_string],
'from_address': 'noreply@openstax.org',
'csrf_token': csrf_token,
}
return JsonResponse(data)
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
| from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = request.POST.get("to_address", "").split(',')
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
email = EmailMessage(subject,
message_body,
'noreply@openstax.org',
to_address,
reply_to=[from_string])
email.send()
return redirect('/contact-thank-you')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
| Revert "return json of message being sent to debug mail issue" | Revert "return json of message being sent to debug mail issue"
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms | ---
+++
@@ -15,25 +15,15 @@
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
- csrf_token = request.POST.get("csrfmiddlewaretoken", "")
email = EmailMessage(subject,
message_body,
'noreply@openstax.org',
to_address,
reply_to=[from_string])
- email.send(fail_silently=False)
+ email.send()
- #return redirect('/contact-thank-you')
- data = {'subject': subject,
- 'message_body': message_body,
- 'to_address': to_address,
- 'reply_to': [from_string],
- 'from_address': 'noreply@openstax.org',
- 'csrf_token': csrf_token,
- }
-
- return JsonResponse(data)
+ return redirect('/contact-thank-you')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request) |
aa5ad938c96d1c6241015e182c7aefb835f13e45 | goodtablesio/utils/frontend.py | goodtablesio/utils/frontend.py | from flask import render_template
from flask_login import current_user
from goodtablesio import settings
# Module API
def render_component(component, props=None):
"""Render frontend component within html layout.
Args:
component (str): component name
props (dict): component props
Returns:
str: rendered component
"""
filename = 'index.min.html'
if settings.DEBUG:
filename = 'index.html'
if not props:
props = {}
# Common props
if props == {} or (props and 'userName' not in props):
user_name = getattr(current_user, 'display_name',
getattr(current_user, 'name', None))
props['userName'] = user_name
return render_template(
filename, component=component, props=props.copy(),
google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
| from flask import render_template
from flask_login import current_user
from goodtablesio import settings
# Module API
def render_component(component, props=None):
"""Render frontend component within html layout.
Args:
component (str): component name
props (dict): component props
Returns:
str: rendered component
"""
filename = 'index.min.html'
if settings.DEBUG:
filename = 'index.html'
if not props:
props = {}
# Common props
if props == {} or (props and 'userName' not in props):
user_name = getattr(current_user, 'display_name')
if not user_name:
user_name = getattr(current_user, 'name')
props['userName'] = user_name
return render_template(
filename, component=component, props=props.copy(),
google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
| Fix user name addition to props | Fix user name addition to props
| Python | agpl-3.0 | frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io | ---
+++
@@ -26,10 +26,10 @@
# Common props
if props == {} or (props and 'userName' not in props):
- user_name = getattr(current_user, 'display_name',
- getattr(current_user, 'name', None))
+ user_name = getattr(current_user, 'display_name')
+ if not user_name:
+ user_name = getattr(current_user, 'name')
props['userName'] = user_name
-
return render_template(
filename, component=component, props=props.copy(),
google_analytics_code=settings.GOOGLE_ANALYTICS_CODE) |
d6c228468ad519f735a12388383b719ee9830f5e | reviewboard/notifications/evolutions/webhooktarget_extra_state.py | reviewboard/notifications/evolutions/webhooktarget_extra_state.py | from django_evolution.mutations import AddField, RenameField
from django.db import models
from djblets.db.fields import JSONField
MUTATIONS = [
AddField('WebHookTarget', 'encoding', models.CharField,
initial='application/json', max_length=40),
AddField('WebHookTarget', 'repositories', models.ManyToManyField,
null=True, related_model='scmtools.Repository'),
AddField('WebHookTarget', 'custom_content', models.TextField, null=True),
AddField('WebHookTarget', 'use_custom_content', models.BooleanField,
initial=False),
AddField('WebHookTarget', 'apply_to', models.CharField, initial='A',
max_length=1),
AddField('WebHookTarget', 'extra_data', JSONField, initial='{}'),
RenameField('WebHookTarget', 'handlers', 'events'),
]
| from django_evolution.mutations import AddField, RenameField
from django.db import models
from djblets.db.fields import JSONField
MUTATIONS = [
AddField('WebHookTarget', 'encoding', models.CharField,
initial='application/json', max_length=40),
AddField('WebHookTarget', 'repositories', models.ManyToManyField,
null=True, related_model='scmtools.Repository'),
AddField('WebHookTarget', 'custom_content', models.TextField, null=True),
AddField('WebHookTarget', 'use_custom_content', models.BooleanField,
initial=False),
AddField('WebHookTarget', 'apply_to', models.CharField, initial='A',
max_length=1),
AddField('WebHookTarget', 'extra_data', JSONField, initial=None),
RenameField('WebHookTarget', 'handlers', 'events'),
]
| Remove the initial value for WebHookTarget.extra_data in the evolution. | Remove the initial value for WebHookTarget.extra_data in the evolution.
The original evolution adding the WebHookTarget.extra_data had an
initial value, and even with changing that in another field, it will
still apply on existing installs. This needs to be modified in order to
allow installation on MySQL.
| Python | mit | reviewboard/reviewboard,beol/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,custode/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,davidt/reviewboard,beol/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,davidt/reviewboard,chipx86/reviewboard,beol/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie/reviewboard,KnowNo/reviewboard,beol/reviewboard,chipx86/reviewboard,brennie/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,chipx86/reviewboard,sgallagher/reviewboard,brennie/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,brennie/reviewboard,reviewboard/reviewboard,custode/reviewboard,KnowNo/reviewboard | ---
+++
@@ -13,6 +13,6 @@
initial=False),
AddField('WebHookTarget', 'apply_to', models.CharField, initial='A',
max_length=1),
- AddField('WebHookTarget', 'extra_data', JSONField, initial='{}'),
+ AddField('WebHookTarget', 'extra_data', JSONField, initial=None),
RenameField('WebHookTarget', 'handlers', 'events'),
] |
05b6eaf259117cc6254e2b13c5a02569713e6356 | inbox/contacts/process_mail.py | inbox/contacts/process_mail.py | import uuid
from inbox.models import Contact, MessageContactAssociation
def update_contacts_from_message(db_session, message, account_id):
with db_session.no_autoflush:
for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'):
if getattr(message, field) is None:
continue
items = set(getattr(message, field))
for name, email_address in items:
contact = db_session.query(Contact).filter(
Contact.email_address == email_address).first()
if contact is None:
contact = Contact(name=name, email_address=email_address,
account_id=account_id, source='local',
provider_name='inbox',
uid=uuid.uuid4().hex)
message.contacts.append(MessageContactAssociation(
contact=contact, field=field))
| import uuid
from inbox.models import Contact, MessageContactAssociation
def update_contacts_from_message(db_session, message, account_id):
with db_session.no_autoflush:
for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'):
if getattr(message, field) is None:
continue
items = set(getattr(message, field))
for name, email_address in items:
contact = db_session.query(Contact).filter(
Contact.email_address == email_address,
Contact.account_id == account_id).first()
if contact is None:
contact = Contact(name=name, email_address=email_address,
account_id=account_id, source='local',
provider_name='inbox',
uid=uuid.uuid4().hex)
message.contacts.append(MessageContactAssociation(
contact=contact, field=field))
| Fix filtering criterion when updating contacts from message. | Fix filtering criterion when updating contacts from message.
| Python | agpl-3.0 | gale320/sync-engine,closeio/nylas,wakermahmud/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,gale320/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,nylas/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,ErinCall/sync-engine,EthanBlackburn/sync-engine,Eagles2F/sync-engine,closeio/nylas,closeio/nylas,wakermahmud/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,EthanBlackburn/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,gale320/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,ErinCall/sync-engine | ---
+++
@@ -10,7 +10,8 @@
items = set(getattr(message, field))
for name, email_address in items:
contact = db_session.query(Contact).filter(
- Contact.email_address == email_address).first()
+ Contact.email_address == email_address,
+ Contact.account_id == account_id).first()
if contact is None:
contact = Contact(name=name, email_address=email_address,
account_id=account_id, source='local', |
523a25d30241ecdd0abdb7545b1454714b003edc | astrospam/pyastro16.py | astrospam/pyastro16.py | """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
| """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
class PyAstro16(PyAstro):
"""
The 2016 edition of the python in astronomy conference.
"""
__doc__ += PyAstro.__doc__
| Add a subclass for the dot graph | Add a subclass for the dot graph
| Python | mit | cdeil/sphinx-tutorial | ---
+++
@@ -69,3 +69,11 @@
Properties are automatically documented as attributes
"""
return self._day
+
+
+class PyAstro16(PyAstro):
+ """
+ The 2016 edition of the python in astronomy conference.
+
+ """
+ __doc__ += PyAstro.__doc__ |
aab9efbcec0bbded807bf207e2324266573fa3a6 | tensorflow/python/tf2.py | tensorflow/python/tf2.py | # Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Tools to help with the TensorFlow 2.0 transition.
This module is meant for TensorFlow internal implementation, not for users of
the TensorFlow library. For that see tf.compat instead.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
_force_enable = None
def enable():
"""Enables v2 behaviors."""
global _force_enable
_force_enable = True
def disable():
"""Disables v2 behaviors."""
global _force_enable
_force_enable = False
def enabled():
"""Returns True iff TensorFlow 2.0 behavior should be enabled."""
if _force_enable is None:
return os.getenv("TF2_BEHAVIOR", "0") != "0"
else:
return _force_enable
| # Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Tools to help with the TensorFlow 2.0 transition.
This module is meant for TensorFlow internal implementation, not for users of
the TensorFlow library. For that see tf.compat instead.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
_force_enable = None
def enable():
"""Enables v2 behaviors."""
global _force_enable
_force_enable = True
def disable():
"""Disables v2 behaviors."""
global _force_enable
_force_enable = False
def enabled():
"""Returns True iff TensorFlow 2.0 behavior should be enabled."""
if _force_enable is None:
return os.getenv("TF2_BEHAVIOR", "0") != "0"
return _force_enable
| Remove the redundant `else` condition. | Remove the redundant `else` condition.
PiperOrigin-RevId: 302901741
Change-Id: I65281a07fc2789fbc13775c1365fd01789a1bb7e
| Python | apache-2.0 | petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,aldian/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,karllessard/tensorflow,gunan/tensorflow,sarvex/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,freedomtan/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,aam-at/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,davidzchen/tensorflow,annarev/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,aam-at/tensorflow,aldian/tensorflow,gunan/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,gunan/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,freedomtan/tensorflow,gunan/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,gunan/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,aldian/tensorflow,aam-at/tensorflow,aldian/tensorflow,gunan/tensorflow,aam-at/tensorflow,sarvex/tensorflow,karllessard/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,aldian/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,petewarden/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,annarev/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,petewarden/tensorflow,aldian/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,gunan/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,gunan/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,gunan/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow | ---
+++
@@ -24,7 +24,6 @@
import os
-
_force_enable = None
@@ -44,5 +43,5 @@
"""Returns True iff TensorFlow 2.0 behavior should be enabled."""
if _force_enable is None:
return os.getenv("TF2_BEHAVIOR", "0") != "0"
- else:
- return _force_enable
+
+ return _force_enable |
afd10d89ead46a8df35f6a0d17a2ca7dd4c7e826 | changes/api/validators/datetime.py | changes/api/validators/datetime.py | from __future__ import absolute_import
from datetime import datetime
import logging
class ISODatetime(object):
def __call__(self, value):
# type: (str) -> datetime
try:
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
except Exception:
logging.exception("Failed to parse datetime: %s", value)
raise ValueError('Datetime was not parseable. Expected ISO 8601 with timezone: YYYY-MM-DDTHH:MM:SS.mmmmmmZ')
| from __future__ import absolute_import
from datetime import datetime
import logging
# We appear to be hitting https://bugs.python.org/issue7980, but by using
# strptime early on, the race should be avoided.
datetime.strptime("", "")
class ISODatetime(object):
def __call__(self, value):
# type: (str) -> datetime
try:
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
except Exception:
logging.exception("Failed to parse datetime: %s", value)
raise ValueError('Datetime was not parseable. Expected ISO 8601 with timezone: YYYY-MM-DDTHH:MM:SS.mmmmmmZ')
| Use strptime at import time to avoid a race | Use strptime at import time to avoid a race
Summary:
We've observed funny AttributeErrors and similar in accessing _strptime, which
are likely the result of a known race. This might possibly fix it.
Test Plan: None
Reviewers: benjamin
Reviewed By: benjamin
Subscribers: changesbot, anupc
Differential Revision: https://tails.corp.dropbox.com/D225912
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -3,6 +3,10 @@
from datetime import datetime
import logging
+
+# We appear to be hitting https://bugs.python.org/issue7980, but by using
+# strptime early on, the race should be avoided.
+datetime.strptime("", "")
class ISODatetime(object): |
51e9262ff273db870310453797dbeb48eefd4df7 | logcollector/__init__.py | logcollector/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db'
db = SQLAlchemy(app)
@app.route("/")
def hello():
return "Hello World!"
| from flask import Flask, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from .models import DataPoint
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db'
db = SQLAlchemy(app)
@app.route("/new", methods=['POST'])
def collect():
new_data = DataPoint(request.form['timestamp'], request.form['dim1'],
request.form['dim2'], request.form['value']
)
db.session.add(new_data)
db.session.commit()
return jsonify(id=new_data.id, timestamp=request.form['timestamp'],
dim1=new_data.dim1, dim2=new_data.dim2), 201
| Implement save functionality with POST request | Implement save functionality with POST request
| Python | agpl-3.0 | kissgyorgy/log-collector | ---
+++
@@ -1,5 +1,6 @@
-from flask import Flask
+from flask import Flask, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
+from .models import DataPoint
app = Flask(__name__)
@@ -7,6 +8,13 @@
db = SQLAlchemy(app)
-@app.route("/")
-def hello():
- return "Hello World!"
+@app.route("/new", methods=['POST'])
+def collect():
+ new_data = DataPoint(request.form['timestamp'], request.form['dim1'],
+ request.form['dim2'], request.form['value']
+ )
+ db.session.add(new_data)
+ db.session.commit()
+
+ return jsonify(id=new_data.id, timestamp=request.form['timestamp'],
+ dim1=new_data.dim1, dim2=new_data.dim2), 201 |
a668afc87465989e85153c9bd2a608ba0ba54d9b | tests/test_containers.py | tests/test_containers.py | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import os
import threading
import unittest
import glob, os
import containers
PORT = 8080
class TestServer(TCPServer):
allow_reuse_address = True
handler = SimpleHTTPRequestHandler
httpd = TestServer(('', PORT), handler)
httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
class TestDiscovery(unittest.TestCase):
def tearDown(self):
filelist = glob.glob('/tmp/*.aci')
for f in filelist:
os.remove(f)
def test_get_etcd(self):
containers.simple_discovery('localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
var='/tmp', secure=False)
if __name__ == '__main__':
unittest.main()
| try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import glob
import os
import sys
import threading
import unittest
import containers
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
PORT = 8080
class TestServer(TCPServer):
allow_reuse_address = True
handler = SimpleHTTPRequestHandler
httpd = TestServer(('', PORT), handler)
httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
class TestDiscovery(unittest.TestCase):
def tearDown(self):
filelist = glob.glob('/tmp/*.aci')
for f in filelist:
os.remove(f)
def test_get_returns_string(self):
c = containers.simple_discovery(
'localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
var='/tmp', secure=False)
self.assertTrue(isinstance(c, string_types))
def test_get_etcd(self):
c = containers.simple_discovery(
'localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
var='/tmp', secure=False)
self.assertTrue(os.path.isfile(os.path.join('/tmp', c)))
if __name__ == '__main__':
unittest.main()
| Add test that aci was downloaded | Add test that aci was downloaded
| Python | mit | kragniz/containers | ---
+++
@@ -8,12 +8,21 @@
except ImportError:
from SocketServer import TCPServer
+import glob
import os
+import sys
import threading
import unittest
-import glob, os
import containers
+
+
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ string_types = str,
+else:
+ string_types = basestring,
PORT = 8080
@@ -35,9 +44,20 @@
for f in filelist:
os.remove(f)
+ def test_get_returns_string(self):
+ c = containers.simple_discovery(
+ 'localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
+ var='/tmp', secure=False)
+
+ self.assertTrue(isinstance(c, string_types))
+
def test_get_etcd(self):
- containers.simple_discovery('localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
- var='/tmp', secure=False)
+ c = containers.simple_discovery(
+ 'localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64',
+ var='/tmp', secure=False)
+
+ self.assertTrue(os.path.isfile(os.path.join('/tmp', c)))
+
if __name__ == '__main__': |
f3e1c74d9b85814cd56397560c5023e7ef536caa | tests/test_statuspage.py | tests/test_statuspage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
| Remove some more unneccesary code. | Unittests: Remove some more unneccesary code.
| Python | mit | zalando/patroni,zalando/patroni,sean-/patroni,pgexperts/patroni,sean-/patroni,pgexperts/patroni,jinty/patroni,jinty/patroni | ---
+++
@@ -36,7 +36,3 @@
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
-
-
-if __name__ == '__main__':
- unittest.main() |
c651034d74df524ad29cb4c381bf4cb12400d73f | src/event_manager/views.py | src/event_manager/views.py | from django.shortcuts import render
from event_manager.models import Suggestion, Event
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'login2.html', {})
#FIXME: Remove comment when login works
#@login_required
def my_suggestions(request):
#FIXME: Need to only select so many, also only yours
suggestions = Suggestion.objects.values()
return render(request, 'suggestions.html', suggestions)
#FIXME: Remove comment when login works
#@login_required
def my_events(request):
#FIXME: Need to only select so many, also only yours
events = Event.objects.values()
return render(request, 'events.html', events)
| from django.shortcuts import render
from event_manager.models import Suggestion, Event
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'login2.html', {})
#FIXME: Remove comment when login works
#@login_required
def my_suggestions(request):
#FIXME: Need to only select so many, also only yours
suggestions = Suggestion.objects.values()
return render(request, 'suggestions.html', {'suggestions': suggestions})
#FIXME: Remove comment when login works
#@login_required
def my_events(request):
#FIXME: Need to only select so many, also only yours
events = Event.objects.values()
return render(request, 'events.html', {'events': events})
| Switch from raw dict to context dict | Switch from raw dict to context dict
| Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit | ---
+++
@@ -10,12 +10,12 @@
def my_suggestions(request):
#FIXME: Need to only select so many, also only yours
suggestions = Suggestion.objects.values()
- return render(request, 'suggestions.html', suggestions)
+ return render(request, 'suggestions.html', {'suggestions': suggestions})
#FIXME: Remove comment when login works
#@login_required
def my_events(request):
#FIXME: Need to only select so many, also only yours
events = Event.objects.values()
- return render(request, 'events.html', events)
+ return render(request, 'events.html', {'events': events})
|
550101a804cb48f07042014ac5d413071a0e29d7 | coap/test/test_request.py | coap/test/test_request.py | from ..code_registry import MethodCode, MessageType
from ..coap import Coap
def test_build_message():
c = Coap('coap.me')
result = c.get('hello')
print str(bytearray(result.server_reply_list[0].payload))
c.destroy()
| from ..code_registry import MethodCode, MessageType
from ..coap import Coap
import binascii
def test_build_message():
c = Coap('coap.me')
result1 = c.get('hello')
assert str(bytearray(result1.server_reply_list[0].payload)) == '\xffworld'
result2 = c.get('separate')
assert str(bytearray(result2.server_reply_list[0].payload)) == '\xffThat took a long time'
c.destroy()
| Add very basic testing for Coap request. | Add very basic testing for Coap request.
| Python | bsd-3-clause | samueldotj/pycoap | ---
+++
@@ -1,9 +1,14 @@
from ..code_registry import MethodCode, MessageType
from ..coap import Coap
+import binascii
def test_build_message():
c = Coap('coap.me')
- result = c.get('hello')
- print str(bytearray(result.server_reply_list[0].payload))
+ result1 = c.get('hello')
+ assert str(bytearray(result1.server_reply_list[0].payload)) == '\xffworld'
+
+ result2 = c.get('separate')
+ assert str(bytearray(result2.server_reply_list[0].payload)) == '\xffThat took a long time'
+
c.destroy()
|
55d13c7f59d5500fbbf2cbe915a6f2fe8e538e14 | example/layout/__year__/index.html.py | example/layout/__year__/index.html.py | __name__ = "Year View"
__author__ = "Decklin Foster <decklin@red-bean.com>"
__description__ = "Calendar of all dates in a given year."
import time
def make(instance, entries, all, vars):
# we get all the entries for this year in ``entries``, in here we want to
# build some monthly calendars to pass to the next bit
cal = {}
for e in entries:
m = time.strftime('%m', e.date)
d = time.strftime('%d', e.date)
cal.setdefault(m, {})
cal[m].setdefault(d, 0)
cal[m][d] += 1
months = [muse.expand('calendar', m=m, days=d, **vars) for m, d in cal.items()]
sidebar = muse.expand('sidebar', entries=entries, all=all, **vars)
footer = 'Footer'
pagetitle = 'Year %s - %s' % (instance, vars['blogtitle'])
return muse.expand('page', layout=__name__, body="\n".join(months),
pagetitle=pagetitle, sidebar=sidebar, footer=footer, **vars)
| __name__ = "Year View"
__author__ = "Decklin Foster <decklin@red-bean.com>"
__description__ = "Calendar of all dates in a given year."
import time
def make(instance, entries, all, vars):
# we get all the entries for this year in ``entries``, in here we want to
# build some monthly calendars to pass to the next bit
cal = {}
for e in entries:
m = time.strftime('%m', e.date)
d = time.strftime('%d', e.date)
cal.setdefault(m, {})
cal[m].setdefault(d, 0)
cal[m][d] += 1
months = [muse.expand('calendar', y=instance, m=month, days=days, **vars)
for month, days in cal.items()]
sidebar = muse.expand('sidebar', entries=entries, all=all, **vars)
footer = 'Footer'
pagetitle = 'Year %s - %s' % (instance, vars['blogtitle'])
return muse.expand('page', layout=__name__, body="\n".join(months),
pagetitle=pagetitle, sidebar=sidebar, footer=footer, **vars)
| Make this a bit more readable. | Make this a bit more readable.
| Python | isc | decklin/ennepe | ---
+++
@@ -15,7 +15,8 @@
cal[m].setdefault(d, 0)
cal[m][d] += 1
- months = [muse.expand('calendar', m=m, days=d, **vars) for m, d in cal.items()]
+ months = [muse.expand('calendar', y=instance, m=month, days=days, **vars)
+ for month, days in cal.items()]
sidebar = muse.expand('sidebar', entries=entries, all=all, **vars)
footer = 'Footer'
pagetitle = 'Year %s - %s' % (instance, vars['blogtitle']) |
d1e2dc224b7b922d39f0f8f21affe39985769315 | src/loader.py | src/loader.py | from scipy.io import loadmat
def load_clean_data():
data = loadmat('data/cleandata_students.mat')
return data['x'], data['y']
def load_noisy_data():
data = loadmat('data/noisydata_students.mat')
return data['x'], data['y']
if __name__ == '__main__':
print('Clean Data:')
x, y = load_clean_data()
print('x:', x)
print('y:', y)
print()
print('Noisy Data:')
x, y = load_noisy_data()
print('x:', x)
print('y:', y)
| from scipy.io import loadmat
def load_data(data_file):
data = loadmat(data_file)
return data['x'], data['y']
if __name__ == '__main__':
print('Clean Data:')
x, y = load_data('data/cleandata_students.mat')
print('x:', x)
print('y:', y)
print()
print('Noisy Data:')
x, y = load_data('data/noisydata_students.mat')
print('x:', x)
print('y:', y)
| Remove hard-coded data file path | Remove hard-coded data file path | Python | mit | MLNotWar/decision-trees-algorithm,MLNotWar/decision-trees-algorithm | ---
+++
@@ -1,22 +1,18 @@
from scipy.io import loadmat
-def load_clean_data():
- data = loadmat('data/cleandata_students.mat')
- return data['x'], data['y']
-
-def load_noisy_data():
- data = loadmat('data/noisydata_students.mat')
+def load_data(data_file):
+ data = loadmat(data_file)
return data['x'], data['y']
if __name__ == '__main__':
print('Clean Data:')
- x, y = load_clean_data()
+ x, y = load_data('data/cleandata_students.mat')
print('x:', x)
print('y:', y)
print()
print('Noisy Data:')
- x, y = load_noisy_data()
+ x, y = load_data('data/noisydata_students.mat')
print('x:', x)
print('y:', y) |
6b5a4dd75bc1d6dc5187da4ea5e617f30e395b89 | orchard/views/__init__.py | orchard/views/__init__.py | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspection PyMethodMayBeStatic
def index(self) -> str:
"""
Display a simple greeting.
:return: The home page with a message to all visitors.
"""
return flask.render_template('index.html')
# noinspection PyMethodMayBeStatic
def get(self, name: str) -> str:
"""
Display a simple personalized greeting.
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
if name == 'BMeu':
flask.abort(500)
elif name == 'BMeu2':
raise ValueError
return flask.render_template('index.html', name = name)
IndexView.register(views)
| # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspection PyMethodMayBeStatic
def index(self) -> str:
"""
Display a simple greeting.
:return: The home page with a message to all visitors.
"""
return flask.render_template('index.html')
# noinspection PyMethodMayBeStatic
def get(self, name: str) -> str:
"""
Display a simple personalized greeting.
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
return flask.render_template('index.html', name = name)
IndexView.register(views)
| Remove the intentional throwing of internal server errors. | Remove the intentional throwing of internal server errors.
Fixes failing tests.
| Python | mit | BMeu/Orchard,BMeu/Orchard | ---
+++
@@ -33,10 +33,6 @@
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
- if name == 'BMeu':
- flask.abort(500)
- elif name == 'BMeu2':
- raise ValueError
return flask.render_template('index.html', name = name)
|
579b566c33174b53276ece63c40d345b207890c8 | allure-behave/setup.py | allure-behave/setup.py | import os
from setuptools import setup
PACKAGE = "allure-behave"
VERSION = "2.6.4"
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Testing :: BDD'
]
install_requires = [
"behave>=1.2.5",
"allure-python-commons==2.6.4"
]
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def main():
setup(
name=PACKAGE,
version=VERSION,
description="Allure behave integration",
url="https://github.com/allure-framework/allure-python",
author="QAMetaSoftware, Stanislav Seliverstov",
author_email="sseliverstov@qameta.io",
license="Apache-2.0",
classifiers=classifiers,
keywords="allure reporting behave",
long_description=read('README.rst'),
packages=["allure_behave"],
package_dir={"allure_behave": "src"},
install_requires=install_requires
)
if __name__ == '__main__':
main()
| import os
from setuptools import setup
PACKAGE = "allure-behave"
VERSION = "2.6.4"
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Testing :: BDD',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
]
install_requires = [
"behave>=1.2.5",
"allure-python-commons==2.6.4"
]
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def main():
setup(
name=PACKAGE,
version=VERSION,
description="Allure behave integration",
url="https://github.com/allure-framework/allure-python",
author="QAMetaSoftware, Stanislav Seliverstov",
author_email="sseliverstov@qameta.io",
license="Apache-2.0",
classifiers=classifiers,
keywords="allure reporting behave",
long_description=read('README.rst'),
packages=["allure_behave"],
package_dir={"allure_behave": "src"},
install_requires=install_requires
)
if __name__ == '__main__':
main()
| Add trove classifiers for python versions | Add trove classifiers for python versions
This marks the project as working on Python 2 and 3. As tests
currently run on python 3.6 and 3.7, I've added those classifiers.
| Python | apache-2.0 | allure-framework/allure-python | ---
+++
@@ -10,7 +10,12 @@
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
- 'Topic :: Software Development :: Testing :: BDD'
+ 'Topic :: Software Development :: Testing :: BDD',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
]
install_requires = [ |
969a4f011c7f78a04b6939768d59ba768ff4d160 | Lib/importlib/__init__.py | Lib/importlib/__init__.py | """Backport of importlib.import_module from 3.x."""
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
level -= 1
try:
if package.count('.') < level:
raise ValueError("attempted relative import beyond top-level "
"package")
except AttributeError:
raise ValueError("__package__ not set to a string")
base = package.rsplit('.', level)[0]
if name:
return "%s.%s" % (base, name)
else:
return base
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
| """Backport of importlib.import_module from 3.x."""
# While not critical (and in no way guaranteed!), it would be nice to keep this
# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
level -= 1
try:
if package.count('.') < level:
raise ValueError("attempted relative import beyond top-level "
"package")
except AttributeError:
raise ValueError("'package' not set to a string")
try:
# rpartition is more "correct" and rfind is just as easy to use, but
# neither are in Python 2.3.
dot_rindex = package.rindex('.', level)[0]
base = package[:dot_rindex]
except ValueError:
base = package
if name:
return "%s.%s" % (base, name)
else:
return base
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
# Try to import specifying the level to be as accurate as possible, but
# realize that keyword arguments are not found in Python 2.3.
try:
__import__(name, level=0)
except TypeError:
__import__(name)
return sys.modules[name]
| Make importlib backwards-compatible to Python 2.2 (but this is not promised to last; just doing it to be nice). | Make importlib backwards-compatible to Python 2.2 (but this is not promised to
last; just doing it to be nice).
Also fix a message for an exception.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,6 @@
"""Backport of importlib.import_module from 3.x."""
+# While not critical (and in no way guaranteed!), it would be nice to keep this
+# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
@@ -9,8 +11,14 @@
raise ValueError("attempted relative import beyond top-level "
"package")
except AttributeError:
- raise ValueError("__package__ not set to a string")
- base = package.rsplit('.', level)[0]
+ raise ValueError("'package' not set to a string")
+ try:
+ # rpartition is more "correct" and rfind is just as easy to use, but
+ # neither are in Python 2.3.
+ dot_rindex = package.rindex('.', level)[0]
+ base = package[:dot_rindex]
+ except ValueError:
+ base = package
if name:
return "%s.%s" % (base, name)
else:
@@ -34,5 +42,10 @@
break
level += 1
name = _resolve_name(name[level:], package, level)
- __import__(name)
+ # Try to import specifying the level to be as accurate as possible, but
+ # realize that keyword arguments are not found in Python 2.3.
+ try:
+ __import__(name, level=0)
+ except TypeError:
+ __import__(name)
return sys.modules[name] |
22a889dd8f12a11ff22f1b1e167b3c888f892f88 | typesetter/typesetter.py | typesetter/typesetter.py | from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
JSONIFY_PRETTYPRINT_REGULAR=False,
)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().split('\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/search/<fragment>')
def search(fragment):
results = []
for word in WORDS:
if fragment in word:
results.append({
'word': word,
'category': classify(word),
})
return jsonify(results)
def classify(word):
length = len(word)
if length < 7:
return 'short'
elif length < 10:
return 'medium'
else:
return 'long'
| from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
# Reduce response size by avoiding pretty printing.
JSONIFY_PRETTYPRINT_REGULAR=False,
)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().split('\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/search/<fragment>')
def search(fragment):
results = []
for word in WORDS:
if fragment in word:
results.append({
'word': word,
'category': classify(word),
})
return jsonify(results)
def classify(word):
length = len(word)
if length < 7:
return 'short'
elif length < 10:
return 'medium'
else:
return 'long'
| Add clarifying comment about avoiding pretty printing | Add clarifying comment about avoiding pretty printing
| Python | mit | rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter | ---
+++
@@ -3,6 +3,7 @@
app = Flask(__name__)
app.config.update(
+ # Reduce response size by avoiding pretty printing.
JSONIFY_PRETTYPRINT_REGULAR=False,
)
|
0d0434744efef091fd8d26725f21c8015a06d8be | opentreemap/treemap/templatetags/instance_config.py | opentreemap/treemap/templatetags/instance_config.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
return '#' + color
else:
return ''
@register.filter
def primary_color(config):
return _get_color_from_config(config,
"scss_variables.primary-color")
@register.filter
def secondary_color(config):
return _get_color_from_config(config,
"scss_variables.secondary-color")
@register.filter
def feature_enabled(instance, feature):
return instance.feature_enabled(feature)
@register.filter
def plot_field_is_writable(instanceuser, field):
return plot_is_writable(instanceuser, field)
@register.filter
def plot_is_writable(instanceuser, field=None):
if instanceuser is None or instanceuser == '':
return False
else:
perms = instanceuser.role.plot_permissions.all()
if field:
perms = perms.filter(field_name=field)
if len(perms) == 0:
return False
else:
return perms[0].allows_writes
@register.filter
def instance_config(instance, field):
if instance:
return get_attr_from_json_field(instance, "config." + field)
else:
return None
| from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
return '#' + color
else:
return ''
@register.filter
def primary_color(config):
return _get_color_from_config(config,
"scss_variables.primary-color")
@register.filter
def secondary_color(config):
return _get_color_from_config(config,
"scss_variables.secondary-color")
@register.filter
def feature_enabled(instance, feature):
return instance.feature_enabled(feature)
@register.filter
def plot_field_is_writable(instanceuser, field):
return plot_is_writable(instanceuser, field)
@register.filter
def plot_is_writable(instanceuser, field=None):
if instanceuser is None or instanceuser == '':
return False
else:
perms = instanceuser.role.plot_permissions.all()
if field:
perms = perms.filter(field_name=field)
return any(perm.allows_writes for perm in perms)
@register.filter
def instance_config(instance, field):
if instance:
return get_attr_from_json_field(instance, "config." + field)
else:
return None
| Allow "writable" if *any* field is writable | Allow "writable" if *any* field is writable
Fixes Internal Issue 598
| Python | agpl-3.0 | recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,RickMohr/otm-core,maurizi/otm-core,maurizi/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core | ---
+++
@@ -48,10 +48,7 @@
if field:
perms = perms.filter(field_name=field)
- if len(perms) == 0:
- return False
- else:
- return perms[0].allows_writes
+ return any(perm.allows_writes for perm in perms)
@register.filter |
b03c0898897bbd89f8701e1c4d6d84d263bbd039 | utils/publish_message.py | utils/publish_message.py | import amqp
from contextlib import closing
def publish_message(message_body, exchange, type, routing_key):
""" Publish a message to an exchange with exchange type and routing key specified.
A message is sent to a specified exchange with the provided routing_key.
:param message_body: The body of the message to be sent.
:param exchange: The name of the exchange the message is sent to.
:param routing_key: The routing key to be sent with the message.
Usage::
>>> from utils import publish_message
>>> publish_message('message', 'exchange', 'routing_key')
"""
with closing(amqp.Connection()) as connection:
channel = connection.channel()
msg = amqp.Message(message)
channel.basic_publish_confirm(msg=msg, exchange=exchange, routing_key=routing_key)
| import amqp
from contextlib import closing
def __get_channel(connection):
return connection.channel()
def __get_message(message_body):
return amqp.Message(message_body)
def __declare_exchange(channel, exchange, type):
channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False)
def __publish_message_to_exchange(channel, message, exchange, routing_key):
channel.basic_publish_confirm(msg=message, exchange=exchange, routing_key=routing_key)
def publish_message(message_body, exchange, type, routing_key):
""" Publish a message to an exchange with exchange type and routing key specified.
A message is sent to an exchange of specified type with the provided routing_key. The exchange is declared if one of the same name does not already exist. If one of the same name does already exist but has different parameters, an error is raised. The exchange has parameters durable=True and auto_delete=False set as default.
:param message_body: The body of the message to be sent.
:param exchange: The name of the exchange the message is sent to.
:param type: The type of the exchange the message is sent to.
:param routing_key: The routing key to be sent with the message.
Usage::
>>> from utils import publish_message
>>> publish_message('message_body', 'exchange', 'type', 'routing_key')
"""
with closing(amqp.Connection()) as connection:
channel = __get_channel(connection)
message = __get_message(message_body)
__declare_exchange(channel, exchange, type)
__publish_message_to_exchange(channel, message, exchange, routing_key)
| Revert "EAFP and removing redundant functions" | Revert "EAFP and removing redundant functions"
This reverts commit fbb9eeded41e46c8fe8c3ddaba7f8d9fd1e3bff3.
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend | ---
+++
@@ -2,22 +2,36 @@
from contextlib import closing
+def __get_channel(connection):
+ return connection.channel()
+
+def __get_message(message_body):
+ return amqp.Message(message_body)
+
+def __declare_exchange(channel, exchange, type):
+ channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False)
+
+def __publish_message_to_exchange(channel, message, exchange, routing_key):
+ channel.basic_publish_confirm(msg=message, exchange=exchange, routing_key=routing_key)
+
def publish_message(message_body, exchange, type, routing_key):
""" Publish a message to an exchange with exchange type and routing key specified.
- A message is sent to a specified exchange with the provided routing_key.
+ A message is sent to an exchange of specified type with the provided routing_key. The exchange is declared if one of the same name does not already exist. If one of the same name does already exist but has different parameters, an error is raised. The exchange has parameters durable=True and auto_delete=False set as default.
:param message_body: The body of the message to be sent.
:param exchange: The name of the exchange the message is sent to.
+ :param type: The type of the exchange the message is sent to.
:param routing_key: The routing key to be sent with the message.
Usage::
>>> from utils import publish_message
- >>> publish_message('message', 'exchange', 'routing_key')
+ >>> publish_message('message_body', 'exchange', 'type', 'routing_key')
"""
with closing(amqp.Connection()) as connection:
- channel = connection.channel()
- msg = amqp.Message(message)
- channel.basic_publish_confirm(msg=msg, exchange=exchange, routing_key=routing_key)
+ channel = __get_channel(connection)
+ message = __get_message(message_body)
+ __declare_exchange(channel, exchange, type)
+ __publish_message_to_exchange(channel, message, exchange, routing_key) |
f9c351bbddb9f0e212b92bdada4825d79bad2812 | categories/__init__.py | categories/__init__.py | __version_info__ = {
'major': 1,
'minor': 6,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| __version_info__ = {
'major': 1,
'minor': 6,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| Update the version to 1.6.1 | Update the version to 1.6.1
| Python | apache-2.0 | callowayproject/django-categories,callowayproject/django-categories,callowayproject/django-categories | ---
+++
@@ -1,7 +1,7 @@
__version_info__ = {
'major': 1,
'minor': 6,
- 'micro': 0,
+ 'micro': 1,
'releaselevel': 'final',
'serial': 1
} |
6d04f0f924df11968b85aa2c885bde30cf6af597 | stack/vpc.py | stack/vpc.py | from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = InternetGateway(
"InternetGateway",
template=template,
)
# Attach Gateway to VPC
VPCGatewayAttachment(
"GatewayAttachement",
template=template,
VpcId=Ref(vpc),
InternetGatewayId=Ref(internet_gateway),
)
| from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
Route,
RouteTable,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = InternetGateway(
"InternetGateway",
template=template,
)
# Attach Gateway to VPC
VPCGatewayAttachment(
"GatewayAttachement",
template=template,
VpcId=Ref(vpc),
InternetGatewayId=Ref(internet_gateway),
)
# Public route table
public_route_table = RouteTable(
"PublicRouteTable",
template=template,
VpcId=Ref(vpc),
)
public_route = Route(
"PublicRoute",
template=template,
GatewayId=Ref(internet_gateway),
DestinationCidrBlock="0.0.0.0/0",
RouteTableId=Ref(public_route_table),
)
| Add a public route table | Add a public route table
| Python | mit | caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics | ---
+++
@@ -4,6 +4,8 @@
from troposphere.ec2 import (
InternetGateway,
+ Route,
+ RouteTable,
VPC,
VPCGatewayAttachment,
)
@@ -32,3 +34,20 @@
VpcId=Ref(vpc),
InternetGatewayId=Ref(internet_gateway),
)
+
+
+# Public route table
+public_route_table = RouteTable(
+ "PublicRouteTable",
+ template=template,
+ VpcId=Ref(vpc),
+)
+
+
+public_route = Route(
+ "PublicRoute",
+ template=template,
+ GatewayId=Ref(internet_gateway),
+ DestinationCidrBlock="0.0.0.0/0",
+ RouteTableId=Ref(public_route_table),
+) |
90e557d681c9ea3f974ee5357ec67f294322d224 | src/elm_doc/decorators.py | src/elm_doc/decorators.py | import functools
import subprocess
from doit.exceptions import TaskFailed
def capture_subprocess_error(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
return TaskFailed(
'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{}'.format(
' '.join(e.cmd),
e.stdout.decode('utf8') if e.stdout else '',
e.stderr.decode('utf8') if e.stderr else ''))
return wrapper
| import functools
import subprocess
from doit.exceptions import TaskFailed
def capture_subprocess_error(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
command_string = e.cmd if isinstance(e.cmd, str) else ' '.join(e.cmd)
return TaskFailed(
'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{}'.format(
command_string,
e.stdout.decode('utf8') if e.stdout else '',
e.stderr.decode('utf8') if e.stderr else ''))
return wrapper
| Clean error output when command is a string | Clean error output when command is a string
| Python | bsd-3-clause | ento/elm-doc,ento/elm-doc | ---
+++
@@ -10,9 +10,10 @@
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
+ command_string = e.cmd if isinstance(e.cmd, str) else ' '.join(e.cmd)
return TaskFailed(
'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{}'.format(
- ' '.join(e.cmd),
+ command_string,
e.stdout.decode('utf8') if e.stdout else '',
e.stderr.decode('utf8') if e.stderr else ''))
return wrapper |
1107fc26cf9baa235d62813ea0006687d4710280 | src/engine/file_loader.py | src/engine/file_loader.py | import os
import json
from lib import contract
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.endswith('.json')
def load_json(json_file_name):
with open(json_file_name) as json_file:
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
| import os
import json
from lib import contract
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.endswith('.json')
def load_json(json_file_name):
with open(json_file_name) as json_file:
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
@contract.accepts(str)
@contract.returns(dict)
def load_enum(struct_name):
enum_ = {}
list_ = read_and_parse_json(struct_name)[0]
for enumeration, enum_type in enumerate(list_):
enum_[str(enum_type)] = enumeration
return enum_
@contract.accepts(str)
@contract.returns(dict)
def load_struct(struct_name):
def create_struct_map(struct_map, struct_):
struct_map[str(struct_['name'])] = struct_
return struct_map
return reduce(create_struct_map, read_and_parse_json(struct_name), {})
| Add load_enum and load_struct functions | Add load_enum and load_struct functions
Load enumeration list json
Load full struct into dictionary
| Python | mit | Tactique/game_engine,Tactique/game_engine | ---
+++
@@ -22,3 +22,23 @@
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
+
+
+@contract.accepts(str)
+@contract.returns(dict)
+def load_enum(struct_name):
+ enum_ = {}
+ list_ = read_and_parse_json(struct_name)[0]
+ for enumeration, enum_type in enumerate(list_):
+ enum_[str(enum_type)] = enumeration
+ return enum_
+
+
+@contract.accepts(str)
+@contract.returns(dict)
+def load_struct(struct_name):
+ def create_struct_map(struct_map, struct_):
+ struct_map[str(struct_['name'])] = struct_
+ return struct_map
+
+ return reduce(create_struct_map, read_and_parse_json(struct_name), {}) |
ab506307b6b3fc2997a7afd38c02cae630dbf90b | addons/hr_holidays/migrations/8.0.1.5/pre-migration.py | addons/hr_holidays/migrations/8.0.1.5/pre-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
'''update hr_holidays
set meeting_id=calendar_event.id
from calendar_event where meeting_id=%s''' % (
openupgrade.get_legacy_name('crm_meeting_id'),
)
)
| # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
"ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey"
)
cr.execute(
'''update hr_holidays
set meeting_id=calendar_event.id
from calendar_event where meeting_id=%s''' % (
openupgrade.get_legacy_name('crm_meeting_id'),
)
)
| Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. | Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues.
- The constraint will be reset by the ORM later.
- Not doing it may both slow the migration and abort it altogether.
| Python | agpl-3.0 | OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,kirca/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,mvaled/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,OpenUpgrade/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,sebalix/OpenUpgrade,hifly/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,csrocha/OpenUpgrade,sebalix/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,blaggacao/OpenUpgrade,0k/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,OpenUpgrade/OpenUpgrade,damdam-s/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,OpenUpgrade/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,csrocha/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,csrocha/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,0k/OpenUpgrade,Endika/OpenUpgrade,blaggacao/OpenUpgrade,grap/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,blaggacao/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,grap/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,mvaled/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,grap/OpenUpgrade,kirca/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,grap/OpenUpgrade,sebalix/OpenUpgrade,hifly/OpenUpgrade,csrocha/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,0k/OpenUpgrade,pedrobaeza/OpenUpgrade,bwrsandman/OpenUpgrade,csrocha/OpenUpgrade,OpenUpgrade/OpenUpgrade,csrocha/OpenUpgrade,hifly/OpenUpgrade,0k/OpenUpgrade,Endika/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,hifly/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,hifly/OpenUpgrade,csrocha/OpenUpgrade,hifly/OpenUpgrade,kirca/OpenUpgrade,grap/OpenUpgrade,sebalix/OpenUpgrade | ---
+++
@@ -24,6 +24,9 @@
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
+ "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey"
+ )
+ cr.execute(
'''update hr_holidays
set meeting_id=calendar_event.id
from calendar_event where meeting_id=%s''' % ( |
8799197befd1f52278a4344fc41ba94cc45c548a | src/you_get/json_output.py | src/you_get/json_output.py |
import json
# save info from common.print_info()
last_info = None
def output(video_extractor, pretty_print=True):
ve = video_extractor
out = {}
out['url'] = ve.url
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
if pretty_print:
print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False))
else:
print(json.dumps(out))
# a fake VideoExtractor object to save info
class VideoExtractor(object):
pass
def print_info(site_info=None, title=None, type=None, size=None):
global last_info
# create a VideoExtractor and save info for download_urls()
ve = VideoExtractor()
last_info = ve
ve.name = site_info
ve.title = title
ve.url = None
def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None):
ve = last_info
if not ve:
ve = VideoExtractor()
ve.name = ''
ve.url = urls
ve.title=title
# save download info in streams
stream = {}
stream['container'] = ext
stream['size'] = total_size
stream['src'] = urls
if refer:
stream['refer'] = refer
stream['video_profile'] = '__default__'
ve.streams = {}
ve.streams['__default__'] = stream
output(ve)
|
import json
# save info from common.print_info()
last_info = None
def output(video_extractor, pretty_print=True):
ve = video_extractor
out = {}
out['url'] = ve.url
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
try:
if ve.audiolang:
out['audiolang'] = ve.audiolang
except NameError:
pass
if pretty_print:
print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False))
else:
print(json.dumps(out))
# a fake VideoExtractor object to save info
class VideoExtractor(object):
pass
def print_info(site_info=None, title=None, type=None, size=None):
global last_info
# create a VideoExtractor and save info for download_urls()
ve = VideoExtractor()
last_info = ve
ve.name = site_info
ve.title = title
ve.url = None
def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None):
ve = last_info
if not ve:
ve = VideoExtractor()
ve.name = ''
ve.url = urls
ve.title=title
# save download info in streams
stream = {}
stream['container'] = ext
stream['size'] = total_size
stream['src'] = urls
if refer:
stream['refer'] = refer
stream['video_profile'] = '__default__'
ve.streams = {}
ve.streams['__default__'] = stream
output(ve)
| Print audiolang in json output | Print audiolang in json output
| Python | mit | zmwangx/you-get,zmwangx/you-get,xyuanmu/you-get,qzane/you-get,qzane/you-get,xyuanmu/you-get,cnbeining/you-get,cnbeining/you-get | ---
+++
@@ -11,6 +11,11 @@
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
+ try:
+ if ve.audiolang:
+ out['audiolang'] = ve.audiolang
+ except NameError:
+ pass
if pretty_print:
print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False))
else: |
1b36e4ec9c15a0f9064d605f7c7f60672416dcb0 | workers/subscriptions.py | workers/subscriptions.py | import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
| import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
| Remove collecting plugins every second | Remove collecting plugins every second
| Python | mit | sevazhidkov/leonard | ---
+++
@@ -1,4 +1,5 @@
import os
+import time
import telegram
@@ -8,10 +9,8 @@
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
- i = 0
+ bot.collect_plugins()
while True:
- if i % 10 == 0:
- bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
- i += 1
+ time.sleep(60) |
662d103adffd0592474378e2aaf98b8fafc3fb93 | salt/beacons/salt_proxy.py | salt/beacons/salt_proxy.py | # -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of
one or more salt proxy processes
.. versionadded:: 2015.8.3
'''
# Import python libs
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def _run_proxy_processes(proxies):
'''
Iterate over a list of proxy
names and restart any that
aren't running
'''
ret = []
for prox_ in proxies:
# prox_ is a dict
proxy = prox_.keys()[0]
result = {}
if not __salt__['salt_proxy.is_running'](proxy)['result']:
__salt__['salt_proxy.configure_proxy'](proxy, start=True)
result[proxy] = 'Proxy {0} was started'.format(proxy)
ret.append(result)
else:
msg = 'Proxy {0} is already running'.format(proxy)
result[proxy] = msg
ret.append(result)
log.debug(msg)
return ret
def beacon(proxies):
'''
Handle configured proxies
.. code-block:: yaml
beacons:
salt_proxy:
- p8000: {}
- p8001: {}
'''
log.trace('salt proxy beacon called')
return _run_proxy_processes(proxies)
| # -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of
one or more salt proxy processes
.. versionadded:: 2015.8.3
'''
# Import python libs
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def _run_proxy_processes(proxies):
'''
Iterate over a list of proxy
names and restart any that
aren't running
'''
ret = []
for prox_ in proxies:
# prox_ is a dict
proxy = prox_.keys()[0]
result = {}
if not __salt__['salt_proxy.is_running'](proxy)['result']:
__salt__['salt_proxy.configure_proxy'](proxy, start=True)
result[proxy] = 'Proxy {0} was started'.format(proxy)
else:
msg = 'Proxy {0} is already running'.format(proxy)
result[proxy] = msg
log.debug(msg)
ret.append(result)
return ret
def beacon(proxies):
'''
Handle configured proxies
.. code-block:: yaml
beacons:
salt_proxy:
- p8000: {}
- p8001: {}
'''
log.trace('salt proxy beacon called')
return _run_proxy_processes(proxies)
| Move append out of if/else block | Move append out of if/else block
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -27,12 +27,11 @@
if not __salt__['salt_proxy.is_running'](proxy)['result']:
__salt__['salt_proxy.configure_proxy'](proxy, start=True)
result[proxy] = 'Proxy {0} was started'.format(proxy)
- ret.append(result)
else:
msg = 'Proxy {0} is already running'.format(proxy)
result[proxy] = msg
- ret.append(result)
log.debug(msg)
+ ret.append(result)
return ret
|
24da0f84e1a844b1f53e5afafc34cfcc915a9a67 | corehq/apps/userreports/tests/test_report_rendering.py | corehq/apps/userreports/tests/test_report_rendering.py | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
class VeryFakeReportView(ConfigurableReportView):
# note: this is very coupled to what it tests below, but it beats bootstrapping a whole UCR thing
def __init__(self, data):
self._data = data
@property
def export_table(self):
return self._data
class ReportRenderingTest(SimpleTestCase):
def test_email_response_unicode(self):
report = VeryFakeReportView(data=[
['hello', 'हिन्दी']
])
# this used to fail: https://manage.dimagi.com/default.asp?263803
report.email_response
| # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
from corehq.apps.userreports.reports.util import ReportExport
class VeryFakeReportExport(ReportExport):
def __init__(self, data):
self._data = data
def get_table(self):
return self._data
class VeryFakeReportView(ConfigurableReportView):
# note: this is very coupled to what it tests below, but it beats bootstrapping a whole UCR thing
def __init__(self, data):
self._data = data
@property
def report_export(self):
return VeryFakeReportExport(self._data)
class ReportRenderingTest(SimpleTestCase):
def test_email_response_unicode(self):
report = VeryFakeReportView(data=[
['hello', 'हिन्दी']
])
# this used to fail: https://manage.dimagi.com/default.asp?263803
report.email_response
| Update report_rendering test to use ReportExport | Update report_rendering test to use ReportExport
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,8 +1,19 @@
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
+
from django.test import SimpleTestCase
+
from corehq.apps.userreports.reports.view import ConfigurableReportView
+from corehq.apps.userreports.reports.util import ReportExport
+
+
+class VeryFakeReportExport(ReportExport):
+ def __init__(self, data):
+ self._data = data
+
+ def get_table(self):
+ return self._data
class VeryFakeReportView(ConfigurableReportView):
@@ -12,8 +23,8 @@
self._data = data
@property
- def export_table(self):
- return self._data
+ def report_export(self):
+ return VeryFakeReportExport(self._data)
class ReportRenderingTest(SimpleTestCase): |
1768207c57b66812931d2586c5544c9b74446918 | peering/management/commands/update_peering_session_states.py | peering/management/commands/update_peering_session_states.py | import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = "Update peering session states for Internet Exchanges."
logger = logging.getLogger("peering.manager.peering")
def handle(self, *args, **options):
self.logger.info("Updating peering session states...")
internet_exchanges = InternetExchange.objects.all()
for internet_exchange in internet_exchanges:
internet_exchange.update_peering_session_states()
| import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = "Update peering session states for Internet Exchanges."
logger = logging.getLogger("peering.manager.peering")
def handle(self, *args, **options):
self.logger.info("Updating peering session states...")
internet_exchanges = InternetExchange.objects.all()
for internet_exchange in internet_exchanges:
internet_exchange.poll_peering_sessions()
| Fix command polling sessions for IX. | Fix command polling sessions for IX.
| Python | apache-2.0 | respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager | ---
+++
@@ -14,4 +14,4 @@
internet_exchanges = InternetExchange.objects.all()
for internet_exchange in internet_exchanges:
- internet_exchange.update_peering_session_states()
+ internet_exchange.poll_peering_sessions() |
8170aca01f6922ef653bceb9121eb7fc098f85de | defenses/torch/audio/input_tranformation/resampling.py | defenses/torch/audio/input_tranformation/resampling.py | import torchaudio
import librosa
# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio
T = torchaudio.transforms
# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]
audio_data = torch.tensor(audio_data).float().to(device)
# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation,
# thereby prevents an adversarial attack.
# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation")
audio_resample_1 = sample(audio_data)
# resample the audio back to 16kHz
sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation")
# Give audio_resample_2 as input to the asr model
audio_resample_2 = sample(audio_resample_1)
| import torchaudio
import librosa
# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio
T = torchaudio.transforms
# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]
audio_data = torch.tensor(audio_data).float().to(device)
# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack.
# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation")
audio_resample_1 = sample(audio_data)
# resample the audio back to 16kHz
sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation")
# Give audio_resample_2 as input to the asr model
audio_resample_2 = sample(audio_resample_1)
| Format the code to black | Format the code to black | Python | mit | cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans | ---
+++
@@ -12,8 +12,7 @@
audio_data = torch.tensor(audio_data).float().to(device)
-# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation,
-# thereby prevents an adversarial attack.
+# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack.
# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") |
2fd3123eb00c16d325a7ec25dfcb6a92872a3849 | tests/test_init.py | tests/test_init.py | import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) == True
| import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) == True
# XXX I can't get this test to work because chdir() isn't having any effect.
# I suspect it's somehow related to testing with click, but I can't figure
# out exactly why.
#
# Leaving the test in but commented because it's failing because of the
# testing environment, not the code, so having it always fail won't tell us
# anything useful. It would be nice to have it part of the suite eventually.
#
#def test_init_with_no_args(tmpdir, monkeypatch):
# monkeypatch.chdir(tmpdir.strpath)
#
# runner = CliRunner()
# result = runner.invoke(application.main, ['init'])
#
# mn_dir = tmpdir.join('.morenines').strpath
#
# assert os.path.isdir(mn_dir) == True
| Add commented-out test for init with no args | Add commented-out test for init with no args
| Python | mit | mcgid/morenines,mcgid/morenines | ---
+++
@@ -14,3 +14,22 @@
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) == True
+
+
+# XXX I can't get this test to work because chdir() isn't having any effect.
+# I suspect it's somehow related to testing with click, but I can't figure
+# out exactly why.
+#
+# Leaving the test in but commented because it's failing because of the
+# testing environment, not the code, so having it always fail won't tell us
+# anything useful. It would be nice to have it part of the suite eventually.
+#
+#def test_init_with_no_args(tmpdir, monkeypatch):
+# monkeypatch.chdir(tmpdir.strpath)
+#
+# runner = CliRunner()
+# result = runner.invoke(application.main, ['init'])
+#
+# mn_dir = tmpdir.join('.morenines').strpath
+#
+# assert os.path.isdir(mn_dir) == True |
88d65d4f9cf41bbc5b080fd4245a3a6d81c1ef46 | queen/helpers/__init__.py | queen/helpers/__init__.py | import serial
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
port.write('0;1;0;\n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
return drones | import serial
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
port.write('0;1;0; \n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
return drones | Add space for empty string. | Add space for empty string.
| Python | mit | kalail/queen,kalail/queen | ---
+++
@@ -2,11 +2,11 @@
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
- port.write('0;1;0;\n')
+ port.write('0;1;0; \n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
-
+
return drones |
0f047cded957bc67441a9acd65b46fab4bac6302 | SUASImageParser/ADLC/characteristic_identifier.py | SUASImageParser/ADLC/characteristic_identifier.py | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
Identifies the characteristics of the target "target" and returns
them as a dictionary object
"""
# My thoughts so far to accomplish this is to break the problem down
# into the following tasks:
# 1) Segmentation
# 2) OCR
# 3) Pixhawk log parse to gather data about
# 3a) GPS
# 3b) Heading
# I'm not really sure how to implement this process, which is why I am
# leaving it in this comment as a "stub" which needs to be resolved.
# Returning the characteristics for each target
return {}
def segment(self, target):
"""
Separate different important aspects of the image out. This is
to extract the letter within the image
"""
# @TODO: Implement segmentation here
return target
def OCR(self, target):
"""
Use OCR to identify the character within the image "target"
"""
# @TODO: Implement OCR here
return "" | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
Identifies the characteristics of the target "target" and returns
them as a dictionary object
"""
# My thoughts so far to accomplish this is to break the problem down
# into the following tasks:
# 1) Segmentation
# 2) OCR
# I'm not really sure how to implement this process, which is why I am
# leaving it in this comment as a "stub" which needs to be resolved.
# Returning the characteristics for each target
return {}
def segment(self, target):
"""
Separate different important aspects of the image out. This is
to extract the letter within the image
"""
# @TODO: Implement segmentation here
return target
def OCR(self, target):
"""
Use OCR to identify the character within the image "target"
"""
# @TODO: Implement OCR here
return ""
| Remove mention of Log parser | Remove mention of Log parser
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | ---
+++
@@ -22,9 +22,6 @@
# into the following tasks:
# 1) Segmentation
# 2) OCR
- # 3) Pixhawk log parse to gather data about
- # 3a) GPS
- # 3b) Heading
# I'm not really sure how to implement this process, which is why I am
# leaving it in this comment as a "stub" which needs to be resolved.
@@ -37,7 +34,7 @@
to extract the letter within the image
"""
# @TODO: Implement segmentation here
-
+
return target
def OCR(self, target): |
c33ce5e8d998278d01310205598ceaf15b1573ab | logya/core.py | logya/core.py | # -*- coding: utf-8 -*-
from logya.content import read_all
from logya.template import init_env
from logya.util import load_yaml, paths
class Logya:
"""Object to store data such as site index and settings."""
def __init__(self, options):
"""Set required logya object properties."""
self.verbose = getattr(options, 'verbose', False)
self.paths = paths(dir_site=getattr(options, 'dir_site', None))
self.settings = load_yaml(self.paths.root.joinpath('site.yaml').read_text())
# Initialize template env and globel variables.
init_env(self.settings, self.index)
self.template_vars = self.settings['site']
def build_index(self):
"""Build index of documents and collections."""
self.index = read_all(self.settings)
def write_index(self):
pass
def info(self, msg):
"""Print message if in verbose mode."""
if self.verbose:
print(msg)
| # -*- coding: utf-8 -*-
from logya.content import read_all
from logya.template import init_env
from logya.util import load_yaml, paths
class Logya:
"""Object to store data such as site index and settings."""
def __init__(self, options):
"""Set required logya object properties."""
self.verbose = getattr(options, 'verbose', False)
self.paths = paths(dir_site=getattr(options, 'dir_site', None))
self.settings = load_yaml(self.paths.root.joinpath('site.yaml').read_text())
def build(self):
"""Build index of documents and collections."""
self.index = read_all(self.paths, self.settings)
# Initialize template env and global variables.
init_env(self.settings, self.index)
self.template_vars = self.settings['site']
def info(self, msg):
"""Print message if in verbose mode."""
if self.verbose:
print(msg)
| Rename build_index to build and add logic to setup template env | Rename build_index to build and add logic to setup template env
| Python | mit | elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya | ---
+++
@@ -14,17 +14,14 @@
self.paths = paths(dir_site=getattr(options, 'dir_site', None))
self.settings = load_yaml(self.paths.root.joinpath('site.yaml').read_text())
- # Initialize template env and globel variables.
+ def build(self):
+ """Build index of documents and collections."""
+
+ self.index = read_all(self.paths, self.settings)
+
+ # Initialize template env and global variables.
init_env(self.settings, self.index)
self.template_vars = self.settings['site']
-
- def build_index(self):
- """Build index of documents and collections."""
-
- self.index = read_all(self.settings)
-
- def write_index(self):
- pass
def info(self, msg):
"""Print message if in verbose mode.""" |
a2cb560851cbbabab0474092f59e1700e1c93284 | tests/chainer_tests/testing_tests/test_unary_math_function_test.py | tests/chainer_tests/testing_tests/test_unary_math_function_test.py | import unittest
from chainer import testing
class Dummy(object):
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(Dummy()) # no numpy.dummy
testing.run_module(__name__, __file__)
| import unittest
from chainer import testing
def dummy():
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(dummy) # no numpy.dummy
testing.run_module(__name__, __file__)
| Fix test of math function testing helper. | Fix test of math function testing helper.
| Python | mit | wkentaro/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,ktnyt/chainer,niboshi/chainer,hvy/chainer,tkerola/chainer,ktnyt/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,ronekko/chainer,okuta/chainer,aonotas/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,okuta/chainer,rezoo/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,chainer/chainer,chainer/chainer,niboshi/chainer,ktnyt/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,pfnet/chainer,chainer/chainer | ---
+++
@@ -3,7 +3,7 @@
from chainer import testing
-class Dummy(object):
+def dummy():
pass
@@ -11,7 +11,7 @@
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
- testing.unary_math_function_unittest(Dummy()) # no numpy.dummy
+ testing.unary_math_function_unittest(dummy) # no numpy.dummy
testing.run_module(__name__, __file__) |
850f6af90b99756e572b06803e40f55efd6734e6 | test/test_pocket_parser.py | test/test_pocket_parser.py | import unittest
import utils
import os
import sys
import re
import subprocess
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(TOPDIR, 'lib'))
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
def test_get_cnc(self):
"""Test get_cnc() function"""
res = cryptosite.pocket_parser.get_cnc(os.path.join(TOPDIR, 'test',
'input', 'test.pdb'),
None)
self.assertEqual(len(res), 8)
self.assertEqual(res[('ILE', 9, 'A')], 0.0)
if __name__ == '__main__':
unittest.main()
| import unittest
import utils
import os
import sys
import re
import subprocess
import shutil
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
def test_get_cnc(self):
"""Test get_cnc() function"""
res = cryptosite.pocket_parser.get_cnc(os.path.join(TOPDIR, 'test',
'input', 'test.pdb'),
None)
self.assertEqual(len(res), 8)
self.assertEqual(res[('ILE', 9, 'A')], 0.0)
def test_main(self):
"""Test simple complete run of pocket_parser"""
with utils.temporary_working_directory() as tmpdir:
shutil.copy(os.path.join(TOPDIR, 'test', 'input',
'pm.pdb.B10010001.pdb'), '.')
with open('SnapList.txt', 'w') as fh:
fh.write("pm.pdb.B10010001.pdb -100.0\n")
fh.write("high-energy.pdb -10.0\n")
subprocess.check_call(['cryptosite', 'pocket_parser'])
with open('pockets.out') as fh:
lines = fh.readlines()
self.assertEqual(len(lines), 13)
self.assertEqual(lines[1], 'ALA\t1\tA\t0.0\n')
self.assertEqual(lines[2], 'MET\t2\tA\t0.092\n')
if __name__ == '__main__':
unittest.main()
| Test simple complete run of pocket_parser. | Test simple complete run of pocket_parser.
| Python | lgpl-2.1 | salilab/cryptosite,salilab/cryptosite,salilab/cryptosite | ---
+++
@@ -4,9 +4,10 @@
import sys
import re
import subprocess
+import shutil
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
-sys.path.append(os.path.join(TOPDIR, 'lib'))
+utils.set_search_paths(TOPDIR)
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
@@ -19,5 +20,20 @@
self.assertEqual(len(res), 8)
self.assertEqual(res[('ILE', 9, 'A')], 0.0)
+ def test_main(self):
+ """Test simple complete run of pocket_parser"""
+ with utils.temporary_working_directory() as tmpdir:
+ shutil.copy(os.path.join(TOPDIR, 'test', 'input',
+ 'pm.pdb.B10010001.pdb'), '.')
+ with open('SnapList.txt', 'w') as fh:
+ fh.write("pm.pdb.B10010001.pdb -100.0\n")
+ fh.write("high-energy.pdb -10.0\n")
+ subprocess.check_call(['cryptosite', 'pocket_parser'])
+ with open('pockets.out') as fh:
+ lines = fh.readlines()
+ self.assertEqual(len(lines), 13)
+ self.assertEqual(lines[1], 'ALA\t1\tA\t0.0\n')
+ self.assertEqual(lines[2], 'MET\t2\tA\t0.092\n')
+
if __name__ == '__main__':
unittest.main() |
8680eac07c50546968c1525642cab41c1c99a6b3 | {{cookiecutter.repo_name}}/pages/context_processors.py | {{cookiecutter.repo_name}}/pages/context_processors.py | from django.contrib.sites.shortcuts import get_current_site
from urlparse import urljoin
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, site.domain),
'site_name': site.name
} | from django.contrib.sites.shortcuts import get_current_site
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, site.domain),
'site_name': site.name
} | Remove urlparse import as not used and also renamed in Python 3 to urllib.parse | Remove urlparse import as not used and also renamed in Python 3 to urllib.parse
| Python | mit | Parbhat/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,chrisdev/wagtail-cookiecutter-foundation,chrisdev/wagtail-cookiecutter-foundation,chrisdev/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation | ---
+++
@@ -1,5 +1,5 @@
from django.contrib.sites.shortcuts import get_current_site
-from urlparse import urljoin
+
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request) |
ffab97ff91366f9045503853198126f1b965e83e | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | Remove square brackets around log level in log ouput | Remove square brackets around log level in log ouput
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -18,8 +18,8 @@
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
-formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
-formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
+formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
+formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
|
23c1413c14a81ee40bbb0bb3adeb20e1a231b9c5 | saleor/data_feeds/urls.py | saleor/data_feeds/urls.py | from django.conf.urls import url
from django.views.generic.base import RedirectView
from .google_merchant import get_feed_file_url
urlpatterns = [
url(r'google/$', RedirectView.as_view(
get_redirect_url=get_feed_file_url), name='google-feed')]
| from django.conf.urls import url
from django.views.generic.base import RedirectView
from .google_merchant import get_feed_file_url
urlpatterns = [
url(r'google/$', RedirectView.as_view(
get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')]
| Update feeds url due to RemovedInDjango19Warning | Update feeds url due to RemovedInDjango19Warning
| Python | bsd-3-clause | jreigel/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,KenMutemi/saleor,tfroehlich82/saleor,UITools/saleor,jreigel/saleor,car3oon/saleor,mociepka/saleor,car3oon/saleor,maferelo/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,tfroehlich82/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,KenMutemi/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,maferelo/saleor,tfroehlich82/saleor,mociepka/saleor,jreigel/saleor,itbabu/saleor,mociepka/saleor | ---
+++
@@ -5,4 +5,4 @@
urlpatterns = [
url(r'google/$', RedirectView.as_view(
- get_redirect_url=get_feed_file_url), name='google-feed')]
+ get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')] |
3157a749cb7f4704e3fe4c949ee80772a9ed8eb3 | samples/debugging/main.py | samples/debugging/main.py | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apiclient.discovery import build
from apiclient.model import LoggingJsonModel
FLAGS = gflags.FLAGS
FLAGS.dump_request_response = True
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
service = build('translate', 'v2',
developerKey='AIzaSyAQIKv_gwnob-YNrXV2stnY86GSGY81Zr0',
model=LoggingJsonModel())
print service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
).execute()
if __name__ == '__main__':
main(sys.argv)
| #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apiclient.discovery import build
from apiclient.model import LoggingJsonModel
FLAGS = gflags.FLAGS
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
service = build('translate', 'v2',
developerKey='AIzaSyAQIKv_gwnob-YNrXV2stnY86GSGY81Zr0',
model=LoggingJsonModel())
print service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
).execute()
if __name__ == '__main__':
main(sys.argv)
| Update sample to reflect final destination in wiki documentation. | Update sample to reflect final destination in wiki documentation.
| Python | apache-2.0 | googleapis/google-api-python-client,jonparrott/oauth2client,googleapis/oauth2client,google/oauth2client,jonparrott/oauth2client,google/oauth2client,googleapis/google-api-python-client,clancychilds/oauth2client,clancychilds/oauth2client,googleapis/oauth2client | ---
+++
@@ -21,12 +21,17 @@
FLAGS = gflags.FLAGS
-FLAGS.dump_request_response = True
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
+ try:
+ argv = FLAGS(argv)
+ except gflags.FlagsError, e:
+ print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
+ sys.exit(1)
+
service = build('translate', 'v2',
developerKey='AIzaSyAQIKv_gwnob-YNrXV2stnY86GSGY81Zr0',
model=LoggingJsonModel()) |
6de2bd60922c012ae3ec179a49aaff950018076d | snactor/utils/variables.py | snactor/utils/variables.py | def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
gen = gen[part]
gen[parts[-1]] = value
return data[parts[0]]
def resolve_variable_spec(data, spec):
if data and spec.startswith('@') and spec.endswith('@'):
for element in spec.strip('@').split('.'):
data = data.get(element, None)
if not data:
break
if not data:
raise ValueError("unresolved reference: {}".format(spec.strip("@")))
return data
return spec
| def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
gen = gen[part]
gen[parts[-1]] = value
return data[parts[0]]
def resolve_variable_spec(data, spec):
if data and spec.startswith('@') and spec.endswith('@'):
for element in spec.strip('@').split('.'):
data = data.get(element, None)
if not data:
break
if data is None:
raise ValueError("unresolved reference: {}".format(spec.strip("@")))
return data
return spec
| Allow empty data in value | Allow empty data in value
| Python | apache-2.0 | leapp-to/snactor | ---
+++
@@ -17,7 +17,7 @@
data = data.get(element, None)
if not data:
break
- if not data:
+ if data is None:
raise ValueError("unresolved reference: {}".format(spec.strip("@")))
return data
return spec |
b3540f744efbcb0f14f9b4081aeffda1f5ccae3c | pyscraper/patchfilter.py | pyscraper/patchfilter.py | #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
print "Error running 'patch' on file %s, blanking it out" % fileshort
os.rename(patchfile, patchfile + ".old~")
blankfile = open(patchfile, "w")
blankfile.close()
| #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
raise Exception, "Error running 'patch' on file %s" % fileshort
#print "blanking out %s" % fileshort
#os.rename(patchfile, patchfile + ".old~")
#blankfile = open(patchfile, "w")
#blankfile.close()
| Remove code which blanks patch files | Remove code which blanks patch files
| Python | agpl-3.0 | mysociety/publicwhip,mysociety/publicwhip,mysociety/publicwhip | ---
+++
@@ -29,9 +29,11 @@
if status == 0:
return True
- print "Error running 'patch' on file %s, blanking it out" % fileshort
- os.rename(patchfile, patchfile + ".old~")
- blankfile = open(patchfile, "w")
- blankfile.close()
+ raise Exception, "Error running 'patch' on file %s" % fileshort
+
+ #print "blanking out %s" % fileshort
+ #os.rename(patchfile, patchfile + ".old~")
+ #blankfile = open(patchfile, "w")
+ #blankfile.close()
|
1eff8a7d89fd3d63f020200207d87213f6182b22 | elasticsearch_flex/management/commands/flex_sync.py | elasticsearch_flex/management/commands/flex_sync.py | # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch import exceptions
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
def add_arguments(self, parser):
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
default=False,
help='Delete existing index',
)
def handle(self, delete, *args, **options):
indices = registered_indices()
connection = connections.get_connection()
hues.info('Using connection', connection)
if len(indices):
hues.info('Discovered', len(indices), 'Indexes')
else:
hues.warn('No search index found')
for i, index in enumerate(indices, 1):
hues.info('==> Initializing', index.__name__)
index_name = index._doc_type.index
try:
connection.indices.close(index_name)
if delete:
hues.warn('Deleting existing index.')
connection.indices.delete(index_name)
except exceptions.NotFoundError:
pass
index.init()
connection.indices.open(index_name)
hues.success('--> Done {0}/{1}'.format(i, len(indices)))
| # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
def add_arguments(self, parser):
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
default=False,
help='Delete existing index',
)
def handle(self, delete, *args, **options):
indices = registered_indices()
connection = connections.get_connection()
hues.info('Using connection', connection)
if len(indices):
hues.info('Discovered', len(indices), 'Indexes')
else:
hues.warn('No search index found')
for i, index in enumerate(indices, 1):
hues.info('==> Initializing', index.__name__)
with index().ensure_closed_and_reopened() as ix:
if delete:
hues.warn('Deleting existing index.')
ix.delete()
ix.init()
hues.success('--> Done {0}/{1}'.format(i, len(indices)))
| Use index context manager for sync | Use index context manager for sync
| Python | mit | prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex | ---
+++
@@ -3,7 +3,6 @@
from django.core.management.base import BaseCommand
-from elasticsearch import exceptions
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
@@ -31,15 +30,10 @@
for i, index in enumerate(indices, 1):
hues.info('==> Initializing', index.__name__)
- index_name = index._doc_type.index
- try:
- connection.indices.close(index_name)
+ with index().ensure_closed_and_reopened() as ix:
if delete:
hues.warn('Deleting existing index.')
- connection.indices.delete(index_name)
- except exceptions.NotFoundError:
- pass
- index.init()
- connection.indices.open(index_name)
+ ix.delete()
+ ix.init()
hues.success('--> Done {0}/{1}'.format(i, len(indices))) |
9742e372a6ccca843120cb5b4e8135033d30cdd6 | cauth/controllers/root.py | cauth/controllers/root.py | #!/usr/bin/env python
#
# Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from pecan import expose, response, conf
from pecan.rest import RestController
from cauth.controllers import base, github, introspection
from cauth.utils.common import LOGOUT_MSG
logger = logging.getLogger(__name__)
class LogoutController(RestController):
@expose(template='login.html')
def get(self, **kwargs):
response.delete_cookie('auth_pubtkt', domain=conf.app.cookie_domain)
return dict(back='/', message=LOGOUT_MSG)
class RootController(object):
login = base.BaseLoginController()
login.github = github.GithubController()
login.githubAPIkey = github.PersonalAccessTokenGithubController()
about = introspection.IntrospectionController()
logout = LogoutController()
| #!/usr/bin/env python
#
# Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from pecan import expose, response, conf
from pecan.rest import RestController
from cauth.auth import base as exceptions
from cauth.controllers import base, github, introspection
from cauth.utils.common import LOGOUT_MSG
logger = logging.getLogger(__name__)
class LogoutController(RestController):
@expose(template='login.html')
def get(self, **kwargs):
response.delete_cookie('auth_pubtkt', domain=conf.app.cookie_domain)
return dict(back='/', message=LOGOUT_MSG)
class RootController(object):
login = base.BaseLoginController()
try:
login.github = github.GithubController()
login.githubAPIkey = github.PersonalAccessTokenGithubController()
except exceptions.AuthProtocolNotAvailableError as e:
logger.error("%s - skipping callback endpoint" % e.message)
about = introspection.IntrospectionController()
logout = LogoutController()
| Fix app crashing at startup if some auth methods are not configured | Fix app crashing at startup if some auth methods are not configured
Change-Id: I201dbc646c6da39c5923a086a0498b7ccb854982
| Python | apache-2.0 | redhat-cip/cauth,enovance/cauth,redhat-cip/cauth,redhat-cip/cauth,enovance/cauth,enovance/cauth | ---
+++
@@ -19,6 +19,7 @@
from pecan import expose, response, conf
from pecan.rest import RestController
+from cauth.auth import base as exceptions
from cauth.controllers import base, github, introspection
from cauth.utils.common import LOGOUT_MSG
@@ -35,8 +36,11 @@
class RootController(object):
login = base.BaseLoginController()
- login.github = github.GithubController()
- login.githubAPIkey = github.PersonalAccessTokenGithubController()
+ try:
+ login.github = github.GithubController()
+ login.githubAPIkey = github.PersonalAccessTokenGithubController()
+ except exceptions.AuthProtocolNotAvailableError as e:
+ logger.error("%s - skipping callback endpoint" % e.message)
about = introspection.IntrospectionController()
logout = LogoutController() |
5ef8b09a055326e2a92c9eccbcb187fa5362fb95 | zipa/magic.py | zipa/magic.py | from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
self.self_module = self_module
self.env = globals()
def __setattr__(self, name, value):
if hasattr(self, "env"):
self.env[name] = value
ModuleType.__setattr__(self, name, value)
def __getattr__(self, name):
if name == "env":
raise AttributeError
if name not in self.env:
host, prefix = self._parse_name(name)
self.env[name] = Resource()
self.env[name].config.host = host
self.env[name].config.prefix = prefix
return self.env[name]
def _parse_name(self, name):
parts = name.split('__')
host = parts[0].replace('_', '.')
prefix = '/'
if len(parts) > 1:
prefix = '/' + parts[1].replace('_', '/') + '/'
return host, prefix
| from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
self.self_module = self_module
self.env = globals()
def __setattr__(self, name, value):
if hasattr(self, "env"):
self.env[name] = value
ModuleType.__setattr__(self, name, value)
def __getattr__(self, name):
if name == "env":
raise AttributeError
if name not in self.env:
host, prefix = self._parse_name(name)
self.env[name] = Resource()
self.env[name].config.host = host
self.env[name].config.prefix = prefix
return self.env[name]
def _parse_name(self, name):
name = name.replace('___', '-')
parts = name.split('__')
host = parts[0].replace('_', '.')
prefix = '/'
if len(parts) > 1:
prefix = '/' + parts[1].replace('_', '/') + '/'
return host, prefix
| Add possibility of using apis with dashes without any workarounds | Add possibility of using apis with dashes without any workarounds
| Python | apache-2.0 | PressLabs/zipa | ---
+++
@@ -28,6 +28,7 @@
return self.env[name]
def _parse_name(self, name):
+ name = name.replace('___', '-')
parts = name.split('__')
host = parts[0].replace('_', '.')
prefix = '/' |
689d1d1f128b4a72aad6783ea2f770c21cd4c2da | queryset_transform/__init__.py | queryset_transform/__init__.py | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns
return c
def transform(self, fn):
self._transform_fns.append(fn)
return self
def iterator(self):
result_iter = super(TransformQuerySet, self).iterator()
if self._transform_fns:
results = list(result_iter)
for fn in self._transform_fns:
fn(results)
return iter(results)
return result_iter
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
| from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
c = self._clone()
c._transform_fns.append(fn)
return c
def iterator(self):
for item in super(TransformQuerySet, self).iterator()
for func in self._transform_fns:
func(item)
yield item
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
| Refactor the ever living hell out of this. | Refactor the ever living hell out of this. | Python | bsd-3-clause | alex/django-queryset-transform | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
@@ -7,23 +8,20 @@
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
- c._transform_fns = self._transform_fns
+ c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
- self._transform_fns.append(fn)
- return self
+ c = self._clone()
+ c._transform_fns.append(fn)
+ return c
def iterator(self):
- result_iter = super(TransformQuerySet, self).iterator()
- if self._transform_fns:
- results = list(result_iter)
- for fn in self._transform_fns:
- fn(results)
- return iter(results)
- return result_iter
+ for item in super(TransformQuerySet, self).iterator()
+ for func in self._transform_fns:
+ func(item)
+ yield item
class TransformManager(models.Manager):
-
def get_query_set(self):
return TransformQuerySet(self.model) |
fa0c63b37bd010f73fede319b5e2755fe1bfbd7c | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| Add utility function for retrieving the active registration backend. | Add utility function for retrieving the active registration backend.
| Python | bsd-3-clause | ratio/django-registration,danielsokolowski/django-registration,stefankoegl/django-couchdb-utils,ogirardot/django-registration,wuyuntao/django-registration,stefankoegl/django-registration-couchdb,bruth/django-registration2,stefankoegl/django-registration-couchdb,wuyuntao/django-registration,schmidsi/django-registration,stefankoegl/django-registration-couchdb,stefankoegl/django-couchdb-utils,stefankoegl/django-couchdb-utils,andresdouglas/django-registration,danielsokolowski/django-registration,ogirardot/django-registration | ---
+++
@@ -0,0 +1,23 @@
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
+def get_backend():
+ """
+ Return an instance of the registration backend for use on this
+ site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
+ ``django.core.exceptions.ImproperlyConfigured`` if the specified
+ backend cannot be located.
+
+ """
+ i = settings.REGISTRATION_BACKEND.rfind('.')
+ module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
+ try:
+ mod = import_module(module)
+ except ImportError, e:
+ raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
+ try:
+ backend_class = getattr(mod, attr)
+ except AttributeError:
+ raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
+ return backend_class() | |
4169f60ce8fa6666b28a1129845c816889a6459a | chef/tests/__init__.py | chef/tests/__init__.py | import os
import random
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
"""Base class for Chef unittests."""
def setUp(self):
super(ChefTestCase, self).setUp()
self.api = test_chef_api()
self.api.set_default()
def random(self, length=8, alphabet='0123456789abcdef'):
return ''.join(random.choice(alphabet) for _ in xrange(length))
| import os
import random
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
"""Base class for Chef unittests."""
def setUp(self):
super(ChefTestCase, self).setUp()
self.api = test_chef_api()
self.api.set_default()
self.objects = []
def tearDown(self):
for obj in self.objects:
try:
obj.delete()
except ChefError, e:
print e
# Continue running
def register(self, obj):
self.objects.append(obj)
def random(self, length=8, alphabet='0123456789abcdef'):
return ''.join(random.choice(alphabet) for _ in xrange(length))
| Add a system for tests to register objects for deletion. | Add a system for tests to register objects for deletion.
They should be deleted no matter the outcome of
the test. | Python | apache-2.0 | coderanger/pychef,jarosser06/pychef,jarosser06/pychef,Scalr/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,dipakvwarade/pychef,cread/pychef | ---
+++
@@ -18,6 +18,18 @@
super(ChefTestCase, self).setUp()
self.api = test_chef_api()
self.api.set_default()
+ self.objects = []
+
+ def tearDown(self):
+ for obj in self.objects:
+ try:
+ obj.delete()
+ except ChefError, e:
+ print e
+ # Continue running
+
+ def register(self, obj):
+ self.objects.append(obj)
def random(self, length=8, alphabet='0123456789abcdef'):
return ''.join(random.choice(alphabet) for _ in xrange(length)) |
44d701eea86f9c2152368f64e54c012cdb937bb1 | alexandria/views/home.py | alexandria/views/home.py | from pyramid.view import (
view_config,
notfound_view_config,
)
# Always send the default index.html
@notfound_view_config(renderer='templates/index.mako', accept='text/html')
@view_config(renderer='templates/index.mako', accept='text/html')
def index(request):
return {}
| from pyramid.view import (
view_config,
notfound_view_config,
)
# Always send the default index.html
@notfound_view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
@view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
def index(request):
return {}
| Verify X-Requested-With is not set | Verify X-Requested-With is not set
| Python | isc | bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria | ---
+++
@@ -4,8 +4,8 @@
)
# Always send the default index.html
-@notfound_view_config(renderer='templates/index.mako', accept='text/html')
-@view_config(renderer='templates/index.mako', accept='text/html')
+@notfound_view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
+@view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
def index(request):
return {}
|
0b00187083b29a38eaf949e41824dcb9fd72f48c | amazonproduct/version.py | amazonproduct/version.py |
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
VERSION = '0.3'
|
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
VERSION = '0.3-dev'
| Mark as dev release until 0.3 is ready. | Mark as dev release until 0.3 is ready.
| Python | bsd-3-clause | redtoad/python-amazon-product-api,redtoad/python-amazon-product-api,redtoad/python-amazon-product-api | ---
+++
@@ -1,5 +1,5 @@
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
-VERSION = '0.3'
+VERSION = '0.3-dev'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.