commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e924f67b37c1a7612e520cca9715152029ddf338
test/integration/ggrc/services/test_query_snapshots.py
test/integration/ggrc/services/test_query_snapshots.py
# coding: utf-8 # Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests for /query api endpoint.""" from datetime import datetime from operator import itemgetter from flask import json from nose.plugins.skip import SkipTest from ggrc import db from ggrc import views from ggrc.models import CustomAttributeDefinition as CAD from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" # we don't call super as TestCase.setUp clears the DB # super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): audit = factories.AuditFactory() factories.MarketFactory() factories.MarketFactory() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
# coding: utf-8 # Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests for /query api endpoint.""" from ggrc import views from ggrc import models from integration.ggrc.converters import TestCase from integration.ggrc.models import factories class BaseQueryAPITestCase(TestCase): """Base class for /query api tests with utility methods.""" def setUp(self): """Log in before performing queries.""" super(BaseQueryAPITestCase, self).setUp() self.client.get("/login") def _setup_objects(self): text_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", ) date_cad = factories.CustomAttributeDefinitionFactory( definition_type="market", attribute_type="Text", ) audit = factories.AuditFactory() for i in range(5): market = factories.MarketFactory() factories.CustomAttributeValueFactory( custom_attribute=date_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) factories.CustomAttributeValueFactory( custom_attribute=text_cad, attributable=market, attribute_value="2016-11-0{}".format(i + 1), ) revisions = models.Revision.query.filter( models.Revision.resource_type == "Market") self.snapshots = [ factories.SnapshotFactory( child_id=revision.resource_id, child_type=revision.resource_type, revision=revision, parent=audit, ) for revision in revisions ] views.do_reindex() def test_basic_query_in(self): """Filter by ~ operator.""" self._setup_objects()
Update snapshot query test generation
Update snapshot query test generation
Python
apache-2.0
selahssea/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core
aaa3f6b8154f03eab16528c05d889c6160e63f22
server/siege/views/devices.py
server/siege/views/devices.py
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): new_device = Device(comment=request.access_route) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): comment = '%s, %s' % (request.remote_addr, request.user_agent) new_device = Device(comment=comment) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
Put the user agent in the device object
Put the user agent in the device object
Python
bsd-2-clause
WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege,WalterCReel3/siege
95d0461cf2f06534f81a954b1f95658cbb019ec6
tests/startsymbol_tests/NonterminalNotInGrammarTest.py
tests/startsymbol_tests/NonterminalNotInGrammarTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 10.08.2017 23:20 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class NonterminalNotInGrammarTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 10.08.2017 23:20 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import * from grammpy.exceptions import NonterminalDoesNotExistsException class A(Nonterminal): pass class B(Nonterminal): pass class NonterminalNotInGrammarTest(TestCase): def test_shouldNotSetStartSymbol(self): g = Grammar(nonterminals=[A]) self.assertFalse(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertFalse(g.start_isSet()) self.assertFalse(g.start_is(B)) def test_shouldNotSetStartSymbolWhenCreate(self): with self.assertRaises(NonterminalDoesNotExistsException): g = Grammar(nonterminals=[B], start_symbol=A) def test_oldStartSymbolShouldStaySame(self): g = Grammar(nonterminals=[A], start_symbol=A) self.assertTrue(g.start_isSet()) with self.assertRaises(NonterminalDoesNotExistsException): g.start_set(B) self.assertTrue(g.start_isSet()) self.assertTrue(g.start_is(A)) self.assertEqual(g.start_get(), A) if __name__ == '__main__': main()
Add tests of setting nonterminal, which is not in grammar, as start symbol
Add tests of setting nonterminal, which is not in grammar, as start symbol
Python
mit
PatrikValkovic/grammpy
7e88a5d648d8e9aec82be14cd55667136adb3754
pytest-{{cookiecutter.plugin_name}}/test_{{cookiecutter.plugin_name}}.py
pytest-{{cookiecutter.plugin_name}}/test_{{cookiecutter.plugin_name}}.py
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): testdir.tmpdir.join('test_foo.py').write(''' def test_a(bar): assert bar == "something" ''' result = testdir.runpytest('--foo=something') def test_foo_option(): pass
# -*- coding: utf-8 -*- def test_bar_fixture(testdir): """Make sure that pytest accepts our fixture.""" # create a temporary pytest test module testdir.makepyfile(""" def test_sth(bar): assert bar == "europython2015" """) # run pytest with the following cmd args result = testdir.runpytest( '--foo=something', '-v' ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ '*::test_a PASSED', ]) # make sure that that we get a '0' exit code for the testsuite assert result.ret == 0 def test_help_message(testdir): result = testdir.runpytest( '--help', ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ 'cat:', '*--foo=DEST_FOO*Set the value for the fixture "bar".', ])
Implement test for help and cli args
Implement test for help and cli args
Python
mit
luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin
9dad4033e4a66208ca00bcb0340f6a2271f1090f
montage_wrapper/mpi.py
montage_wrapper/mpi.py
MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
MPI_COMMAND = 'mpirun -n {n_proc} {executable}' def set_mpi_command(command): """ Set the MPI Command to use. This should contain {n_proc} to indicate the number of processes, and {executable} to indicate the name of the executable. Parameters ---------- command: str The MPI command for running executables Examples -------- Use ``mpirun``: >>> set_mpi_command('mpirun -n {n_proc} {executable}') Use ``mpiexec`` with host list: >>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}') """ global MPI_COMMAND MPI_COMMAND = command def _get_mpi_command(executable=None, n_proc=None): return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
Fix setting of custom MPI command
Fix setting of custom MPI command
Python
bsd-3-clause
vterron/montage-wrapper,astrofrog/montage-wrapper,astropy/montage-wrapper,astrofrog/montage-wrapper,jat255/montage-wrapper
a09689c570e70c80ad7cadd9702133b3851c63b9
providers/provider.py
providers/provider.py
import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector): html = self._http_get(url) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None): data = self._http_get(url) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60 * 60): response = requests.get(url, timeout=10) return get_unicode_from_response(response)
import json import requests from requests.utils import get_unicode_from_response from lxml import html as lxml_html class BaseProvider(object): # ==== HELPER METHODS ==== def parse_html(self, url, css_selector, timeout=60): html = self._http_get(url, timeout=timeout) document = lxml_html.document_fromstring(html) results = document.cssselect(css_selector) data = [result.text_content() for result in results] return data def traverse_json(self, data, path): if not path: return data for item in path.split("."): if item.isdigit(): item = int(item) try: data = data[item] except (IndexError, KeyError): return {} return data def parse_json(self, url, path=None, timeout=60): data = self._http_get(url, timeout=timeout) data = json.loads(data) data = self.traverse_json(data, path) return data # ==== PRIVATE METHODS ==== def _http_get(self, url, timeout=60): response = requests.get(url, timeout=timeout) return get_unicode_from_response(response)
Increase timeout to 60 sec and make available to external callers.
Increase timeout to 60 sec and make available to external callers.
Python
mit
EmilStenstrom/nephele
a229e1737542a5011e70c3fa63c360638e96e754
lettuce_webdriver/css_selector_steps.py
lettuce_webdriver/css_selector_steps.py
from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, xpath, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(xpath) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) #elems = wait_for_elem(world.browser, selector, seconds) #assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
import time from lettuce import step from lettuce import world from lettuce_webdriver.util import assert_true from lettuce_webdriver.util import assert_false import logging log = logging.getLogger(__name__) def wait_for_elem(browser, sel, timeout=15): start = time.time() elems = [] while time.time() - start < timeout: elems = browser.find_elements_by_css_selector(sel) if elems: return elems time.sleep(0.2) return elems @step(r'There should be an element matching \$\("(.*?)"\) within (\d+) seconds?') def wait_for_element_by_selector(step, selector, seconds): log.error(selector) elems = wait_for_elem(world.browser, selector, seconds) assert_true(step, elems) __all__ = ['wait_for_element_by_selector']
Make the step actually do something.
Make the step actually do something.
Python
mit
koterpillar/aloe_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,ponsfrilus/lettuce_webdriver,aloetesting/aloe_webdriver,macndesign/lettuce_webdriver,infoxchange/aloe_webdriver,bbangert/lettuce_webdriver,aloetesting/aloe_webdriver,koterpillar/aloe_webdriver,infoxchange/lettuce_webdriver,infoxchange/aloe_webdriver,infoxchange/lettuce_webdriver,ponsfrilus/lettuce_webdriver,bbangert/lettuce_webdriver
6926ddbb9cdbf05808339412cee5106e581f66cb
tests/import_wordpress_and_build_workflow.py
tests/import_wordpress_and_build_workflow.py
# -*- coding: utf-8 -*- """ Script to test the import workflow. It will remove an existing Nikola installation and then install from the package directory. After that it will do create a new site with the import_wordpress command and use that newly created site to make a build. """ from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Script to test the import workflow. It will remove an existing Nikola installation and then install from the package directory. After that it will do create a new site with the import_wordpress command and use that newly created site to make a build. """ from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
Use the more or less new options for importing
Use the more or less new options for importing
Python
mit
damianavila/nikola,xuhdev/nikola,getnikola/nikola,berezovskyi/nikola,TyberiusPrime/nikola,kotnik/nikola,atiro/nikola,servalproject/nikola,gwax/nikola,schettino72/nikola,kotnik/nikola,lucacerone/nikola,okin/nikola,s2hc-johan/nikola,andredias/nikola,masayuko/nikola,x1101/nikola,s2hc-johan/nikola,Proteus-tech/nikola,techdragon/nikola,jjconti/nikola,berezovskyi/nikola,techdragon/nikola,servalproject/nikola,masayuko/nikola,getnikola/nikola,immanetize/nikola,damianavila/nikola,jjconti/nikola,knowsuchagency/nikola,wcmckee/nikola,JohnTroony/nikola,xuhdev/nikola,getnikola/nikola,masayuko/nikola,andredias/nikola,gwax/nikola,knowsuchagency/nikola,damianavila/nikola,berezovskyi/nikola,TyberiusPrime/nikola,wcmckee/nikola,pluser/nikola,okin/nikola,schettino72/nikola,xuhdev/nikola,okin/nikola,x1101/nikola,TyberiusPrime/nikola,JohnTroony/nikola,wcmckee/nikola,atiro/nikola,lucacerone/nikola,yamila-moreno/nikola,Proteus-tech/nikola,x1101/nikola,lucacerone/nikola,kotnik/nikola,jjconti/nikola,JohnTroony/nikola,xuhdev/nikola,atiro/nikola,knowsuchagency/nikola,immanetize/nikola,Proteus-tech/nikola,gwax/nikola,techdragon/nikola,getnikola/nikola,pluser/nikola,s2hc-johan/nikola,immanetize/nikola,schettino72/nikola,servalproject/nikola,Proteus-tech/nikola,yamila-moreno/nikola,okin/nikola,andredias/nikola,pluser/nikola,yamila-moreno/nikola
48394c55599968c456f1f58c0fcdf58e1750f293
amplpy/tests/TestBase.py
amplpy/tests/TestBase.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def str2file(self, filename, content): fullpath = self.tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return fullpath def tmpfile(self, filename): return os.path.join(self.dirpath, filename) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from builtins import map, range, object, zip, sorted from .context import amplpy import unittest import tempfile import shutil import os # For MSYS2, MINGW, etc., run with: # $ REAL_ROOT=`cygpath -w /` python -m amplpy.tests REAL_ROOT = os.environ.get('REAL_ROOT', None) class TestBase(unittest.TestCase): def setUp(self): self.ampl = amplpy.AMPL() self.dirpath = tempfile.mkdtemp() def _tmpfile(self, filename): return os.path.join(self.dirpath, filename) def _real_filename(self, filename): # Workaround for MSYS2, MINGW paths if REAL_ROOT is not None and filename.startswith('/'): filename = filename.replace('/', REAL_ROOT, 1) return filename def str2file(self, filename, content): fullpath = self._tmpfile(filename) with open(fullpath, 'w') as f: print(content, file=f) return self._real_filename(fullpath) def tmpfile(self, filename): return self._real_filename(self._tmpfile(filename)) def tearDown(self): self.ampl.close() shutil.rmtree(self.dirpath) if __name__ == '__main__': unittest.main()
Add workaround for tests on MSYS2 and MINGW
Add workaround for tests on MSYS2 and MINGW
Python
bsd-3-clause
ampl/amplpy,ampl/amplpy,ampl/amplpy
43afda1fa0ae2d0011d6b87b5c05e3eb1fe13a21
viewer_examples/viewers/collection_viewer.py
viewer_examples/viewers/collection_viewer.py
""" ===================== CollectionViewer demo ===================== Demo of CollectionViewer for viewing collections of images. This demo uses successively darker versions of the same image to fake an image collection. You can scroll through images with the slider, or you can interact with the viewer using your keyboard: left/right arrows Previous/next image in collection. number keys, 0--9 0% to 90% of collection. For example, "5" goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. """ import numpy as np from skimage import data from skimage.viewer import CollectionViewer img = data.lena() img_collection = [np.uint8(img * 0.9**i) for i in range(20)] view = CollectionViewer(img_collection) view.show()
""" ===================== CollectionViewer demo ===================== Demo of CollectionViewer for viewing collections of images. This demo uses successively darker versions of the same image to fake an image collection. You can scroll through images with the slider, or you can interact with the viewer using your keyboard: left/right arrows Previous/next image in collection. number keys, 0--9 0% to 90% of collection. For example, "5" goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. """ import numpy as np from skimage import data from skimage.viewer import CollectionViewer from skimage.transform import build_gaussian_pyramid img = data.lena() img_collection = tuple(build_gaussian_pyramid(img)) view = CollectionViewer(img_collection) view.show()
Use gaussian pyramid function for collection viewer example
Use gaussian pyramid function for collection viewer example
Python
bsd-3-clause
rjeli/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,newville/scikit-image,SamHames/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,blink1073/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,emon10005/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,newville/scikit-image,bsipocz/scikit-image,Midafi/scikit-image,almarklein/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,chintak/scikit-image,SamHames/scikit-image,michaelaye/scikit-image,chintak/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,bennlich/scikit-image,almarklein/scikit-image,oew1v07/scikit-image,Britefury/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,blink1073/scikit-image,rjeli/scikit-image,jwiggins/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,Hiyorimi/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,bsipocz/scikit-image,ajaybhat/scikit-image,oew1v07/scikit-image,warmspringwinds/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,robintw/scikit-image,SamHames/scikit-image,paalge/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,emon10005/scikit-image,youprofit/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,dpshelio/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,WarrenWeckesser/scikits-image
710c77b2805058364e326d26c9e0c7cfcfed6453
repugeng/Compat3k.py
repugeng/Compat3k.py
from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) return sys.stdin.readline().rstrip("\r\n")
from repugeng.StaticClass import StaticClass import sys class Compat3k(StaticClass): @classmethod def str_to_bytes(cls, s): """Convert a string of either width to a byte string.""" try: try: return bytes(s) except NameError: return str(s) except ValueError: pass #Not ASCII? Not really a problem... except TypeError: pass #I didn't specify an encoding? Oh, boo hoo... return s.encode("latin1") #Not utf-8, m'kay... @classmethod def prompt_user(cls, s="", file=None): """Substitute of py2k's raw_input().""" (file or sys.stderr).write(s) (file or sys.stderr).flush() return sys.stdin.readline().rstrip("\r\n")
Fix yet another 3k issue (stderr not flushing automatically).
Fix yet another 3k issue (stderr not flushing automatically). Signed-off-by: Thomas Hori <7133b3a0da8e60bd3295f2c8559ef184054a68ed@liddicott.com>
Python
mpl-2.0
thomas-hori/Repuge-NG
c0ff6cbf293bca3f0757a62e05a14c56dbdf12a4
installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py
installscripts/jazz-terraform-unix-noinstances/scripts/health_check.py
import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
import boto3 import sys import time def health_check_tg(client, tg_arn, max_tries): if max_tries == 1: return False else: max_tries -= 1 try: response = client.describe_target_health(TargetGroupArn=str(tg_arn)) if response['TargetHealthDescriptions'][0]['TargetHealth']['State'] == 'healthy': time.sleep(30) return True else: time.sleep(30) health_check_tg(client, tg_arn, max_tries) except Exception: time.sleep(30) health_check_tg(client, tg_arn, max_tries) if __name__ == u"__main__": client = boto3.client('elbv2') health_check_tg(client, sys.argv[1], 50)
Fix travis issue for v1.13.1 release
Fix travis issue for v1.13.1 release
Python
apache-2.0
tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer
8ad795f86e16209007537cbf47a3466733653e2d
snippets/__main__.py
snippets/__main__.py
import argparse import sys from .generator import Generator from .repository import Repository def run(args=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', default='snippets') parser.add_argument('-o', '--output', default='output') parser.add_argument('-t', '--theme') args = parser.parse_args(args) repository = Repository() repository.add_repopath(args.source) generator = Generator(repository, args.theme) generator.generate(args.output) if __name__ == '__main__': run()
import argparse import sys from .generator import Generator from .repository import Repository def run(args=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument('-r', '--repository', default='snippets') parser.add_argument('-o', '--output', default='output') parser.add_argument('-t', '--theme') args = parser.parse_args(args) repository = Repository() repository.add_repopath(args.repository) generator = Generator(repository, args.theme) generator.generate(args.output) if __name__ == '__main__': run()
Fix cli argument name for repository path
Fix cli argument name for repository path
Python
isc
trilan/snippets,trilan/snippets
cd38101f097edc60312f0c083385968ed40fd54a
src/control.py
src/control.py
#!/usr/bin/env python import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose current_pose = message.pose[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
#!/usr/bin/env python import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose, current_twist current_pose = message.pose[2] current_twist = message.twist[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None current_twist = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None or current_twist is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
Store current twist in a global variable
Store current twist in a global variable
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
7d03a6bfa32d2bf20a95769b2937e098972285af
src/scs_mfr/test/opc_test.py
src/scs_mfr/test/opc_test.py
""" Created on 18 May 2017 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.OPC_SPI_BUS, Host.OPC_SPI_DEVICE) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
""" Created on 18 May 2017 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import sys from scs_dfe.particulate.opc_n2 import OPCN2 from scs_host.bus.i2c import I2C from scs_host.sys.host import Host from scs_mfr.test.test import Test # -------------------------------------------------------------------------------------------------------------------- class OPCTest(Test): """ test script """ # ---------------------------------------------------------------------------------------------------------------- def __init__(self, verbose): Test.__init__(self, verbose) # ---------------------------------------------------------------------------------------------------------------- def conduct(self): if self.verbose: print("OPC...", file=sys.stderr) opc = None try: I2C.open(Host.I2C_SENSORS) # resources... opc = OPCN2(Host.opc_spi_bus(), Host.opc_spi_device()) opc.power_on() opc.operations_on() # test... self.datum = opc.firmware() if self.verbose: print(self.datum, file=sys.stderr) # test criterion... return len(self.datum) > 0 and self.datum.startswith('OPC') finally: if opc: opc.operations_off() opc.power_off() I2C.close()
Put SPI slave configurations on Host.
Put SPI slave configurations on Host.
Python
mit
south-coast-science/scs_mfr,south-coast-science/scs_mfr
6b819174557a1dffbcb397dc1d6e2a3f7e01a12b
milestones/migrations/0002_data__seed_relationship_types.py
milestones/migrations/0002_data__seed_relationship_types.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") db_alias = schema_editor.connection.alias for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.using(db_alias).filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from milestones.data import fetch_milestone_relationship_types def seed_relationship_types(apps, schema_editor): """Seed the relationship types.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.get_or_create( name=name, description='Autogenerated milestone relationship type "{}"'.format(name), ) def delete_relationship_types(apps, schema_editor): """Clean up any relationships we made.""" MilestoneRelationshipType = apps.get_model("milestones", "MilestoneRelationshipType") for name in fetch_milestone_relationship_types().values(): MilestoneRelationshipType.objects.filter(name=name).delete() class Migration(migrations.Migration): dependencies = [ ('milestones', '0001_initial'), ] operations = [ migrations.RunPython(seed_relationship_types, delete_relationship_types), ]
Remove uses of using() from migrations
Remove uses of using() from migrations This hardcoded the db_alias fetched from schema_editor and forces django to try and migrate any second database you use, rather than routing to the default database. In testing a build from scratch, these do not appear needed. Using using() prevents us from using multiple databases behind edxapp
Python
agpl-3.0
edx/edx-milestones
6bdb91aefc6acb9b0065c7edae19887778dedb22
.ci/package-version.py
.ci/package-version.py
#!/usr/bin/env python3 import os.path import sys def main(): setup_py = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setup.py') with open(setup_py, 'r') as f: for line in f: if line.startswith('VERSION ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in setup.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python3 import os.path import sys def main(): version_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'uvloop', '__init__.py') with open(version_file, 'r') as f: for line in f: if line.startswith('__version__ ='): _, _, version = line.partition('=') print(version.strip(" \n'\"")) return 0 print('could not find package version in uvloop/__init__.py', file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())
Fix ci / package_version.py script to support __version__
Fix ci / package_version.py script to support __version__
Python
apache-2.0
1st1/uvloop,MagicStack/uvloop,MagicStack/uvloop
261cb5aecc52d07b10d826e8b22d17817d1c3529
web/backend/backend_django/apps/capacity/management/commands/importpath.py
web/backend/backend_django/apps/capacity/management/commands/importpath.py
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) for k, path in trips.items(): trip_id = k[0] stop_id = k[1] try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) self.stdout.write("Done")
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done")
Update import path method to reflect behaviour
Update import path method to reflect behaviour
Python
apache-2.0
tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project
24d7f9f05e4d597358b62a50d2d0f5fad6a61c63
package_name/__meta__.py
package_name/__meta__.py
name = "package-name" # See https://www.python.org/dev/peps/pep-0008/ path = name.lower().replace("-", "_").replace(" ", "_") version = "0.1.dev0" # https://python.org/dev/peps/pep-0440 https://semver.org author = "Author Name" author_email = "" description = "" # One-liner url = "" # your project homepage license = "MIT" # See https://choosealicense.com
# `name` is the name of the package as used for `pip install package` name = "package-name" # `path` is the name of the package for `import package` path = name.lower().replace("-", "_").replace(" ", "_") # Your version number should follow https://python.org/dev/peps/pep-0440 and # https://semver.org version = "0.1.dev0" author = "Author Name" author_email = "" description = "" # One-liner url = "" # your project homepage license = "MIT" # See https://choosealicense.com
Clarify comments on what name and path are
DOC: Clarify comments on what name and path are
Python
mit
scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-ci,scottclowe/python-continuous-integration
1869b79d49419799cecf1f5e19eb0aa3987e215b
tests/test_vector2_scalar_multiplication.py
tests/test_vector2_scalar_multiplication.py
import pytest # type: ignore from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected
import pytest # type: ignore from hypothesis import given from hypothesis.strategies import floats from utils import vectors from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected @given( x=floats(min_value=-1e75, max_value=1e75), y=floats(min_value=-1e75, max_value=1e75), v=vectors(max_magnitude=1e150) ) def test_scalar_associative(x: float, y: float, v: Vector2): left = (x * y) * v right = x * (y * v) assert left.isclose(right)
Add a test of the associativity of scalar multiplication
Add a test of the associativity of scalar multiplication
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
6b14c9e5683d41ca9d8b9138c25af7526c83d1e4
test/integration/ggrc/converters/test_import_delete.py
test/integration/ggrc/converters/test_import_delete.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc.converters import errors from integration.ggrc import TestCase class TestBasicCsvImport(TestCase): def setUp(self): TestCase.setUp(self) self.client.get("/login") def test_policy_basic_import(self): filename = "ca_setup_for_deletion.csv" self.import_file(filename) filename = "ca_deletion.csv" response_data_dry = self.import_file(filename, dry_run=True) response_data = self.import_file(filename) self.assertEqual(response_data_dry, response_data) self.assertEqual(response_data[0]["deleted"], 2) self.assertEqual(response_data[0]["ignored"], 0)
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from integration.ggrc import TestCase class TestBasicCsvImport(TestCase): def setUp(self): TestCase.setUp(self) self.client.get("/login") def test_policy_basic_import(self): filename = "ca_setup_for_deletion.csv" self.import_file(filename) filename = "ca_deletion.csv" response_data = self.import_file(filename) self.assertEqual(response_data[0]["deleted"], 2) self.assertEqual(response_data[0]["ignored"], 0)
Optimize basic delete import tests
Optimize basic delete import tests The dry-run check is now automatically performed on each import and we do not need to duplicate the work in the delete test.
Python
apache-2.0
selahssea/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core
e4079d7cdeb59a3cac129813b7bb14a6639ea9db
plugins/Webcam_plugin.py
plugins/Webcam_plugin.py
info = { 'id': 'webcam', 'name': 'Webcam', 'description': 'Generic webcam driver', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
info = { 'id': 'webcam', 'name': 'OpenCV', 'description': 'Video camera interfacing through OpenCV', 'module name': 'Webcam', 'class name': 'Webcam', 'author': 'Philip Chimento', 'copyright year': '2011', }
Rename 'webcam' plugin to OpenCV
Rename 'webcam' plugin to OpenCV
Python
mit
ptomato/Beams
df6642256806e0a501e83c06e64b35f187efaf60
rally/benchmark/scenarios/authenticate/authenticate.py
rally/benchmark/scenarios/authenticate/authenticate.py
# Copyright 2014 Red Hat, Inc. <http://www.redhat.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.benchmark.scenarios import base from rally import osclients class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): keystone_endpoint = self.clients("endpoint") cl = osclients.Clients(keystone_endpoint) cl.get_keystone_client()
# Copyright 2014 Red Hat, Inc. <http://www.redhat.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally.benchmark.scenarios import base class Authenticate(base.Scenario): """This class should contain authentication mechanism for different types of clients like Keystone. """ def keystone(self, **kwargs): self.clients("keystone")
Fix for Authentication scenario to correctly use self.clients
Fix for Authentication scenario to correctly use self.clients Scenario has recently been refactored, self.clients in Scenario now takes the name of the CLI client. During the refactoring, the Authenticate scenario was not correctly updated, which causes the authentication scenario to fail. This patch fixes that. Change-Id: I546c0846e00a5285f0d47bc80b6304a53cc566ff Closes-Bug: #1291386
Python
apache-2.0
pandeyop/rally,go-bears/rally,vefimova/rally,aplanas/rally,group-policy/rally,amit0701/rally,shdowofdeath/rally,ytsarev/rally,go-bears/rally,vefimova/rally,group-policy/rally,shdowofdeath/rally,openstack/rally,gluke77/rally,ytsarev/rally,redhat-openstack/rally,varunarya10/rally,amit0701/rally,gluke77/rally,vganapath/rally,gluke77/rally,aforalee/RRally,amit0701/rally,gluke77/rally,afaheem88/rally,eayunstack/rally,vponomaryov/rally,cernops/rally,vganapath/rally,aforalee/RRally,openstack/rally,aplanas/rally,vponomaryov/rally,paboldin/rally,redhat-openstack/rally,cernops/rally,vganapath/rally,eonpatapon/rally,paboldin/rally,yeming233/rally,pyKun/rally,eayunstack/rally,openstack/rally,eonpatapon/rally,vganapath/rally,paboldin/rally,eayunstack/rally,group-policy/rally,yeming233/rally,varunarya10/rally,openstack/rally,pyKun/rally,pandeyop/rally,afaheem88/rally
022f2cc6d067769a6c8e56601c0238aac69ec9ab
jfr_playoff/settings.py
jfr_playoff/settings.py
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.settings = None self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') if self.settings is None: self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
Load config file only once
Load config file only once
Python
bsd-2-clause
emkael/jfrteamy-playoff,emkael/jfrteamy-playoff
19faa280c924254b960a8b9fcb716017e51db09f
pymks/tests/test_mksRegressionModel.py
pymks/tests/test_mksRegressionModel.py
from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) model.coeff = np.fft.ifft(model.Fcoeff, axis=0) assert np.allclose(coeff, model.coeff) if __name__ == '__main__': test()
from pymks import MKSRegressionModel import numpy as np def test(): Nbin = 2 Nspace = 81 Nsample = 400 def filter(x): return np.where(x < 10, np.exp(-abs(x)) * np.cos(x * np.pi), np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi)) coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None] Fcoeff = np.fft.fft(coeff, axis=0) np.random.seed(2) X = np.random.random((Nsample, Nspace)) H = np.linspace(0, 1, Nbin) X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0) FX = np.fft.fft(X_, axis=1) Fy = np.sum(Fcoeff[None] * FX, axis=-1) y = np.fft.ifft(Fy, axis=1).real model = MKSRegressionModel(Nbin=Nbin) model.fit(X, y) assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff) if __name__ == '__main__': test()
Fix test due to addition of coeff property
Fix test due to addition of coeff property Address #49 Add fftshift to test coefficients as model.coeff now returns the shifted real versions.
Python
mit
davidbrough1/pymks,XinyiGong/pymks,awhite40/pymks,davidbrough1/pymks,fredhohman/pymks
0336651c6538d756eb40babe086975a0f7fcabd6
qual/tests/test_historical_calendar.py
qual/tests/test_historical_calendar.py
from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 13)] julian_triplets = [(1752, 9, 1)] transition_triplets = [(1752, 9, 6)]
from test_calendar import CalendarTest from qual.calendars import EnglishHistoricalCalendar class TestHistoricalCalendar(object): def setUp(self): self.calendar = self.calendar_type() def test_before_switch(self): for triplet in self.julian_triplets: self.check_valid_date(*triplet) def test_after_switch(self): for triplet in self.gregorian_triplets: self.check_valid_date(*triplet) def test_during_switch(self): for triplet in self.transition_triplets: self.check_invalid_date(*triplet) class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest): calendar_type = EnglishHistoricalCalendar gregorian_triplets = [(1752, 9, 14)] julian_triplets = [(1752, 9, 1), (1752, 9, 2)] transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
Correct test for the right missing days and present days.
Correct test for the right missing days and present days. 1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
6833865ff35d451a8215803b9fa74cd57167ed82
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb'
Update libchromiumcontent: Contain linux symbols.
Update libchromiumcontent: Contain linux symbols.
Python
mit
trankmichael/electron,gabrielPeart/electron,felixrieseberg/electron,seanchas116/electron,bitemyapp/electron,xfstudio/electron,leolujuyi/electron,pombredanne/electron,astoilkov/electron,gabriel/electron,mubassirhayat/electron,smczk/electron,Jacobichou/electron,medixdev/electron,yalexx/electron,natgolov/electron,rsvip/electron,Neron-X5/electron,tomashanacek/electron,systembugtj/electron,webmechanicx/electron,fomojola/electron,felixrieseberg/electron,mubassirhayat/electron,cqqccqc/electron,wan-qy/electron,gerhardberger/electron,LadyNaggaga/electron,rsvip/electron,vaginessa/electron,Floato/electron,nagyistoce/electron-atom-shell,gbn972/electron,Rokt33r/electron,xiruibing/electron,joaomoreno/atom-shell,kazupon/electron,oiledCode/electron,stevekinney/electron,miniak/electron,fabien-d/electron,fritx/electron,ankitaggarwal011/electron,RIAEvangelist/electron,arturts/electron,joaomoreno/atom-shell,jtburke/electron,dkfiresky/electron,tomashanacek/electron,tomashanacek/electron,synaptek/electron,deed02392/electron,chrisswk/electron,saronwei/electron,lrlna/electron,lzpfmh/electron,michaelchiche/electron,abhishekgahlot/electron,simongregory/electron,smczk/electron,farmisen/electron,Jacobichou/electron,subblue/electron,BionicClick/electron,jannishuebl/electron,deed02392/electron,seanchas116/electron,DivyaKMenon/electron,shennushi/electron,Rokt33r/electron,GoooIce/electron,shockone/electron,neutrous/electron,mattdesl/electron,dahal/electron,mattotodd/electron,michaelchiche/electron,aliib/electron,simonfork/electron,seanchas116/electron,roadev/electron,simongregory/electron,saronwei/electron,SufianHassan/electron,pirafrank/electron,Jonekee/electron,trigrass2/electron,fabien-d/electron,systembugtj/electron,rhencke/electron,tincan24/electron,dongjoon-hyun/electron,voidbridge/electron,gabrielPeart/electron,mhkeller/electron,minggo/electron,bwiggs/electron,tincan24/electron,arusakov/electron,shaundunne/electron,ervinb/electron,stevemao/electron,fffej/electron,egoist/electron,icattlecoder/electron,wan-qy/electron,kikong/electron,bobwol/electron,Neron-X5/electron,takashi/electron,rreimann/electron,jlord/electron,renaesop/electron,wolfflow/electron,rajatsingla28/electron,bitemyapp/electron,bpasero/electron,joneit/electron,synaptek/electron,dahal/electron,aichingm/electron,anko/electron,bpasero/electron,wan-qy/electron,webmechanicx/electron,setzer777/electron,vaginessa/electron,simonfork/electron,soulteary/electron,icattlecoder/electron,aliib/electron,Gerhut/electron,RIAEvangelist/electron,tomashanacek/electron,faizalpribadi/electron,renaesop/electron,gstack/infinium-shell,nagyistoce/electron-atom-shell,vHanda/electron,baiwyc119/electron,fritx/electron,fomojola/electron,bright-sparks/electron,jonatasfreitasv/electron,nicholasess/electron,ankitaggarwal011/electron,JussMee15/electron,bright-sparks/electron,jlord/electron,DivyaKMenon/electron,oiledCode/electron,mattotodd/electron,micalan/electron,yan-foto/electron,BionicClick/electron,bruce/electron,maxogden/atom-shell,RobertJGabriel/electron,medixdev/electron,michaelchiche/electron,rsvip/electron,wan-qy/electron,brave/muon,Rokt33r/electron,carsonmcdonald/electron,trankmichael/electron,ankitaggarwal011/electron,eriser/electron,rhencke/electron,Neron-X5/electron,coderhaoxin/electron,shaundunne/electron,aliib/electron,deed02392/electron,ankitaggarwal011/electron,meowlab/electron,ervinb/electron,simongregory/electron,digideskio/electron,tonyganch/electron,cos2004/electron,aecca/electron,LadyNaggaga/electron,Faiz7412/electron,maxogden/atom-shell,sky7sea/electron,aaron-goshine/electron,gamedevsam/electron,hokein/atom-shell,kenmozi/electron,matiasinsaurralde/electron,shaundunne/electron,pandoraui/electron,stevekinney/electron,pirafrank/electron,yan-foto/electron,MaxGraey/electron,zhakui/electron,RIAEvangelist/electron,preco21/electron,Faiz7412/electron,kostia/electron,beni55/electron,arturts/electron,synaptek/electron,brave/electron,noikiy/electron,oiledCode/electron,simonfork/electron,meowlab/electron,preco21/electron,tinydew4/electron,benweissmann/electron,fritx/electron,sky7sea/electron,ervinb/electron,synaptek/electron,nekuz0r/electron,sircharleswatson/electron,jlhbaseball15/electron,Andrey-Pavlov/electron,kcrt/electron,rsvip/electron,leethomas/electron,roadev/electron,lzpfmh/electron,greyhwndz/electron,vaginessa/electron,farmisen/electron,coderhaoxin/electron,biblerule/UMCTelnetHub,mrwizard82d1/electron,zhakui/electron,trigrass2/electron,mjaniszew/electron,bpasero/electron,Jonekee/electron,bwiggs/electron,bpasero/electron,bobwol/electron,dongjoon-hyun/electron,JesselJohn/electron,SufianHassan/electron,digideskio/electron,MaxWhere/electron,bbondy/electron,thomsonreuters/electron,edulan/electron,Neron-X5/electron,fomojola/electron,leethomas/electron,tylergibson/electron,arusakov/electron,dongjoon-hyun/electron,twolfson/electron,renaesop/electron,Evercoder/electron,etiktin/electron,the-ress/electron,jsutcodes/electron,kikong/electron,Jonekee/electron,minggo/electron,sshiting/electron,xiruibing/electron,rreimann/electron,deepak1556/atom-shell,deed02392/electron,arturts/electron,bright-sparks/electron,RobertJGabriel/electron,saronwei/electron,electron/electron,cqqccqc/electron,mirrh/electron,biblerule/UMCTelnetHub,the-ress/electron,pombredanne/electron,d-salas/electron,jacksondc/electron,pirafrank/electron,JesselJohn/electron,rhencke/electron,chriskdon/electron,takashi/electron,Gerhut/electron,bobwol/electron,the-ress/electron,yan-foto/electron,MaxGraey/electron,thingsinjars/electron,icattlecoder/electron,edulan/electron,jlord/electron,shaundunne/electron,iftekeriba/electron,gerhardberger/electron,Zagorakiss/electron,aichingm/electron,sky7sea/electron,John-Lin/electron,lzpfmh/electron,stevemao/electron,thomsonreuters/electron,howmuchcomputer/electron,sircharleswatson/electron,greyhwndz/electron,Floato/electron,thingsinjars/electron,matiasinsaurralde/electron,chrisswk/electron,adamjgray/electron,brave/electron,jsutcodes/electron,mirrh/electron,RIAEvangelist/electron,shiftkey/electron,cqqccqc/electron,the-ress/electron,fritx/electron,joneit/electron,trankmichael/electron,joaomoreno/atom-shell,soulteary/electron,anko/electron,GoooIce/electron,felixrieseberg/electron,brenca/electron,benweissmann/electron,mjaniszew/electron,bbondy/electron,tincan24/electron,neutrous/electron,howmuchcomputer/electron,jtburke/electron,voidbridge/electron,bbondy/electron,eric-seekas/electron,MaxWhere/electron,gabriel/electron,Ivshti/electron,mattotodd/electron,sshiting/electron,aecca/electron,shiftkey/electron,zhakui/electron,MaxWhere/electron,evgenyzinoviev/electron,sshiting/electron,xiruibing/electron,dkfiresky/electron,kenmozi/electron,dongjoon-hyun/electron,leethomas/electron,cqqccqc/electron,natgolov/electron,sshiting/electron,jacksondc/electron,nicobot/electron,smczk/electron,jaanus/electron,tincan24/electron,shiftkey/electron,jlord/electron,the-ress/electron,webmechanicx/electron,xfstudio/electron,mattdesl/electron,coderhaoxin/electron,pombredanne/electron,bright-sparks/electron,xiruibing/electron,jjz/electron,mirrh/electron,noikiy/electron,nicobot/electron,leftstick/electron,preco21/electron,jjz/electron,eric-seekas/electron,anko/electron,darwin/electron,fritx/electron,jonatasfreitasv/electron,nicholasess/electron,bright-sparks/electron,electron/electron,John-Lin/electron,aaron-goshine/electron,SufianHassan/electron,shiftkey/electron,rajatsingla28/electron,rreimann/electron,natgolov/electron,natgolov/electron,Gerhut/electron,shockone/electron,electron/electron,trankmichael/electron,aaron-goshine/electron,bpasero/electron,JussMee15/electron,SufianHassan/electron,yalexx/electron,kcrt/electron,jsutcodes/electron,abhishekgahlot/electron,deed02392/electron,zhakui/electron,zhakui/electron,christian-bromann/electron,egoist/electron,benweissmann/electron,kcrt/electron,Andrey-Pavlov/electron,kikong/electron,adcentury/electron,fffej/electron,darwin/electron,BionicClick/electron,jiaz/electron,Floato/electron,IonicaBizauKitchen/electron,webmechanicx/electron,pombredanne/electron,jsutcodes/electron,systembugtj/electron,beni55/electron,fomojola/electron,destan/electron,vaginessa/electron,eric-seekas/electron,rprichard/electron,bbondy/electron,Zagorakiss/electron,JesselJohn/electron,gamedevsam/electron,joneit/electron,gabriel/electron,bruce/electron,tincan24/electron,jacksondc/electron,micalan/electron,edulan/electron,brave/electron,wolfflow/electron,kazupon/electron,felixrieseberg/electron,darwin/electron,fffej/electron,mjaniszew/electron,kokdemo/electron,DivyaKMenon/electron,etiktin/electron,IonicaBizauKitchen/electron,voidbridge/electron,trigrass2/electron,chriskdon/electron,arusakov/electron,stevekinney/electron,rajatsingla28/electron,davazp/electron,greyhwndz/electron,neutrous/electron,Andrey-Pavlov/electron,fomojola/electron,d-salas/electron,tonyganch/electron,abhishekgahlot/electron,darwin/electron,icattlecoder/electron,subblue/electron,hokein/atom-shell,takashi/electron,wan-qy/electron,systembugtj/electron,jiaz/electron,vipulroxx/electron,d-salas/electron,xiruibing/electron,jiaz/electron,jacksondc/electron,shockone/electron,robinvandernoord/electron,etiktin/electron,fireball-x/atom-shell,davazp/electron,dongjoon-hyun/electron,biblerule/UMCTelnetHub,nagyistoce/electron-atom-shell,jhen0409/electron,twolfson/electron,ianscrivener/electron,mattdesl/electron,gamedevsam/electron,nicobot/electron,soulteary/electron,Evercoder/electron,rreimann/electron,preco21/electron,tylergibson/electron,medixdev/electron,faizalpribadi/electron,faizalpribadi/electron,adamjgray/electron,tinydew4/electron,SufianHassan/electron,icattlecoder/electron,nicholasess/electron,lrlna/electron,baiwyc119/electron,brenca/electron,leolujuyi/electron,tonyganch/electron,fomojola/electron,hokein/atom-shell,nicholasess/electron,micalan/electron,oiledCode/electron,kokdemo/electron,GoooIce/electron,fffej/electron,adamjgray/electron,gstack/infinium-shell,kcrt/electron,bruce/electron,dahal/electron,tylergibson/electron,lrlna/electron,soulteary/electron,kcrt/electron,cqqccqc/electron,gbn972/electron,iftekeriba/electron,abhishekgahlot/electron,adamjgray/electron,jjz/electron,egoist/electron,faizalpribadi/electron,ianscrivener/electron,deepak1556/atom-shell,bruce/electron,webmechanicx/electron,the-ress/electron,farmisen/electron,nagyistoce/electron-atom-shell,destan/electron,jannishuebl/electron,shockone/electron,joaomoreno/atom-shell,bwiggs/electron,jlhbaseball15/electron,chrisswk/electron,d-salas/electron,michaelchiche/electron,adamjgray/electron,twolfson/electron,soulteary/electron,bwiggs/electron,carsonmcdonald/electron,jaanus/electron,gerhardberger/electron,kenmozi/electron,xfstudio/electron,howmuchcomputer/electron,leolujuyi/electron,coderhaoxin/electron,Zagorakiss/electron,roadev/electron,xfstudio/electron,carsonmcdonald/electron,thomsonreuters/electron,yan-foto/electron,shennushi/electron,anko/electron,vHanda/electron,jhen0409/electron,Floato/electron,electron/electron,fabien-d/electron,bbondy/electron,carsonmcdonald/electron,faizalpribadi/electron,pandoraui/electron,Faiz7412/electron,smczk/electron,subblue/electron,kenmozi/electron,noikiy/electron,nicholasess/electron,tylergibson/electron,nekuz0r/electron,rsvip/electron,cos2004/electron,brenca/electron,christian-bromann/electron,jaanus/electron,astoilkov/electron,greyhwndz/electron,mhkeller/electron,Zagorakiss/electron,yan-foto/electron,jsutcodes/electron,deepak1556/atom-shell,carsonmcdonald/electron,iftekeriba/electron,mattotodd/electron,MaxGraey/electron,aaron-goshine/electron,stevekinney/electron,dahal/electron,thompsonemerson/electron,lzpfmh/electron,jlhbaseball15/electron,d-salas/electron,benweissmann/electron,voidbridge/electron,kazupon/electron,Jonekee/electron,vipulroxx/electron,vHanda/electron,brenca/electron,tincan24/electron,pombredanne/electron,Zagorakiss/electron,chriskdon/electron,biblerule/UMCTelnetHub,thompsonemerson/electron,rprichard/electron,subblue/electron,noikiy/electron,jtburke/electron,chriskdon/electron,howmuchcomputer/electron,gerhardberger/electron,eriser/electron,coderhaoxin/electron,MaxGraey/electron,gbn972/electron,joneit/electron,neutrous/electron,eriser/electron,astoilkov/electron,John-Lin/electron,mhkeller/electron,nicholasess/electron,felixrieseberg/electron,benweissmann/electron,kazupon/electron,mjaniszew/electron,bobwol/electron,mirrh/electron,gstack/infinium-shell,pirafrank/electron,leftstick/electron,jcblw/electron,fireball-x/atom-shell,RobertJGabriel/electron,mjaniszew/electron,pombredanne/electron,GoooIce/electron,gstack/infinium-shell,jjz/electron,nicobot/electron,gbn972/electron,anko/electron,tylergibson/electron,jonatasfreitasv/electron,faizalpribadi/electron,beni55/electron,ianscrivener/electron,timruffles/electron,mubassirhayat/electron,ervinb/electron,stevemao/electron,mattotodd/electron,IonicaBizauKitchen/electron,Jacobichou/electron,arusakov/electron,RobertJGabriel/electron,matiasinsaurralde/electron,bitemyapp/electron,davazp/electron,mjaniszew/electron,adcentury/electron,Evercoder/electron,tonyganch/electron,setzer777/electron,simongregory/electron,pandoraui/electron,Floato/electron,simongregory/electron,leftstick/electron,kcrt/electron,arusakov/electron,rreimann/electron,howmuchcomputer/electron,adamjgray/electron,John-Lin/electron,noikiy/electron,oiledCode/electron,roadev/electron,aecca/electron,dkfiresky/electron,bitemyapp/electron,preco21/electron,Evercoder/electron,benweissmann/electron,the-ress/electron,saronwei/electron,mattdesl/electron,darwin/electron,BionicClick/electron,jhen0409/electron,Andrey-Pavlov/electron,systembugtj/electron,mrwizard82d1/electron,RobertJGabriel/electron,astoilkov/electron,jiaz/electron,gamedevsam/electron,aichingm/electron,jtburke/electron,jhen0409/electron,greyhwndz/electron,mrwizard82d1/electron,mirrh/electron,minggo/electron,John-Lin/electron,destan/electron,brenca/electron,tomashanacek/electron,thompsonemerson/electron,leftstick/electron,greyhwndz/electron,ianscrivener/electron,kostia/electron,JussMee15/electron,sky7sea/electron,jcblw/electron,cos2004/electron,tinydew4/electron,maxogden/atom-shell,gerhardberger/electron,fritx/electron,etiktin/electron,IonicaBizauKitchen/electron,thompsonemerson/electron,lrlna/electron,roadev/electron,kokdemo/electron,brave/muon,rajatsingla28/electron,shiftkey/electron,MaxGraey/electron,SufianHassan/electron,timruffles/electron,twolfson/electron,setzer777/electron,brave/electron,medixdev/electron,seanchas116/electron,saronwei/electron,edulan/electron,rhencke/electron,fireball-x/atom-shell,IonicaBizauKitchen/electron,shaundunne/electron,smczk/electron,MaxWhere/electron,chriskdon/electron,simonfork/electron,eriser/electron,jtburke/electron,chrisswk/electron,trigrass2/electron,brave/electron,nagyistoce/electron-atom-shell,digideskio/electron,joaomoreno/atom-shell,trankmichael/electron,synaptek/electron,gstack/infinium-shell,DivyaKMenon/electron,John-Lin/electron,mrwizard82d1/electron,systembugtj/electron,fireball-x/atom-shell,beni55/electron,jhen0409/electron,deepak1556/atom-shell,kostia/electron,eriser/electron,trigrass2/electron,Ivshti/electron,wolfflow/electron,gabriel/electron,dkfiresky/electron,JesselJohn/electron,thompsonemerson/electron,RIAEvangelist/electron,bpasero/electron,aaron-goshine/electron,hokein/atom-shell,mirrh/electron,jcblw/electron,gabrielPeart/electron,simongregory/electron,evgenyzinoviev/electron,matiasinsaurralde/electron,fffej/electron,matiasinsaurralde/electron,Andrey-Pavlov/electron,JussMee15/electron,fabien-d/electron,gabrielPeart/electron,renaesop/electron,dkfiresky/electron,ankitaggarwal011/electron,arturts/electron,LadyNaggaga/electron,LadyNaggaga/electron,jonatasfreitasv/electron,bwiggs/electron,leethomas/electron,kazupon/electron,d-salas/electron,mrwizard82d1/electron,farmisen/electron,timruffles/electron,vaginessa/electron,bright-sparks/electron,bobwol/electron,Rokt33r/electron,eric-seekas/electron,rajatsingla28/electron,setzer777/electron,baiwyc119/electron,xfstudio/electron,JussMee15/electron,Ivshti/electron,JesselJohn/electron,seanchas116/electron,biblerule/UMCTelnetHub,digideskio/electron,Ivshti/electron,thomsonreuters/electron,evgenyzinoviev/electron,egoist/electron,edulan/electron,BionicClick/electron,neutrous/electron,brave/muon,etiktin/electron,maxogden/atom-shell,maxogden/atom-shell,jcblw/electron,jtburke/electron,Evercoder/electron,nekuz0r/electron,xfstudio/electron,gbn972/electron,jannishuebl/electron,zhakui/electron,miniak/electron,pandoraui/electron,neutrous/electron,rhencke/electron,arturts/electron,natgolov/electron,jannishuebl/electron,Gerhut/electron,bruce/electron,Gerhut/electron,ianscrivener/electron,wan-qy/electron,takashi/electron,digideskio/electron,farmisen/electron,thingsinjars/electron,baiwyc119/electron,roadev/electron,leethomas/electron,adcentury/electron,voidbridge/electron,beni55/electron,coderhaoxin/electron,jonatasfreitasv/electron,saronwei/electron,jannishuebl/electron,bruce/electron,bpasero/electron,rprichard/electron,renaesop/electron,sircharleswatson/electron,Floato/electron,egoist/electron,jaanus/electron,JussMee15/electron,shockone/electron,jhen0409/electron,gabriel/electron,gabrielPeart/electron,electron/electron,leolujuyi/electron,christian-bromann/electron,BionicClick/electron,shockone/electron,rhencke/electron,kokdemo/electron,tonyganch/electron,trankmichael/electron,leftstick/electron,pirafrank/electron,mhkeller/electron,nekuz0r/electron,kenmozi/electron,aecca/electron,dongjoon-hyun/electron,IonicaBizauKitchen/electron,kokdemo/electron,Faiz7412/electron,leolujuyi/electron,stevekinney/electron,jjz/electron,kenmozi/electron,gbn972/electron,Jacobichou/electron,setzer777/electron,JesselJohn/electron,kikong/electron,aliib/electron,minggo/electron,shiftkey/electron,astoilkov/electron,pandoraui/electron,abhishekgahlot/electron,jjz/electron,lzpfmh/electron,yalexx/electron,fffej/electron,miniak/electron,yalexx/electron,mattdesl/electron,matiasinsaurralde/electron,wolfflow/electron,gabrielPeart/electron,Jacobichou/electron,christian-bromann/electron,simonfork/electron,aaron-goshine/electron,miniak/electron,chrisswk/electron,robinvandernoord/electron,thingsinjars/electron,davazp/electron,electron/electron,Zagorakiss/electron,ankitaggarwal011/electron,aichingm/electron,aecca/electron,jlord/electron,joneit/electron,wolfflow/electron,tinydew4/electron,takashi/electron,micalan/electron,adcentury/electron,medixdev/electron,posix4e/electron,leethomas/electron,trigrass2/electron,etiktin/electron,lzpfmh/electron,sshiting/electron,brave/muon,leftstick/electron,abhishekgahlot/electron,tylergibson/electron,michaelchiche/electron,dahal/electron,davazp/electron,brave/muon,kokdemo/electron,noikiy/electron,Rokt33r/electron,jannishuebl/electron,mhkeller/electron,michaelchiche/electron,shaundunne/electron,rprichard/electron,jcblw/electron,carsonmcdonald/electron,aliib/electron,jaanus/electron,LadyNaggaga/electron,meowlab/electron,miniak/electron,jiaz/electron,simonfork/electron,shennushi/electron,thompsonemerson/electron,joneit/electron,meowlab/electron,jacksondc/electron,kikong/electron,egoist/electron,cos2004/electron,thomsonreuters/electron,timruffles/electron,minggo/electron,posix4e/electron,icattlecoder/electron,chriskdon/electron,aichingm/electron,RobertJGabriel/electron,micalan/electron,kostia/electron,Faiz7412/electron,sshiting/electron,farmisen/electron,vHanda/electron,renaesop/electron,digideskio/electron,kostia/electron,jonatasfreitasv/electron,gamedevsam/electron,LadyNaggaga/electron,posix4e/electron,aichingm/electron,twolfson/electron,sky7sea/electron,kostia/electron,lrlna/electron,cos2004/electron,wolfflow/electron,arusakov/electron,mhkeller/electron,anko/electron,jsutcodes/electron,ervinb/electron,micalan/electron,mattotodd/electron,natgolov/electron,pandoraui/electron,Andrey-Pavlov/electron,robinvandernoord/electron,jiaz/electron,timruffles/electron,smczk/electron,pirafrank/electron,mattdesl/electron,evgenyzinoviev/electron,webmechanicx/electron,RIAEvangelist/electron,miniak/electron,twolfson/electron,christian-bromann/electron,tinydew4/electron,sircharleswatson/electron,christian-bromann/electron,DivyaKMenon/electron,Gerhut/electron,fabien-d/electron,mrwizard82d1/electron,biblerule/UMCTelnetHub,nicobot/electron,rreimann/electron,evgenyzinoviev/electron,gabriel/electron,Rokt33r/electron,vaginessa/electron,aecca/electron,nekuz0r/electron,jacksondc/electron,ervinb/electron,mubassirhayat/electron,baiwyc119/electron,iftekeriba/electron,sircharleswatson/electron,vHanda/electron,arturts/electron,shennushi/electron,cos2004/electron,astoilkov/electron,tonyganch/electron,stevemao/electron,takashi/electron,tinydew4/electron,setzer777/electron,stevemao/electron,thomsonreuters/electron,robinvandernoord/electron,gamedevsam/electron,deed02392/electron,felixrieseberg/electron,brave/muon,nekuz0r/electron,MaxWhere/electron,yan-foto/electron,destan/electron,Neron-X5/electron,davazp/electron,yalexx/electron,brenca/electron,Ivshti/electron,jcblw/electron,aliib/electron,GoooIce/electron,bitemyapp/electron,lrlna/electron,rajatsingla28/electron,shennushi/electron,posix4e/electron,ianscrivener/electron,bobwol/electron,xiruibing/electron,subblue/electron,shennushi/electron,posix4e/electron,oiledCode/electron,robinvandernoord/electron,Evercoder/electron,vipulroxx/electron,evgenyzinoviev/electron,yalexx/electron,bitemyapp/electron,brave/electron,thingsinjars/electron,sircharleswatson/electron,fireball-x/atom-shell,meowlab/electron,hokein/atom-shell,stevekinney/electron,dahal/electron,cqqccqc/electron,vHanda/electron,robinvandernoord/electron,dkfiresky/electron,Neron-X5/electron,eric-seekas/electron,MaxWhere/electron,vipulroxx/electron,howmuchcomputer/electron,eric-seekas/electron,iftekeriba/electron,destan/electron,thingsinjars/electron,adcentury/electron,GoooIce/electron,jlhbaseball15/electron,adcentury/electron,joaomoreno/atom-shell,leolujuyi/electron,gerhardberger/electron,jlhbaseball15/electron,preco21/electron,kazupon/electron,nicobot/electron,tomashanacek/electron,soulteary/electron,stevemao/electron,seanchas116/electron,mubassirhayat/electron,Jonekee/electron,jaanus/electron,eriser/electron,meowlab/electron,edulan/electron,vipulroxx/electron,subblue/electron,baiwyc119/electron,beni55/electron,Jacobichou/electron,minggo/electron,gerhardberger/electron,DivyaKMenon/electron,electron/electron,iftekeriba/electron,sky7sea/electron,Jonekee/electron,jlhbaseball15/electron,medixdev/electron,posix4e/electron,bwiggs/electron,bbondy/electron,synaptek/electron,voidbridge/electron,deepak1556/atom-shell,vipulroxx/electron,destan/electron
c56480fd8905332e54649dac0ade95c825e8ba23
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'b27290717c08f8c6a58067d3c3725d68b4e6a2e5'
#!/usr/bin/env python NODE_VERSION = 'v0.11.10' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'fe05f53f3080889ced2696b2741d93953e654b49'
Update libchromiumcontent to use the thin version.
Update libchromiumcontent to use the thin version.
Python
mit
cos2004/electron,rajatsingla28/electron,bobwol/electron,tonyganch/electron,gbn972/electron,deed02392/electron,natgolov/electron,felixrieseberg/electron,bright-sparks/electron,adcentury/electron,jhen0409/electron,soulteary/electron,pandoraui/electron,subblue/electron,matiasinsaurralde/electron,jlord/electron,rreimann/electron,shockone/electron,mattdesl/electron,subblue/electron,eriser/electron,gabriel/electron,destan/electron,adamjgray/electron,shennushi/electron,aliib/electron,mattdesl/electron,vaginessa/electron,yalexx/electron,jsutcodes/electron,Gerhut/electron,kokdemo/electron,JussMee15/electron,subblue/electron,DivyaKMenon/electron,vaginessa/electron,aaron-goshine/electron,shennushi/electron,leolujuyi/electron,davazp/electron,stevemao/electron,Evercoder/electron,cos2004/electron,bitemyapp/electron,arturts/electron,smczk/electron,pombredanne/electron,brave/electron,yalexx/electron,jlord/electron,felixrieseberg/electron,evgenyzinoviev/electron,SufianHassan/electron,dahal/electron,bruce/electron,nekuz0r/electron,jcblw/electron,leolujuyi/electron,miniak/electron,RIAEvangelist/electron,lzpfmh/electron,brave/muon,carsonmcdonald/electron,simonfork/electron,fireball-x/atom-shell,benweissmann/electron,jtburke/electron,xiruibing/electron,Jonekee/electron,RIAEvangelist/electron,mirrh/electron,jcblw/electron,timruffles/electron,the-ress/electron,pirafrank/electron,xiruibing/electron,xiruibing/electron,coderhaoxin/electron,twolfson/electron,chriskdon/electron,deepak1556/atom-shell,sky7sea/electron,saronwei/electron,bright-sparks/electron,mubassirhayat/electron,deepak1556/atom-shell,benweissmann/electron,kcrt/electron,arusakov/electron,kikong/electron,nagyistoce/electron-atom-shell,matiasinsaurralde/electron,icattlecoder/electron,saronwei/electron,thomsonreuters/electron,wan-qy/electron,aliib/electron,joaomoreno/atom-shell,gerhardberger/electron,gstack/infinium-shell,greyhwndz/electron,fomojola/electron,smczk/electron,stevekinney/electron,abhishekgahlot/electron,robinvandernoord/electron,bruce/electron,rsvip/electron,carsonmcdonald/electron,gstack/infinium-shell,Floato/electron,voidbridge/electron,cos2004/electron,kazupon/electron,webmechanicx/electron,simongregory/electron,beni55/electron,takashi/electron,beni55/electron,leftstick/electron,dkfiresky/electron,shennushi/electron,twolfson/electron,shennushi/electron,matiasinsaurralde/electron,christian-bromann/electron,pandoraui/electron,shockone/electron,vHanda/electron,kokdemo/electron,soulteary/electron,arturts/electron,faizalpribadi/electron,systembugtj/electron,biblerule/UMCTelnetHub,aichingm/electron,tonyganch/electron,brenca/electron,hokein/atom-shell,dongjoon-hyun/electron,minggo/electron,jlhbaseball15/electron,anko/electron,Gerhut/electron,etiktin/electron,eric-seekas/electron,etiktin/electron,thompsonemerson/electron,leethomas/electron,twolfson/electron,soulteary/electron,tinydew4/electron,coderhaoxin/electron,trigrass2/electron,dahal/electron,sircharleswatson/electron,medixdev/electron,davazp/electron,micalan/electron,farmisen/electron,ianscrivener/electron,hokein/atom-shell,nicholasess/electron,roadev/electron,matiasinsaurralde/electron,bwiggs/electron,stevekinney/electron,MaxGraey/electron,rajatsingla28/electron,jannishuebl/electron,shaundunne/electron,seanchas116/electron,carsonmcdonald/electron,webmechanicx/electron,nicholasess/electron,aecca/electron,preco21/electron,faizalpribadi/electron,rsvip/electron,systembugtj/electron,rajatsingla28/electron,yan-foto/electron,the-ress/electron,mjaniszew/electron,d-salas/electron,soulteary/electron,jaanus/electron,brenca/electron,mrwizard82d1/electron,noikiy/electron,Jonekee/electron,adcentury/electron,darwin/electron,kikong/electron,iftekeriba/electron,nagyistoce/electron-atom-shell,fomojola/electron,chrisswk/electron,DivyaKMenon/electron,rhencke/electron,dahal/electron,Ivshti/electron,kazupon/electron,anko/electron,aecca/electron,jhen0409/electron,vHanda/electron,bwiggs/electron,darwin/electron,voidbridge/electron,tonyganch/electron,bobwol/electron,howmuchcomputer/electron,jsutcodes/electron,JesselJohn/electron,nekuz0r/electron,Ivshti/electron,Gerhut/electron,benweissmann/electron,minggo/electron,mirrh/electron,BionicClick/electron,Evercoder/electron,icattlecoder/electron,Faiz7412/electron,ankitaggarwal011/electron,fireball-x/atom-shell,vipulroxx/electron,davazp/electron,setzer777/electron,digideskio/electron,renaesop/electron,cos2004/electron,xfstudio/electron,SufianHassan/electron,subblue/electron,ervinb/electron,bobwol/electron,darwin/electron,Floato/electron,rajatsingla28/electron,BionicClick/electron,eriser/electron,jonatasfreitasv/electron,jlhbaseball15/electron,mrwizard82d1/electron,arturts/electron,MaxGraey/electron,jaanus/electron,shockone/electron,jacksondc/electron,evgenyzinoviev/electron,dkfiresky/electron,lzpfmh/electron,jsutcodes/electron,robinvandernoord/electron,smczk/electron,cos2004/electron,leethomas/electron,electron/electron,ankitaggarwal011/electron,setzer777/electron,gabrielPeart/electron,Rokt33r/electron,digideskio/electron,michaelchiche/electron,Gerhut/electron,rreimann/electron,digideskio/electron,wolfflow/electron,RobertJGabriel/electron,electron/electron,natgolov/electron,leolujuyi/electron,astoilkov/electron,gamedevsam/electron,fireball-x/atom-shell,icattlecoder/electron,rsvip/electron,jcblw/electron,iftekeriba/electron,ianscrivener/electron,faizalpribadi/electron,RIAEvangelist/electron,eric-seekas/electron,tonyganch/electron,jtburke/electron,pombredanne/electron,sshiting/electron,aliib/electron,Neron-X5/electron,icattlecoder/electron,DivyaKMenon/electron,takashi/electron,trankmichael/electron,zhakui/electron,leethomas/electron,d-salas/electron,eric-seekas/electron,fffej/electron,Jacobichou/electron,adcentury/electron,egoist/electron,arusakov/electron,faizalpribadi/electron,pandoraui/electron,RIAEvangelist/electron,evgenyzinoviev/electron,takashi/electron,twolfson/electron,medixdev/electron,electron/electron,fffej/electron,shockone/electron,chriskdon/electron,wan-qy/electron,edulan/electron,shiftkey/electron,bbondy/electron,oiledCode/electron,lzpfmh/electron,maxogden/atom-shell,renaesop/electron,brave/muon,pirafrank/electron,matiasinsaurralde/electron,adamjgray/electron,webmechanicx/electron,jlord/electron,JussMee15/electron,kokdemo/electron,webmechanicx/electron,seanchas116/electron,gabriel/electron,farmisen/electron,jacksondc/electron,howmuchcomputer/electron,electron/electron,oiledCode/electron,arusakov/electron,simonfork/electron,rhencke/electron,IonicaBizauKitchen/electron,greyhwndz/electron,baiwyc119/electron,tincan24/electron,shiftkey/electron,sshiting/electron,vaginessa/electron,d-salas/electron,miniak/electron,tomashanacek/electron,adcentury/electron,zhakui/electron,smczk/electron,cqqccqc/electron,RobertJGabriel/electron,jlhbaseball15/electron,JesselJohn/electron,biblerule/UMCTelnetHub,davazp/electron,wan-qy/electron,meowlab/electron,evgenyzinoviev/electron,noikiy/electron,mhkeller/electron,JussMee15/electron,jonatasfreitasv/electron,gabriel/electron,synaptek/electron,farmisen/electron,DivyaKMenon/electron,natgolov/electron,miniak/electron,benweissmann/electron,jannishuebl/electron,christian-bromann/electron,eric-seekas/electron,MaxGraey/electron,wolfflow/electron,fomojola/electron,LadyNaggaga/electron,maxogden/atom-shell,rajatsingla28/electron,lrlna/electron,mrwizard82d1/electron,leftstick/electron,meowlab/electron,wolfflow/electron,electron/electron,Jacobichou/electron,tincan24/electron,mjaniszew/electron,xfstudio/electron,minggo/electron,rreimann/electron,simonfork/electron,sshiting/electron,shiftkey/electron,RobertJGabriel/electron,kenmozi/electron,roadev/electron,matiasinsaurralde/electron,benweissmann/electron,baiwyc119/electron,d-salas/electron,icattlecoder/electron,gerhardberger/electron,fomojola/electron,brenca/electron,nicobot/electron,joaomoreno/atom-shell,Rokt33r/electron,BionicClick/electron,synaptek/electron,Andrey-Pavlov/electron,mattotodd/electron,micalan/electron,kcrt/electron,digideskio/electron,fomojola/electron,miniak/electron,icattlecoder/electron,Jacobichou/electron,LadyNaggaga/electron,bpasero/electron,posix4e/electron,minggo/electron,Neron-X5/electron,mattdesl/electron,thompsonemerson/electron,jtburke/electron,saronwei/electron,mattotodd/electron,shaundunne/electron,jcblw/electron,tonyganch/electron,yan-foto/electron,rhencke/electron,abhishekgahlot/electron,jjz/electron,nagyistoce/electron-atom-shell,MaxWhere/electron,gstack/infinium-shell,seanchas116/electron,jjz/electron,tylergibson/electron,SufianHassan/electron,nicholasess/electron,MaxWhere/electron,voidbridge/electron,tinydew4/electron,jtburke/electron,mubassirhayat/electron,Evercoder/electron,simongregory/electron,egoist/electron,jannishuebl/electron,LadyNaggaga/electron,synaptek/electron,astoilkov/electron,thingsinjars/electron,Ivshti/electron,fabien-d/electron,pombredanne/electron,astoilkov/electron,BionicClick/electron,tinydew4/electron,setzer777/electron,Neron-X5/electron,chrisswk/electron,RobertJGabriel/electron,edulan/electron,MaxWhere/electron,evgenyzinoviev/electron,deed02392/electron,pandoraui/electron,mrwizard82d1/electron,Floato/electron,sky7sea/electron,bbondy/electron,sircharleswatson/electron,ervinb/electron,jonatasfreitasv/electron,thingsinjars/electron,renaesop/electron,GoooIce/electron,baiwyc119/electron,kokdemo/electron,rprichard/electron,pirafrank/electron,kazupon/electron,thingsinjars/electron,biblerule/UMCTelnetHub,MaxGraey/electron,bruce/electron,christian-bromann/electron,robinvandernoord/electron,shennushi/electron,RobertJGabriel/electron,gamedevsam/electron,pombredanne/electron,Neron-X5/electron,jiaz/electron,eric-seekas/electron,vipulroxx/electron,stevemao/electron,gstack/infinium-shell,carsonmcdonald/electron,bwiggs/electron,Floato/electron,seanchas116/electron,etiktin/electron,bright-sparks/electron,farmisen/electron,davazp/electron,tylergibson/electron,eriser/electron,Jacobichou/electron,mirrh/electron,takashi/electron,felixrieseberg/electron,thingsinjars/electron,leethomas/electron,jonatasfreitasv/electron,vipulroxx/electron,anko/electron,ianscrivener/electron,stevekinney/electron,thomsonreuters/electron,mirrh/electron,mattotodd/electron,gerhardberger/electron,Evercoder/electron,Neron-X5/electron,twolfson/electron,posix4e/electron,subblue/electron,gerhardberger/electron,jjz/electron,mjaniszew/electron,simongregory/electron,renaesop/electron,John-Lin/electron,micalan/electron,GoooIce/electron,destan/electron,kikong/electron,leolujuyi/electron,yan-foto/electron,yan-foto/electron,aaron-goshine/electron,biblerule/UMCTelnetHub,robinvandernoord/electron,John-Lin/electron,aichingm/electron,tylergibson/electron,ankitaggarwal011/electron,timruffles/electron,edulan/electron,maxogden/atom-shell,tincan24/electron,howmuchcomputer/electron,seanchas116/electron,shennushi/electron,simonfork/electron,Rokt33r/electron,yalexx/electron,aecca/electron,bpasero/electron,carsonmcdonald/electron,mattdesl/electron,kikong/electron,fireball-x/atom-shell,preco21/electron,cqqccqc/electron,jhen0409/electron,jaanus/electron,iftekeriba/electron,nekuz0r/electron,kcrt/electron,leftstick/electron,GoooIce/electron,fffej/electron,egoist/electron,RobertJGabriel/electron,egoist/electron,jannishuebl/electron,sshiting/electron,xfstudio/electron,GoooIce/electron,robinvandernoord/electron,gerhardberger/electron,meowlab/electron,christian-bromann/electron,tomashanacek/electron,coderhaoxin/electron,pirafrank/electron,evgenyzinoviev/electron,DivyaKMenon/electron,takashi/electron,kokdemo/electron,hokein/atom-shell,brave/electron,bpasero/electron,edulan/electron,GoooIce/electron,fritx/electron,gbn972/electron,shaundunne/electron,lzpfmh/electron,joneit/electron,carsonmcdonald/electron,sky7sea/electron,mubassirhayat/electron,faizalpribadi/electron,mattotodd/electron,medixdev/electron,IonicaBizauKitchen/electron,xfstudio/electron,rreimann/electron,IonicaBizauKitchen/electron,aaron-goshine/electron,arturts/electron,eriser/electron,jsutcodes/electron,thompsonemerson/electron,iftekeriba/electron,iftekeriba/electron,etiktin/electron,kostia/electron,wolfflow/electron,minggo/electron,soulteary/electron,howmuchcomputer/electron,trankmichael/electron,GoooIce/electron,jhen0409/electron,micalan/electron,miniak/electron,trankmichael/electron,simonfork/electron,maxogden/atom-shell,chrisswk/electron,kikong/electron,brave/muon,thingsinjars/electron,anko/electron,kazupon/electron,aliib/electron,aecca/electron,deed02392/electron,sircharleswatson/electron,tincan24/electron,jjz/electron,nicholasess/electron,christian-bromann/electron,davazp/electron,Ivshti/electron,jjz/electron,nicobot/electron,trigrass2/electron,jaanus/electron,deed02392/electron,mubassirhayat/electron,tylergibson/electron,gbn972/electron,mhkeller/electron,neutrous/electron,nekuz0r/electron,John-Lin/electron,adamjgray/electron,RIAEvangelist/electron,coderhaoxin/electron,Andrey-Pavlov/electron,Andrey-Pavlov/electron,leethomas/electron,shiftkey/electron,eric-seekas/electron,baiwyc119/electron,mrwizard82d1/electron,felixrieseberg/electron,astoilkov/electron,fabien-d/electron,twolfson/electron,kostia/electron,jtburke/electron,smczk/electron,Ivshti/electron,brenca/electron,thomsonreuters/electron,thingsinjars/electron,kostia/electron,setzer777/electron,bitemyapp/electron,d-salas/electron,micalan/electron,oiledCode/electron,tonyganch/electron,thompsonemerson/electron,mhkeller/electron,mattdesl/electron,shockone/electron,etiktin/electron,brave/electron,Andrey-Pavlov/electron,chrisswk/electron,John-Lin/electron,saronwei/electron,pandoraui/electron,xfstudio/electron,vipulroxx/electron,bbondy/electron,farmisen/electron,aaron-goshine/electron,thomsonreuters/electron,SufianHassan/electron,dkfiresky/electron,pirafrank/electron,aliib/electron,JesselJohn/electron,rsvip/electron,bbondy/electron,dongjoon-hyun/electron,JussMee15/electron,mhkeller/electron,destan/electron,MaxWhere/electron,noikiy/electron,trigrass2/electron,dongjoon-hyun/electron,michaelchiche/electron,Evercoder/electron,posix4e/electron,synaptek/electron,lrlna/electron,yan-foto/electron,ervinb/electron,Jacobichou/electron,JussMee15/electron,ankitaggarwal011/electron,zhakui/electron,brave/electron,kenmozi/electron,posix4e/electron,pandoraui/electron,nagyistoce/electron-atom-shell,stevekinney/electron,eriser/electron,shaundunne/electron,darwin/electron,stevemao/electron,bitemyapp/electron,kenmozi/electron,wan-qy/electron,Zagorakiss/electron,mubassirhayat/electron,ankitaggarwal011/electron,sky7sea/electron,gabrielPeart/electron,jacksondc/electron,felixrieseberg/electron,kazupon/electron,vHanda/electron,zhakui/electron,Zagorakiss/electron,fabien-d/electron,howmuchcomputer/electron,vaginessa/electron,Neron-X5/electron,renaesop/electron,systembugtj/electron,tinydew4/electron,rprichard/electron,cqqccqc/electron,jtburke/electron,meowlab/electron,shaundunne/electron,trankmichael/electron,rreimann/electron,bruce/electron,neutrous/electron,the-ress/electron,bitemyapp/electron,leftstick/electron,synaptek/electron,bruce/electron,roadev/electron,brave/muon,Gerhut/electron,Jonekee/electron,bbondy/electron,jlord/electron,Faiz7412/electron,Jacobichou/electron,gamedevsam/electron,leftstick/electron,kcrt/electron,wan-qy/electron,Floato/electron,bright-sparks/electron,kenmozi/electron,bwiggs/electron,shaundunne/electron,christian-bromann/electron,IonicaBizauKitchen/electron,dongjoon-hyun/electron,natgolov/electron,brenca/electron,Faiz7412/electron,tomashanacek/electron,fffej/electron,simongregory/electron,neutrous/electron,ervinb/electron,maxogden/atom-shell,simonfork/electron,posix4e/electron,trigrass2/electron,abhishekgahlot/electron,pirafrank/electron,greyhwndz/electron,aichingm/electron,rreimann/electron,vHanda/electron,Faiz7412/electron,the-ress/electron,trigrass2/electron,neutrous/electron,lrlna/electron,brenca/electron,nagyistoce/electron-atom-shell,neutrous/electron,John-Lin/electron,jcblw/electron,MaxGraey/electron,preco21/electron,JesselJohn/electron,yan-foto/electron,mjaniszew/electron,coderhaoxin/electron,Jonekee/electron,mjaniszew/electron,jaanus/electron,Rokt33r/electron,edulan/electron,arturts/electron,jonatasfreitasv/electron,xiruibing/electron,voidbridge/electron,Jonekee/electron,jacksondc/electron,yalexx/electron,chriskdon/electron,noikiy/electron,bitemyapp/electron,LadyNaggaga/electron,ianscrivener/electron,kazupon/electron,stevekinney/electron,bwiggs/electron,timruffles/electron,digideskio/electron,biblerule/UMCTelnetHub,fritx/electron,tomashanacek/electron,MaxWhere/electron,bpasero/electron,Rokt33r/electron,joneit/electron,Evercoder/electron,brave/electron,preco21/electron,fireball-x/atom-shell,dkfiresky/electron,saronwei/electron,tylergibson/electron,aaron-goshine/electron,dahal/electron,JesselJohn/electron,voidbridge/electron,arusakov/electron,neutrous/electron,leftstick/electron,Jonekee/electron,joneit/electron,aichingm/electron,bobwol/electron,darwin/electron,xiruibing/electron,deepak1556/atom-shell,fffej/electron,jjz/electron,Zagorakiss/electron,miniak/electron,Zagorakiss/electron,lzpfmh/electron,nicobot/electron,tinydew4/electron,nicholasess/electron,vaginessa/electron,fabien-d/electron,cqqccqc/electron,vaginessa/electron,tomashanacek/electron,tomashanacek/electron,ervinb/electron,abhishekgahlot/electron,JesselJohn/electron,SufianHassan/electron,gerhardberger/electron,etiktin/electron,rprichard/electron,oiledCode/electron,medixdev/electron,posix4e/electron,michaelchiche/electron,edulan/electron,beni55/electron,kostia/electron,bbondy/electron,rhencke/electron,jcblw/electron,rhencke/electron,sky7sea/electron,fabien-d/electron,the-ress/electron,fomojola/electron,adamjgray/electron,astoilkov/electron,rsvip/electron,vHanda/electron,aliib/electron,vipulroxx/electron,jlhbaseball15/electron,BionicClick/electron,bright-sparks/electron,renaesop/electron,baiwyc119/electron,meowlab/electron,kostia/electron,medixdev/electron,dkfiresky/electron,mhkeller/electron,tinydew4/electron,fritx/electron,chrisswk/electron,jiaz/electron,baiwyc119/electron,kostia/electron,kenmozi/electron,dongjoon-hyun/electron,lrlna/electron,JussMee15/electron,aecca/electron,greyhwndz/electron,lrlna/electron,mattotodd/electron,pombredanne/electron,MaxWhere/electron,Faiz7412/electron,gamedevsam/electron,kcrt/electron,chriskdon/electron,gbn972/electron,trigrass2/electron,kokdemo/electron,gstack/infinium-shell,setzer777/electron,jiaz/electron,sshiting/electron,leolujuyi/electron,Zagorakiss/electron,systembugtj/electron,adamjgray/electron,bwiggs/electron,wolfflow/electron,sshiting/electron,arusakov/electron,rprichard/electron,dahal/electron,subblue/electron,jlhbaseball15/electron,joaomoreno/atom-shell,Zagorakiss/electron,benweissmann/electron,roadev/electron,d-salas/electron,joneit/electron,jiaz/electron,xfstudio/electron,soulteary/electron,the-ress/electron,nicobot/electron,eriser/electron,xiruibing/electron,bobwol/electron,yalexx/electron,jacksondc/electron,anko/electron,egoist/electron,timruffles/electron,preco21/electron,dkfiresky/electron,deepak1556/atom-shell,destan/electron,joaomoreno/atom-shell,shockone/electron,stevemao/electron,leethomas/electron,michaelchiche/electron,medixdev/electron,farmisen/electron,stevekinney/electron,jonatasfreitasv/electron,jsutcodes/electron,nekuz0r/electron,adcentury/electron,tincan24/electron,yalexx/electron,gabriel/electron,abhishekgahlot/electron,egoist/electron,fritx/electron,rajatsingla28/electron,simongregory/electron,aecca/electron,fritx/electron,trankmichael/electron,bobwol/electron,stevemao/electron,seanchas116/electron,chriskdon/electron,aaron-goshine/electron,gabriel/electron,gamedevsam/electron,greyhwndz/electron,Andrey-Pavlov/electron,aichingm/electron,DivyaKMenon/electron,thomsonreuters/electron,cos2004/electron,mirrh/electron,synaptek/electron,zhakui/electron,John-Lin/electron,deed02392/electron,lrlna/electron,rhencke/electron,bpasero/electron,ankitaggarwal011/electron,vHanda/electron,simongregory/electron,natgolov/electron,mhkeller/electron,adamjgray/electron,brave/electron,ianscrivener/electron,biblerule/UMCTelnetHub,gamedevsam/electron,joaomoreno/atom-shell,chriskdon/electron,michaelchiche/electron,fritx/electron,Floato/electron,IonicaBizauKitchen/electron,arturts/electron,Gerhut/electron,Andrey-Pavlov/electron,noikiy/electron,LadyNaggaga/electron,BionicClick/electron,jaanus/electron,setzer777/electron,jannishuebl/electron,trankmichael/electron,nicholasess/electron,kenmozi/electron,bruce/electron,jhen0409/electron,jannishuebl/electron,dongjoon-hyun/electron,roadev/electron,astoilkov/electron,arusakov/electron,destan/electron,wolfflow/electron,iftekeriba/electron,brave/muon,Rokt33r/electron,IonicaBizauKitchen/electron,smczk/electron,shiftkey/electron,voidbridge/electron,deed02392/electron,coderhaoxin/electron,deepak1556/atom-shell,noikiy/electron,oiledCode/electron,micalan/electron,preco21/electron,takashi/electron,fffej/electron,mirrh/electron,jacksondc/electron,webmechanicx/electron,lzpfmh/electron,jsutcodes/electron,electron/electron,thomsonreuters/electron,zhakui/electron,natgolov/electron,ianscrivener/electron,nicobot/electron,beni55/electron,digideskio/electron,the-ress/electron,gabrielPeart/electron,LadyNaggaga/electron,oiledCode/electron,beni55/electron,pombredanne/electron,thompsonemerson/electron,mattdesl/electron,gbn972/electron,timruffles/electron,ervinb/electron,RIAEvangelist/electron,joaomoreno/atom-shell,howmuchcomputer/electron,jiaz/electron,gabrielPeart/electron,minggo/electron,beni55/electron,shiftkey/electron,hokein/atom-shell,michaelchiche/electron,jiaz/electron,anko/electron,stevemao/electron,meowlab/electron,thompsonemerson/electron,sircharleswatson/electron,faizalpribadi/electron,bright-sparks/electron,gabrielPeart/electron,cqqccqc/electron,leolujuyi/electron,felixrieseberg/electron,bitemyapp/electron,jlhbaseball15/electron,webmechanicx/electron,gabrielPeart/electron,abhishekgahlot/electron,tincan24/electron,sky7sea/electron,destan/electron,SufianHassan/electron,saronwei/electron,adcentury/electron,gbn972/electron,bpasero/electron,bpasero/electron,cqqccqc/electron,hokein/atom-shell,mjaniszew/electron,systembugtj/electron,jlord/electron,sircharleswatson/electron,nekuz0r/electron,dahal/electron,wan-qy/electron,gabriel/electron,joneit/electron,mattotodd/electron,tylergibson/electron,vipulroxx/electron,greyhwndz/electron,joneit/electron,gerhardberger/electron,roadev/electron,mrwizard82d1/electron,jhen0409/electron,electron/electron,systembugtj/electron,kcrt/electron,robinvandernoord/electron,nicobot/electron,sircharleswatson/electron,brave/muon,aichingm/electron
1c32b17bd4c85165f91fbb188b22471a296c6176
kajiki/i18n.py
kajiki/i18n.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand doc = _Parser(filename='<string>', source=fileobj.read()).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
Fix issue with message extractor on Py2
Fix issue with message extractor on Py2
Python
mit
ollyc/kajiki,ollyc/kajiki,ollyc/kajiki
c1785e0713a5af6b849baaa1b314a13ac777f3f5
tests/test_str_py3.py
tests/test_str_py3.py
from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits import fastavro from fastavro.compat import BytesIO letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
# -*- coding: utf-8 -*- """Python3 string tests for fastavro""" from __future__ import absolute_import from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import fastavro letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
Python
mit
e-heller/fastavro,e-heller/fastavro
df1397dcf6fe849b87db139e8ea3087a5f73649a
tests/graphics/toolbuttons.py
tests/graphics/toolbuttons.py
from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(named_icon='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(named_icon='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
from gi.repository import Gtk from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.graphics.colorbutton import ColorToolButton from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.toggletoolbutton import ToggleToolButton import common test = common.Test() test.show() vbox = Gtk.VBox() test.pack_start(vbox, True, True, 0) vbox.show() toolbar_box = ToolbarBox() vbox.pack_start(toolbar_box, False, False, 0) toolbar_box.show() radial_button = RadioToolButton(icon_name='view-radial') toolbar_box.toolbar.insert(radial_button, -1) radial_button.show() list_button = RadioToolButton(icon_name='view-list') list_button.props.group = radial_button toolbar_box.toolbar.insert(list_button, -1) list_button.show() separator = Gtk.SeparatorToolItem() toolbar_box.toolbar.insert(separator, -1) separator.show() color_button = ColorToolButton() toolbar_box.toolbar.insert(color_button, -1) color_button.show() favorite_button = ToggleToolButton('emblem-favorite') toolbar_box.toolbar.insert(favorite_button, -1) favorite_button.show() if __name__ == '__main__': common.main(test)
Update toolbar buttons testcase with API change for the icon name
Update toolbar buttons testcase with API change for the icon name Follow up of fe11a3aa23c0e7fbc3c0c498e147b0a20348cc12 . Signed-off-by: Manuel Quiñones <6f5069c5b6be23302a13accec56587944be09079@laptop.org>
Python
lgpl-2.1
i5o/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,sugarlabs/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,samdroid-apps/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,samdroid-apps/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3
2f56d481c05e28a4434a038a356f521b4ea5cbca
tests/test_simple_features.py
tests/test_simple_features.py
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per_second(): datapoints = time_values(float(i) for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_monotonic_down_per_second(): datapoints = time_values(10.0 - i for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_tent_map(): values = list(float(i) for i in range(10)) values.append(11.0) values+= list(10.0 - i for i in range(10)) datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per_second(): datapoints = time_values(float(i) for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_monotonic_down_per_second(): datapoints = time_values(10.0 - i for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_tent_map(): values = [float(i) for i in range(10)] values.append(11.0) values += [10.0 - i for i in range(10)] datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features def test_step_function(): values = [1.0] * 10 values += [2.0] * 10 datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features
Test case for step function in time series
Test case for step function in time series Test a graph function that is linear in two time periods, jumping between linear values.
Python
apache-2.0
tleeuwenburg/wordgraph,tleeuwenburg/wordgraph
9051fc68b2c542f7a201a969340b1f1f5d0f660c
test_openfolder.py
test_openfolder.py
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception): open_folder("it_is_very_unlikely_that_this_file_exists_20150718") def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception): result = open_folder("/") def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
import pytest from mock import patch, MagicMock from open_folder import * def test_folder_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): result = open_folder(".") assert result == None def test_folder_does_not_exists(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with pytest.raises(Exception) as excinfo: open_folder("it_is_very_unlikely_that_this_file_exists_20150718") assert str(excinfo.value) == ('Folder does not exist.') def test_unsupported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="NotDarwinWindowsLinux")): with pytest.raises(Exception) as excinfo: open_folder("/") assert str(excinfo.value).startswith('Your operating system was not recognized.') def test_supported_os(): with patch('subprocess.check_call', MagicMock(return_value="NOOP")): with patch('platform.system', MagicMock(return_value="Linux")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Darwin")): result = open_folder("/") assert result == None with patch('platform.system', MagicMock(return_value="Windows")): result = open_folder("/") assert result == None
Check to ensure the exceptions return the text we expect.
Check to ensure the exceptions return the text we expect.
Python
mit
golliher/dg-tickler-file
e5fa10e27d9c5911b0238d23fc13acc081accc79
utils/dates.py
utils/dates.py
# This file is part of e-Giełda. # Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński # # e-Giełda 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. # # You should have received a copy of the GNU Affero General Public License # along with e-Giełda. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(datetime): return datetime.strftime(datetime, DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
# This file is part of e-Giełda. # Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński # # e-Giełda 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. # # You should have received a copy of the GNU Affero General Public License # along with e-Giełda. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta DT_FORMAT = '%Y-%m-%d %H:%M:%S%z' def datetime_html_format(date): return date.strftime("%Y-%m-%dT%H:%M") def datetime_to_string(date): return date.strftime(DT_FORMAT) def string_to_datetime(date): return datetime.strptime(date, DT_FORMAT) def date_range(start_date, end_date): return list(start_date + timedelta(x) for x in range((end_date - start_date).days + 1))
Fix error on date save
Fix error on date save
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
ca430300c08f78b7c2de4153e08c1645996f85b7
tests/test_parsers.py
tests/test_parsers.py
import unittest from brew.parsers import JSONDataLoader class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
import unittest from brew.parsers import DataLoader from brew.parsers import JSONDataLoader class TestDataLoader(unittest.TestCase): def setUp(self): self.parser = DataLoader('./') def test_read_data_raises(self): with self.assertRaises(NotImplementedError): self.parser.read_data('filename') class TestJSONDataLoader(unittest.TestCase): def setUp(self): self.parser = JSONDataLoader('./') def test_format_name(self): name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'), ('caramel crystal malt 20l', 'caramel_crystal_malt_20l'), ('centennial', 'centennial'), ('cascade us', 'cascade_us'), ('Wyeast 1056', 'wyeast_1056'), ] for name, expected in name_list: out = self.parser.format_name(name) self.assertEquals(out, expected)
Add test to DataLoader base class
Add test to DataLoader base class
Python
mit
chrisgilmerproj/brewday,chrisgilmerproj/brewday
17d2d4eaf58011ceb33a4d5944253578c2b5edd1
pmdarima/preprocessing/endog/tests/test_log.py
pmdarima/preprocessing/endog/tests/test_log.py
# -*- coding: utf-8 -*- import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer() log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t)
# -*- coding: utf-8 -*- import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer(lmbda=0) log_trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) log_y_t, _ = log_trans.fit_transform(y) assert_array_almost_equal(log_y_t, y_t) def test_invertible(): y = [1, 2, 3] trans = LogEndogTransformer() y_t, _ = trans.fit_transform(y) y_prime, _ = trans.inverse_transform(y_t) assert_array_almost_equal(y, y_prime)
Add test_invertible to log transformer test
Add test_invertible to log transformer test
Python
mit
alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima,tgsmith61591/pyramid
5c1f9b0a70fe47bbfa7d3813a47e2da81cd81506
tests/runalldoctests.py
tests/runalldoctests.py
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file)
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
Add option to pick single test file from the runner
Add option to pick single test file from the runner git-svn-id: 8e0fbe17d71f9a07a4f24b82f5b9fb44b438f95e@620 b426a367-1105-0410-b9ff-cdf4ab011145
Python
bsd-3-clause
sabman/OWSLib,monoid/owslib,monoid/owslib
61bbd4e8fc0712fe56614481173eb86d409eb8d7
tests/test_linked_list.py
tests/test_linked_list.py
from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Fix range issue with travis
Fix range issue with travis
Python
mit
apranav19/pystructures
01c0dd4d34e61df589b3dd9ee3c5f8b96cf5486b
tests/test_transformer.py
tests/test_transformer.py
from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester("TEST", TEST_SCHEMA, TEST_NAMESPACES) def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
from __future__ import unicode_literals import functools from scrapi.base import XMLHarvester from scrapi.linter import RawDocument from .utils import get_leaves from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC class TestHarvester(XMLHarvester): def harvest(self, days_back=1): return [RawDocument({ 'doc': str(TEST_XML_DOC), 'source': 'TEST', 'filetype': 'XML', 'docID': "1" }) for _ in xrange(days_back)] @property def name(self): return 'TEST' @property def namespaces(self): return TEST_NAMESPACES @property def schema(self): return TEST_SCHEMA class TestTransformer(object): def setup_method(self, method): self.harvester = TestHarvester() def test_normalize(self): results = [ self.harvester.normalize(record) for record in self.harvester.harvest(days_back=10) ] for result in results: assert result['properties']['title1'] == 'Test' assert result['properties']['title2'] == 'test' assert result['properties']['title3'] == 'Testtest' for (k, v) in get_leaves(result.attributes): assert type(v) != functools.partial
Update tests with required properties
Update tests with required properties
Python
apache-2.0
CenterForOpenScience/scrapi,jeffreyliu3230/scrapi,fabianvf/scrapi,felliott/scrapi,erinspace/scrapi,icereval/scrapi,mehanig/scrapi,ostwald/scrapi,erinspace/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi
46d274401080d47f3a9974c6ee80f2f3b9c0c8b0
metakernel/magics/tests/test_download_magic.py
metakernel/magics/tests/test_download_magic.py
from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" def teardown(): try: os.remove("TEST.txt") except: pass
from metakernel.tests.utils import (get_kernel, get_log_text, clear_log_text, EvalKernel) import os def test_download_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'TEST.txt'" in text, text assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt" clear_log_text(kernel) kernel.do_execute("%download https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt") text = get_log_text(kernel) assert "Downloaded 'LICENSE.txt'" in text, text assert os.path.isfile("LICENSE.txt"), "File does not exist: LICENSE.txt" def teardown(): for fname in ['TEST.txt', 'LICENSE.txt']: try: os.remove(fname) except: pass
Add download test without filename
Add download test without filename
Python
bsd-3-clause
Calysto/metakernel
6220c36f046b2b504cc2ebbbc04a34c4d826564d
IPython/extensions/tests/test_storemagic.py
IPython/extensions/tests/test_storemagic.py
import tempfile, os import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) os.rmdir(tmpd)
import tempfile, os from IPython.config.loader import Config import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) os.rmdir(tmpd) def test_autorestore(): ip.user_ns['foo'] = 95 ip.magic('store foo') del ip.user_ns['foo'] c = Config() c.StoreMagics.autorestore = False orig_config = ip.config try: ip.config = c ip.extension_manager.reload_extension('storemagic') nt.assert_not_in('foo', ip.user_ns) c.StoreMagics.autorestore = True ip.extension_manager.reload_extension('storemagic') nt.assert_equal(ip.user_ns['foo'], 95) finally: ip.config = orig_config
Add test for StoreMagics.autorestore option
Add test for StoreMagics.autorestore option
Python
bsd-3-clause
ipython/ipython,ipython/ipython
975a5010e97b11b9b6f00923c87268dd883b1cfa
2017-code/opt/test1.py
2017-code/opt/test1.py
# test1.py # Ronald L. Rivest and Karim Husayn Karimi # August 17, 2017 # Routine to experiment with scipy.optimize.minimize import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.0000005 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), constraints=constraints))
# test1.py # Ronald L. Rivest and Karim Husayn Karimi # August 17, 2017 # Routine to experiment with scipy.optimize.minimize import scipy.optimize from scipy.stats import norm # function to minimize: def g(xy): (x,y) = xy print("g({},{})".format(x,y)) return x + y # constraints noise_level = 0.05 # constraint 1: y <= x/2 def f1(xy): (x,y) = xy return x/2 - y + noise_level * norm.rvs(0) # constraint 2: y >= 1/x def f2(xy): (x,y) = xy return y - 1.0/x + noise_level * norm.rvs(0) constraints = [ { "type": "ineq", "fun": f1 }, { "type": "ineq", "fun": f2 } ] print(scipy.optimize.minimize(g, (11, 5), method = "COBYLA", tol = 0.01, constraints=constraints))
Switch to COBYLA optimization method. Works much better.
Switch to COBYLA optimization method. Works much better.
Python
mit
ron-rivest/2017-bayes-audit,ron-rivest/2017-bayes-audit
76cf350b4ca48455e9ae7d6288d992389a8ec0b5
src/toil/provisioners/azure/__init__.py
src/toil/provisioners/azure/__init__.py
# Copyright (C) 2015-2016 Regents of the University of California # # 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 os def getAzureZone(defaultZone=None): """ Find an appropriate azure zone. Look for an environment variable or return a default as provided. :param defaultZone: The zone specified in the leader metadata. :return zone: The zone. """ return os.environ.get('TOIL_AZURE_ZONE') or defaultZone
# Copyright (C) 2015-2016 Regents of the University of California # # 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.
Remove getAzureZone from init, no longer needed.
Remove getAzureZone from init, no longer needed.
Python
apache-2.0
BD2KGenomics/slugflow,BD2KGenomics/slugflow
6941d9048a8c630244bb48100864872b35a1a307
tests/functional/test_layout_and_styling.py
tests/functional/test_layout_and_styling.py
import os from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", self.browser.page_source.strip()) self.assertIn( "//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js", self.browser.page_source.strip()) self.assertIn( '//code.jquery.com/jquery.min.js', self.browser.page_source.strip())
from .base import FunctionalTest class LayoutStylingTest(FunctionalTest): def test_bootstrap_links_loaded_successfully(self): self.browser.get(self.live_server_url) links = [link.get_attribute("href") for link in self.browser.find_elements_by_tag_name('link')] scripts = [script.get_attribute("src") for script in self.browser.find_elements_by_tag_name('script')] self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" in link for link in links]) self.assertTrue( ["//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" in link for link in links]) self.assertTrue( ["//code.jquery.com/jquery.min.js" in link for link in scripts])
Fix bootstrap and jQuery link checking in homepage
Fix bootstrap and jQuery link checking in homepage
Python
bsd-3-clause
andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop
7375c41b1d9bd5ca153df80705ae1887e6f2e70b
api/base/exceptions.py
api/base/exceptions.py
def jsonapi_exception_handler(exc, context): """ Custom exception handler that nests detail inside errors. """ from rest_framework.views import exception_handler response = exception_handler(exc, context) if response is not None: if 'detail' in response.data: response.data = {'errors': [response.data]} else: response.data = {'errors': [{'detail': response.data}]} return response
def jsonapi_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array with a 'detail' member """ from rest_framework.views import exception_handler response = exception_handler(exc, context) if response is not None: if 'detail' in response.data: response.data = {'errors': [response.data]} else: response.data = {'errors': [{'detail': response.data}]} return response
Change docstring for exception handler
Change docstring for exception handler
Python
apache-2.0
RomanZWang/osf.io,felliott/osf.io,cosenal/osf.io,caseyrollins/osf.io,aaxelb/osf.io,aaxelb/osf.io,ckc6cz/osf.io,zamattiac/osf.io,emetsger/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,petermalcolm/osf.io,mfraezz/osf.io,crcresearch/osf.io,MerlinZhang/osf.io,mluke93/osf.io,hmoco/osf.io,emetsger/osf.io,felliott/osf.io,ckc6cz/osf.io,caseyrollins/osf.io,aaxelb/osf.io,samanehsan/osf.io,brianjgeiger/osf.io,kwierman/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,mluke93/osf.io,cosenal/osf.io,sbt9uc/osf.io,pattisdr/osf.io,sloria/osf.io,amyshi188/osf.io,leb2dg/osf.io,brandonPurvis/osf.io,crcresearch/osf.io,felliott/osf.io,mluo613/osf.io,caseyrygt/osf.io,doublebits/osf.io,SSJohns/osf.io,alexschiller/osf.io,TomBaxter/osf.io,mattclark/osf.io,RomanZWang/osf.io,doublebits/osf.io,cslzchen/osf.io,icereval/osf.io,erinspace/osf.io,MerlinZhang/osf.io,doublebits/osf.io,Johnetordoff/osf.io,acshi/osf.io,KAsante95/osf.io,jnayak1/osf.io,danielneis/osf.io,petermalcolm/osf.io,zamattiac/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,haoyuchen1992/osf.io,baylee-d/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,aaxelb/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,acshi/osf.io,sloria/osf.io,pattisdr/osf.io,njantrania/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,Johnetordoff/osf.io,billyhunt/osf.io,mattclark/osf.io,KAsante95/osf.io,arpitar/osf.io,caneruguz/osf.io,ckc6cz/osf.io,abought/osf.io,jmcarp/osf.io,zachjanicki/osf.io,abought/osf.io,mattclark/osf.io,crcresearch/osf.io,mluo613/osf.io,asanfilippo7/osf.io,wearpants/osf.io,mfraezz/osf.io,samchrisinger/osf.io,adlius/osf.io,chrisseto/osf.io,danielneis/osf.io,samanehsan/osf.io,samanehsan/osf.io,sloria/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,GageGaskins/osf.io,alexschiller/osf.io,Ghalko/osf.io,binoculars/osf.io,doublebits/osf.io,Nesiehr/osf.io,chrisseto/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,alexschiller/osf.io,emetsger/osf.io,haoyuchen1992/osf.io,chrisseto/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,mfraezz/osf.io,abought/osf.io,emetsger/osf.io,amyshi188/osf.io,chennan47/osf.io,zachjanicki/osf.io,kch8qx/osf.io,mluke93/osf.io,acshi/osf.io,doublebits/osf.io,billyhunt/osf.io,leb2dg/osf.io,ckc6cz/osf.io,mluo613/osf.io,monikagrabowska/osf.io,sbt9uc/osf.io,TomHeatwole/osf.io,caneruguz/osf.io,Ghalko/osf.io,billyhunt/osf.io,leb2dg/osf.io,asanfilippo7/osf.io,erinspace/osf.io,zamattiac/osf.io,KAsante95/osf.io,cslzchen/osf.io,kch8qx/osf.io,kch8qx/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,cwisecarver/osf.io,SSJohns/osf.io,adlius/osf.io,jmcarp/osf.io,CenterForOpenScience/osf.io,RomanZWang/osf.io,kwierman/osf.io,laurenrevere/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,MerlinZhang/osf.io,kwierman/osf.io,GageGaskins/osf.io,KAsante95/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,MerlinZhang/osf.io,Ghalko/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,rdhyee/osf.io,asanfilippo7/osf.io,njantrania/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,baylee-d/osf.io,jmcarp/osf.io,kch8qx/osf.io,njantrania/osf.io,rdhyee/osf.io,petermalcolm/osf.io,sbt9uc/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,cosenal/osf.io,felliott/osf.io,Nesiehr/osf.io,hmoco/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,erinspace/osf.io,acshi/osf.io,saradbowman/osf.io,TomBaxter/osf.io,Ghalko/osf.io,kch8qx/osf.io,TomHeatwole/osf.io,chennan47/osf.io,ticklemepierce/osf.io,Nesiehr/osf.io,billyhunt/osf.io,icereval/osf.io,mluo613/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,haoyuchen1992/osf.io,icereval/osf.io,arpitar/osf.io,sbt9uc/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,njantrania/osf.io,baylee-d/osf.io,caseyrygt/osf.io,DanielSBrown/osf.io,brandonPurvis/osf.io,binoculars/osf.io,GageGaskins/osf.io,caseyrygt/osf.io,mluke93/osf.io,jmcarp/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,wearpants/osf.io,cslzchen/osf.io,mfraezz/osf.io,pattisdr/osf.io,wearpants/osf.io,samchrisinger/osf.io,abought/osf.io,HalcyonChimera/osf.io,caseyrygt/osf.io,binoculars/osf.io,kwierman/osf.io,zachjanicki/osf.io,acshi/osf.io,ZobairAlijan/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,hmoco/osf.io,DanielSBrown/osf.io,alexschiller/osf.io,zachjanicki/osf.io,danielneis/osf.io,rdhyee/osf.io,samanehsan/osf.io,petermalcolm/osf.io,hmoco/osf.io,ticklemepierce/osf.io,ZobairAlijan/osf.io,arpitar/osf.io,billyhunt/osf.io,saradbowman/osf.io,zamattiac/osf.io,KAsante95/osf.io,caneruguz/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,samchrisinger/osf.io,SSJohns/osf.io,cosenal/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,danielneis/osf.io,Johnetordoff/osf.io,adlius/osf.io,leb2dg/osf.io,SSJohns/osf.io,TomBaxter/osf.io,arpitar/osf.io
6d624d693a05749879f4184231e727590542db03
backend/globaleaks/tests/utils/test_zipstream.py
backend/globaleaks/tests/utils/test_zipstream.py
# -*- encoding: utf-8 -*- import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.files = [] for k in self.internationalized_text: self.files.append({'name': self.internationalized_text[k].encode('utf8'), 'buf': self.internationalized_text[k].encode('utf-8')}) def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip())
# -*- encoding: utf-8 -*- import os import StringIO from twisted.internet.defer import inlineCallbacks from zipfile import ZipFile from globaleaks.tests import helpers from globaleaks.utils.zipstream import ZipStream class TestZipStream(helpers.TestGL): @inlineCallbacks def setUp(self): yield helpers.TestGL.setUp(self) self.unicode_seq = ''.join(unichr(x) for x in range(0x400, 0x40A)) self.files = [ {'name': self.unicode_seq, 'buf': self.unicode_seq}, {'name': __file__, 'path': os.path.abspath(__file__)} ] def test_zipstream(self): output = StringIO.StringIO() for data in ZipStream(self.files): output.write(data) with ZipFile(output, 'r') as f: self.assertIsNone(f.testzip()) with ZipFile(output, 'r') as f: infolist = f.infolist() self.assertTrue(len(infolist), 2) for ff in infolist: if ff.filename == self.unicode_seq: self.assertTrue(ff.file_size == len(self.unicode_seq)) else: self.assertTrue(ff.file_size == os.stat(os.path.abspath(__file__)).st_size)
Improve unit testing of zipstream utilities
Improve unit testing of zipstream utilities
Python
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
92138f23dfc5dbbcb81aeb1f429e68a63a9d5005
apps/organizations/admin.py
apps/organizations/admin.py
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) admin.site.register(OrganizationMember)
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 0 class OrganizationAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} inlines = (OrganizationAddressAdmin,) search_fields = ('name', 'description') admin.site.register(Organization, OrganizationAdmin) class OrganizationMemberAdmin(admin.ModelAdmin): list_display = ('user', 'function', 'organization') list_filter = ('function',) search_fields = ('user__first_name', 'user__last_name', 'user__username', 'organization__name') admin.site.register(OrganizationMember, OrganizationMemberAdmin)
Add a custom Admin page for organization members.
Add a custom Admin page for organization members. This is a partial fix for BB-66.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
539608a9ca9a21707184496e744fc40a8cb72cc1
announce/management/commands/migrate_mailchimp_users.py
announce/management/commands/migrate_mailchimp_users.py
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) for user in to_update: user.profile.communication_opt_in = True user.profile.save()
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub)
Remove once of code for mailchimp list migration
Remove once of code for mailchimp list migration
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
c93cb479446fbe12e019550f193cb45dbdc1e3e0
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
# -*- coding: utf-8 -*- import pytest def pytest_addoption(parser): group = parser.getgroup('{{cookiecutter.plugin_name}}') group.addoption( '--foo', action='store', dest='foo', help='alias for --foo' ) @pytest.fixture def bar(request): return request.config.option.foo
# -*- coding: utf-8 -*- import pytest def pytest_addoption(parser): group = parser.getgroup('{{cookiecutter.plugin_name}}') group.addoption( '--foo', action='store', dest='foo', help='Set the value for the fixture "bar".' ) @pytest.fixture def bar(request): return request.config.option.foo
Optimize the help message for the option arg
Optimize the help message for the option arg
Python
mit
luzfcb/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin
3d7bbd37485dca4782ad7e7fdb088b22db586b66
pyscores/config.py
pyscores/config.py
BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "PL": "426", "ELC": "427", "EL1": "428", "FAC": "429", "BL1": "430", "BL2": "431", "DFB": "432", "DED": "433", "FL1": "434", "FL2": "435", "PD": "436", "SD": "437", "SA": "438", "PPL": "439", "CL": "440", "SB": "441", "ENL": "442", "EL2": "443" }
BASE_URL = "http://api.football-data.org/v1" LEAGUE_IDS = { "BSA": "444", "PL": "445", "ELC": "446", "EL1": "447", "EL2": "448", "DED": "449", "FL1": "450", "FL2": "451", "BL1": "452", "BL2": "453", "PD": "455", "SA": "456", "PPL": "457", "DFB": "458", "SB": "459", "CL": "464", "AAL": "466" }
Update league codes for new season
Update league codes for new season
Python
mit
conormag94/pyscores
a476c42216af99488c2e02bacd29f7e3a869a3e7
tests/retrieval_metrics/test_precision_at_k.py
tests/retrieval_metrics/test_precision_at_k.py
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected)
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected, atol=1e-05)
Update atol on precision at k test.
Update atol on precision at k test.
Python
apache-2.0
tensorflow/similarity
b1a3a17460ae1f68c6c9bf60ecbd6a3b80a95abe
billjobs/tests/tests_model.py
billjobs/tests/tests_model.py
from django.test import TestCase, Client from django.contrib.auth.models import User from billjobs.models import Bill, Service from billjobs.settings import BILLJOBS_BILL_ISSUER class BillingTestCase(TestCase): ''' Test billing creation and modification ''' fixtures = ['dev_data.json'] def setUp(self): self.client = Client() self.client.login(username='bill', password='jobs') def tearDown(self): self.client.logout() def test_create_bill_with_one_line(self): ''' Test when user is created a bill with a single service ''' #response = self.client.get('/admin/billjobs/bill/add/', follow_redirect=True) #self.assertEqual(response.status_code, 200) self.assertTrue(True) def test_create_bill(self): user = User.objects.get(username='bill') bill = Bill(user=user) bill.save() self.assertEqual(bill.user.username, 'bill') self.assertEqual(bill.issuer_address, BILLJOBS_BILL_ISSUER) self.assertEqual( bill.billing_address, user.userprofile.billing_address)
from django.test import TestCase, Client from django.contrib.auth.models import User from billjobs.models import Bill, Service from billjobs.settings import BILLJOBS_BILL_ISSUER class BillingTestCase(TestCase): ''' Test billing creation and modification ''' fixtures = ['dev_data.json'] def setUp(self): self.user = User.objects.get(username='bill') def tearDown(self): pass def test_create_bill_with_one_line(self): ''' Test when user is created a bill with a single service ''' #response = self.client.get('/admin/billjobs/bill/add/', follow_redirect=True) #self.assertEqual(response.status_code, 200) self.assertTrue(True) def test_create_bill(self): bill = Bill(user=self.user) bill.save() self.assertEqual(bill.user.username, self.user.username) self.assertEqual(bill.issuer_address, BILLJOBS_BILL_ISSUER) self.assertEqual( bill.billing_address, self.user.userprofile.billing_address) def test_user_change_billing_address(self): ''' Test when user is changing is billing address Previous bill is with old address New bill is with new address ''' pass
Refactor test to use user
Refactor test to use user
Python
mit
ioO/billjobs
ed8423041abc80b778bf9ffed61e3dad246d72ff
bucketeer/test/test_commit.py
bucketeer/test/test_commit.py
import unittest import boto from bucketeer import commit class BuckeeterTest(unittest.TestCase): def setUp(self): # Create a bucket with one file connection = boto.connect_s3() bucket = connection.create_bucket('bucket.exists') return def tearDown(self): # Remove all test-created buckets and files connection = boto.connect_s3() bucket = connection.delete_bucket('bucket.exists') return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
import unittest import boto from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket existing_bucket = 'bucket.exists' def setUp(self): # Create a bucket with one file connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) return def tearDown(self): # Remove all test-created buckets and files connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
Refactor bucket name to global variable
Refactor bucket name to global variable
Python
mit
mgarbacz/bucketeer
d0367aacfea7c238c476772a2c83f7826b1e9de5
corehq/apps/export/tasks.py
corehq/apps/export/tasks.py
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) def rebuild_export_task(export_instance): rebuild_export(export_instance)
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter)
Fix botched keyword args in rebuild_export_task()
Fix botched keyword args in rebuild_export_task()
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
bddd7cb9131dd61a8167fe9db5bbc3b02f8e3add
tests/main.py
tests/main.py
#!/usr/bin/env python """ Tests for python-bna >>> import bna >>> serial = "US120910711868" >>> secret = b"88aaface48291e09dc1ece9c2aa44d839983a7ff" >>> bna.get_token(secret, time=1347279358) (93461643, 2) >>> bna.get_token(secret, time=1347279359) (93461643, 1) >>> bna.get_token(secret, time=1347279360) (86031001, 30) >>> bna.get_restore_code(serial, secret) '4B91NQCYQ3' >>> bna.normalize_serial(bna.prettify_serial(serial)) == serial True """ if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python """ Tests for python-bna >>> import bna >>> serial = "US120910711868" >>> secret = b"88aaface48291e09dc1ece9c2aa44d839983a7ff" >>> bna.get_token(secret, time=1347279358) (93461643, 2) >>> bna.get_token(secret, time=1347279359) (93461643, 1) >>> bna.get_token(secret, time=1347279360) (86031001, 30) >>> bna.get_restore_code(serial, secret) '4B91NQCYQ3' >>> bna.normalize_serial(bna.prettify_serial(serial)) == serial True >>> bna.get_otpauth_url(serial, secret) 'otpauth://totp/Battle.net:US120910711868:?secret=HA4GCYLGMFRWKNBYGI4TCZJQHFSGGMLFMNSTSYZSMFQTINDEHAZTSOJYGNQTOZTG&issuer=Battle.net&digits=8' """ if __name__ == "__main__": import doctest doctest.testmod()
Add a test for bna.get_otpauth_url
Add a test for bna.get_otpauth_url
Python
mit
jleclanche/python-bna,Adys/python-bna
86a325777742e1fa79bc632fca9460f3b1b8eb16
to_do/urls.py
to_do/urls.py
from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
from django.conf.urls import patterns, include, url from task.views import TaskList, TaskView, get_task_list # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TaskList.as_view(), name='TaskList'), url(r'^task/', TaskView.as_view(), name='TaskView'), url(r'^tasks/', get_task_list, name='get_task_list'), url(r'^admin/', include(admin.site.urls)), ) """ MyModel = Backbone.Model.extend({ url: function(){ "API/" return "API/MyModel/" +this.get("id"); } }); MyCollection = Backbone.Collection.extend({ model: MyModel , url: "API/MyModels" }); """
Enable url to get all list of tasks by ajax
Enable url to get all list of tasks by ajax
Python
mit
rosadurante/to_do,rosadurante/to_do
49975504a590a1ae53e2e8cc81aadea277cc5600
cvrminer/app/__init__.py
cvrminer/app/__init__.py
"""cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
"""cvrminer app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap, StaticCDN def create_app(smiley=False): """Create app. Factory for app. Parameters ---------- smiley : bool, optional Determines whether the smiley functionality should be setup. """ app = Flask(__name__) Bootstrap(app) # Serve assets from wmflabs for privacy reasons app.extensions['bootstrap']['cdns']['jquery'] = StaticCDN() app.extensions['bootstrap']['cdns']['bootstrap'] = StaticCDN() if smiley: from ..smiley import Smiley app.smiley = Smiley() else: app.smiley = None from .views import main as main_blueprint app.register_blueprint(main_blueprint) return app
Change to use local Javascript and CSS files
Change to use local Javascript and CSS files
Python
apache-2.0
fnielsen/cvrminer,fnielsen/cvrminer,fnielsen/cvrminer
3b4322b8de8ffdc691f08fbf7f35e6ec5293f41e
crm_job_position/models/crm_job_position.py
crm_job_position/models/crm_job_position.py
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmJobPosition(models.Model): _name = 'crm.job_position' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Job position" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.job_position') children = fields.One2many(comodel_name='crm.job_position', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmJobPosition(models.Model): _name = 'crm.job_position' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Job position" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.job_position') children = fields.One2many(comodel_name='crm.job_position', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Set some fields as tranlate
Set some fields as tranlate
Python
agpl-3.0
acsone/partner-contact,Therp/partner-contact,diagramsoftware/partner-contact,Endika/partner-contact,open-synergy/partner-contact
f7bfcd7fee64ae9220710835974125f41dae1c50
frappe/core/doctype/role/test_role.py
frappe/core/doctype/role/test_role.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
Test Case for disabled role
fix: Test Case for disabled role
Python
mit
mhbu50/frappe,mhbu50/frappe,saurabh6790/frappe,frappe/frappe,saurabh6790/frappe,vjFaLk/frappe,StrellaGroup/frappe,vjFaLk/frappe,yashodhank/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,yashodhank/frappe,frappe/frappe,vjFaLk/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,yashodhank/frappe,mhbu50/frappe,almeidapaulopt/frappe,frappe/frappe,saurabh6790/frappe,saurabh6790/frappe
82121f05032f83de538c4a16596b24b5b012a3be
chaco/shell/tests/test_tutorial_example.py
chaco/shell/tests/test_tutorial_example.py
""" Test script-oriented example from interactive plotting tutorial source: docs/source/user_manual/chaco_tutorial.rst """ import unittest from numpy import linspace, pi, sin from enthought.chaco.shell import plot, show, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
""" Test script-oriented example from interactive plotting tutorial source: docs/source/user_manual/chaco_tutorial.rst """ import unittest from numpy import linspace, pi, sin from chaco.shell import plot, title, ytitle class InteractiveTestCase(unittest.TestCase): def test_script(self): x = linspace(-2*pi, 2*pi, 100) y = sin(x) plot(x, y, "r-") title("First plot") ytitle("sin(x)") if __name__ == "__main__": unittest.main()
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
Python
bsd-3-clause
tommy-u/chaco,burnpanck/chaco,burnpanck/chaco,tommy-u/chaco,tommy-u/chaco,burnpanck/chaco
e029998f73a77ebd8f4a6e32a8b03edcc93ec0d7
dataproperty/__init__.py
dataproperty/__init__.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len, strict_strtobool ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from ._align import Align from ._align_getter import align_getter from ._container import MinMaxContainer from ._data_property import ( ColumnDataProperty, DataProperty ) from ._error import TypeConversionError from ._function import ( is_integer, is_hex, is_float, is_nan, is_empty_string, is_not_empty_string, is_list_or_tuple, is_empty_sequence, is_not_empty_sequence, is_empty_list_or_tuple, is_not_empty_list_or_tuple, is_datetime, get_integer_digit, get_number_of_digit, get_text_len ) from ._property_extractor import PropertyExtractor from ._type import ( NoneType, StringType, IntegerType, FloatType, DateTimeType, BoolType, InfinityType, NanType ) from ._typecode import Typecode
Delete import that no longer used
Delete import that no longer used
Python
mit
thombashi/DataProperty
69abcf66d36079e100815f629487d121ae016ee9
future/tests/test_standard_library_renames.py
future/tests/test_standard_library_renames.py
""" Tests for the future.standard_library_renames module """ from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue heap = ['thing', 'another thing'] queue.heapq.heapify(heap) self.assertEqual(heap, ['another thing', 'thing']) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
""" Tests for the future.standard_library_renames module """ from __future__ import absolute_import, unicode_literals, print_function from future import standard_library_renames, six import unittest class TestStandardLibraryRenames(unittest.TestCase): def test_configparser(self): import configparser def test_copyreg(self): import copyreg def test_pickle(self): import pickle def test_profile(self): import profile def test_io(self): from io import StringIO s = StringIO('test') for method in ['next', 'read', 'seek', 'close']: self.assertTrue(hasattr(s, method)) def test_queue(self): import queue q = queue.Queue() q.put('thing') self.assertFalse(q.empty()) # 'markupbase': '_markupbase', def test_reprlib(self): import reprlib def test_socketserver(self): import socketserver def test_tkinter(self): import tkinter # '_winreg': 'winreg', def test_builtins(self): import builtins self.assertTrue(hasattr(builtins, 'tuple')) if __name__ == '__main__': unittest.main()
Fix test for queue module
Fix test for queue module I was testing heapq before ;) ...
Python
mit
QuLogic/python-future,QuLogic/python-future,krischer/python-future,michaelpacer/python-future,michaelpacer/python-future,krischer/python-future,PythonCharmers/python-future,PythonCharmers/python-future
f266132c05c37469290027e7aa8000d1f9a19a6c
tst/colors.py
tst/colors.py
YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN="\033[9;32m" WHITE="\033[1;37m" LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m'
YELLOW = '\033[1;33m' LRED = '\033[1;31m' LGREEN = '\033[1;32m' GREEN = '\033[9;32m' WHITE = '\033[0;37m' LWHITE = '\033[1;37m' LCYAN = '\033[1;36m' LBLUE = '\033[1;34m' RESET = '\033[0m' CRITICAL = '\033[41;37m'
Add some new color codes
Add some new color codes
Python
agpl-3.0
daltonserey/tst,daltonserey/tst
038978f87883247a14e9bec08708452c98c91285
test/test_chimera.py
test/test_chimera.py
import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
import unittest import utils import os import sys import re import shutil import subprocess TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) import cryptosite.chimera class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to chimera""" for args in ([], ['x'] * 4): out = utils.check_output(['cryptosite', 'chimera'] + args, stderr=subprocess.STDOUT, retcode=2) out = utils.check_output(['python', '-m', 'cryptosite.chimera'] + args, stderr=subprocess.STDOUT, retcode=2) def test_make_chimera_file(self): """Test make_chimera_file() function""" cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax') with open('out.chimerax') as fh: lines = fh.readlines() self.assertEqual(lines[-4], 'open_files("url1", "url2")\n') os.unlink('out.chimerax') if __name__ == '__main__': unittest.main()
Check generated file for sanity.
Check generated file for sanity.
Python
lgpl-2.1
salilab/cryptosite,salilab/cryptosite,salilab/cryptosite
05ddf0fff9469ae0173809eb559486ff216231a0
test/test_scripts.py
test/test_scripts.py
import pytest import subprocess @pytest.mark.parametrize("script", []) def test_script(script): try: subprocess.check_output([script, '-h'], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print e.output assert e.returncode == 0
import pytest import subprocess @pytest.mark.parametrize("script", ['bin/cast-example']) def test_script(script): try: subprocess.check_output([script, '-h'], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print e.output assert e.returncode == 0
Add example-cast to sanity test
Add example-cast to sanity test
Python
mit
maxzheng/clicast
33598fd8baf527d63cef965eddfc90548b6c52b3
go/apps/jsbox/definition.py
go/apps/jsbox/definition.py
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] # vumi-jssandbox-toolkit v2 endpoints try: v2_endpoints = list(js_config["endpoints"].keys()) except Exception: v2_endpoints = [] # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] v1_endpoints = [u"%s:%s" % (pool, tag)] except Exception: v1_endpoints = [] endpoints = v1_endpoints + v2_endpoints endpoints = [ep for ep in endpoints if isinstance(ep, unicode)] return sorted(set(endpoints))
Remove non-unicode endpoints from the endpoint list.
Remove non-unicode endpoints from the endpoint list.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
fbc46862af7fa254f74f1108149fd0669c46f1ad
rplugin/python3/deoplete/sources/LanguageClientSource.py
rplugin/python3/deoplete/sources/LanguageClientSource.py
import re from .base import Base CompleteResults = "g:LanguageClient_completeResults" def simplify_snippet(snip: str) -> str: snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip) return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}', '<`\g<num>:\g<desc>`>', snip) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.min_pattern_length = 1 self.input_pattern = r'(\.|::|->)\w*' self.__keyword_patterns = r'(?:[a-zA-Z@0-9_À-ÿ]|\.|::|->)*$' def get_complete_position(self, context): m = re.search('(?:' + context['keyword_patterns'] + ')$', context['input']) if m: return m.start() m = re.search(self.__keyword_patterns, context['input']) if m: return m.end() return -1 def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if not isinstance(result, list): result = [] return result
from .base import Base CompleteResults = "g:LanguageClient_completeResults" class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() def gather_candidates(self, context): if not context["is_async"]: context["is_async"] = True self.vim.funcs.LanguageClient_omniComplete() return [] elif self.vim.funcs.eval("len({})".format(CompleteResults)) == 0: return [] context["is_async"] = False result = self.vim.funcs.eval("remove({}, 0)".format(CompleteResults)) if not isinstance(result, list): result = [] return result
Remove problematic deoplete source customization.
Remove problematic deoplete source customization. Close #312.
Python
mit
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim
d6a3d43e58796299c55fe3a6c6d597edaf5cfc3c
troposphere/kms.py
troposphere/kms.py
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Alias(AWSObject): resource_type = "AWS::KMS::Alias" props = { 'AliasName': (basestring, True), 'TargetKeyId': (basestring, True) } class Key(AWSObject): resource_type = "AWS::KMS::Key" props = { 'Description': (basestring, False), 'Enabled': (boolean, False), 'EnableKeyRotation': (boolean, False), 'KeyPolicy': (policytypes, True), 'Tags': (list, False) }
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, Tags from .validators import boolean try: from awacs.aws import Policy policytypes = (dict, Policy) except ImportError: policytypes = dict, class Alias(AWSObject): resource_type = "AWS::KMS::Alias" props = { 'AliasName': (basestring, True), 'TargetKeyId': (basestring, True) } class Key(AWSObject): resource_type = "AWS::KMS::Key" props = { 'Description': (basestring, False), 'Enabled': (boolean, False), 'EnableKeyRotation': (boolean, False), 'KeyPolicy': (policytypes, True), 'Tags': ((Tags, list), False) }
Change KMS::Key to accept a standard Tags
Change KMS::Key to accept a standard Tags
Python
bsd-2-clause
ikben/troposphere,pas256/troposphere,johnctitus/troposphere,cloudtools/troposphere,ikben/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere
ca777965c26b8dfd43b472adeb032f048e2537ed
acceptancetests/tests/acc_test_login_page.py
acceptancetests/tests/acc_test_login_page.py
# (c) Crown Owned Copyright, 2016. Dstl. import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(self.browser.title, title) self.assertIn('Login with ID.', self.browser.html)
# (c) Crown Owned Copyright, 2016. Dstl. import os import unittest from splinter import Browser class TestLoginPage (unittest.TestCase): def setUp(self): self.browser = Browser('phantomjs') def test_login_page_appears(self): # This needs to come from an environment variable at some point # For now, this will only pass if the lighthouse-app-server host is # running. url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST'] title = 'Lighthouse' self.browser.visit(url) self.assertEqual(self.browser.url, url) self.assertEqual(self.browser.status_code.code, 200) self.assertIn(title, self.browser.title) self.assertIn('Login with ID.', self.browser.html)
Check that expected title exists in the actual title, not the other way round
Check that expected title exists in the actual title, not the other way round
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
d5ee91ba36c7e3d2ce0720b5b047934d554041cd
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from config import config bootstrap = Bootstrap() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) from .aflafrettir import aflafrettir as afla_blueprint app.register_blueprint(afla_blueprint) return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from config import config bootstrap = Bootstrap() db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) db.init_app(app) from .aflafrettir import aflafrettir as afla_blueprint app.register_blueprint(afla_blueprint) return app
Initialize the database in the application package constructor
Initialize the database in the application package constructor
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
154b64b2ee56fa4391251268ba4a85d178bedd60
djangoautoconf/urls.py
djangoautoconf/urls.py
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
Fix the issue of override url by mistake.
Fix the issue of override url by mistake.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
96f9819ab67b48135a61c8a1e15bc808cf82d194
bokeh/models/widget.py
bokeh/models/widget.py
from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool class Widget(PlotObject): disabled = Bool(False)
from __future__ import absolute_import from ..plot_object import PlotObject from ..properties import Bool from ..embed import notebook_div class Widget(PlotObject): disabled = Bool(False) def _repr_html_(self): return notebook_div(self) @property def html(self): from IPython.core.display import HTML return HTML(self._repr_html_())
Implement display protocol for Widget (_repr_html_)
Implement display protocol for Widget (_repr_html_) This effectively allows us to automatically display plots and widgets.
Python
bsd-3-clause
evidation-health/bokeh,abele/bokeh,mutirri/bokeh,percyfal/bokeh,htygithub/bokeh,jakirkham/bokeh,rhiever/bokeh,DuCorey/bokeh,srinathv/bokeh,DuCorey/bokeh,awanke/bokeh,clairetang6/bokeh,ericdill/bokeh,ahmadia/bokeh,saifrahmed/bokeh,mutirri/bokeh,bokeh/bokeh,gpfreitas/bokeh,philippjfr/bokeh,xguse/bokeh,srinathv/bokeh,draperjames/bokeh,schoolie/bokeh,laurent-george/bokeh,paultcochrane/bokeh,akloster/bokeh,caseyclements/bokeh,justacec/bokeh,maxalbert/bokeh,philippjfr/bokeh,birdsarah/bokeh,evidation-health/bokeh,rs2/bokeh,phobson/bokeh,PythonCharmers/bokeh,draperjames/bokeh,satishgoda/bokeh,mindriot101/bokeh,PythonCharmers/bokeh,CrazyGuo/bokeh,mindriot101/bokeh,birdsarah/bokeh,jplourenco/bokeh,matbra/bokeh,htygithub/bokeh,deeplook/bokeh,abele/bokeh,bsipocz/bokeh,rhiever/bokeh,laurent-george/bokeh,ericmjl/bokeh,htygithub/bokeh,DuCorey/bokeh,justacec/bokeh,PythonCharmers/bokeh,msarahan/bokeh,mutirri/bokeh,percyfal/bokeh,timsnyder/bokeh,timsnyder/bokeh,muku42/bokeh,deeplook/bokeh,xguse/bokeh,daodaoliang/bokeh,ChristosChristofidis/bokeh,ericmjl/bokeh,timothydmorton/bokeh,percyfal/bokeh,schoolie/bokeh,alan-unravel/bokeh,jplourenco/bokeh,canavandl/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,evidation-health/bokeh,Karel-van-de-Plassche/bokeh,tacaswell/bokeh,bsipocz/bokeh,mutirri/bokeh,deeplook/bokeh,dennisobrien/bokeh,msarahan/bokeh,quasiben/bokeh,roxyboy/bokeh,josherick/bokeh,mindriot101/bokeh,saifrahmed/bokeh,rothnic/bokeh,CrazyGuo/bokeh,canavandl/bokeh,aiguofer/bokeh,akloster/bokeh,clairetang6/bokeh,almarklein/bokeh,josherick/bokeh,aiguofer/bokeh,timothydmorton/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,mindriot101/bokeh,aavanian/bokeh,josherick/bokeh,quasiben/bokeh,xguse/bokeh,saifrahmed/bokeh,KasperPRasmussen/bokeh,akloster/bokeh,awanke/bokeh,ptitjano/bokeh,aavanian/bokeh,azjps/bokeh,tacaswell/bokeh,draperjames/bokeh,alan-unravel/bokeh,ericmjl/bokeh,rs2/bokeh,bokeh/bokeh,stonebig/bokeh,tacaswell/bokeh,ChinaQuants/bokeh,stonebig/bokeh,stuart-knock/bokeh,paultcochrane/bokeh,xguse/bokeh,jakirkham/bokeh,abele/bokeh,alan-unravel/bokeh,KasperPRasmussen/bokeh,birdsarah/bokeh,stuart-knock/bokeh,Karel-van-de-Plassche/bokeh,carlvlewis/bokeh,gpfreitas/bokeh,dennisobrien/bokeh,deeplook/bokeh,alan-unravel/bokeh,lukebarnard1/bokeh,jakirkham/bokeh,ahmadia/bokeh,aavanian/bokeh,phobson/bokeh,clairetang6/bokeh,timsnyder/bokeh,ptitjano/bokeh,ahmadia/bokeh,lukebarnard1/bokeh,rs2/bokeh,tacaswell/bokeh,ericdill/bokeh,matbra/bokeh,satishgoda/bokeh,awanke/bokeh,rothnic/bokeh,evidation-health/bokeh,jplourenco/bokeh,muku42/bokeh,CrazyGuo/bokeh,roxyboy/bokeh,bokeh/bokeh,caseyclements/bokeh,jplourenco/bokeh,matbra/bokeh,gpfreitas/bokeh,ChinaQuants/bokeh,ChinaQuants/bokeh,KasperPRasmussen/bokeh,dennisobrien/bokeh,saifrahmed/bokeh,timothydmorton/bokeh,rhiever/bokeh,timsnyder/bokeh,maxalbert/bokeh,DuCorey/bokeh,azjps/bokeh,birdsarah/bokeh,satishgoda/bokeh,stonebig/bokeh,srinathv/bokeh,rs2/bokeh,aiguofer/bokeh,schoolie/bokeh,rothnic/bokeh,philippjfr/bokeh,laurent-george/bokeh,stonebig/bokeh,matbra/bokeh,justacec/bokeh,maxalbert/bokeh,percyfal/bokeh,jakirkham/bokeh,eteq/bokeh,eteq/bokeh,rs2/bokeh,philippjfr/bokeh,daodaoliang/bokeh,ericdill/bokeh,azjps/bokeh,khkaminska/bokeh,draperjames/bokeh,philippjfr/bokeh,almarklein/bokeh,canavandl/bokeh,ericmjl/bokeh,clairetang6/bokeh,ptitjano/bokeh,srinathv/bokeh,KasperPRasmussen/bokeh,ericmjl/bokeh,htygithub/bokeh,carlvlewis/bokeh,ptitjano/bokeh,aiguofer/bokeh,laurent-george/bokeh,lukebarnard1/bokeh,ChristosChristofidis/bokeh,abele/bokeh,ChristosChristofidis/bokeh,azjps/bokeh,draperjames/bokeh,jakirkham/bokeh,roxyboy/bokeh,Karel-van-de-Plassche/bokeh,roxyboy/bokeh,khkaminska/bokeh,phobson/bokeh,caseyclements/bokeh,paultcochrane/bokeh,percyfal/bokeh,caseyclements/bokeh,muku42/bokeh,eteq/bokeh,msarahan/bokeh,aiguofer/bokeh,almarklein/bokeh,ChinaQuants/bokeh,ericdill/bokeh,PythonCharmers/bokeh,khkaminska/bokeh,carlvlewis/bokeh,canavandl/bokeh,bokeh/bokeh,timsnyder/bokeh,eteq/bokeh,muku42/bokeh,rothnic/bokeh,ahmadia/bokeh,timothydmorton/bokeh,DuCorey/bokeh,stuart-knock/bokeh,bsipocz/bokeh,phobson/bokeh,dennisobrien/bokeh,stuart-knock/bokeh,CrazyGuo/bokeh,aavanian/bokeh,schoolie/bokeh,phobson/bokeh,dennisobrien/bokeh,akloster/bokeh,bsipocz/bokeh,paultcochrane/bokeh,josherick/bokeh,daodaoliang/bokeh,schoolie/bokeh,rhiever/bokeh,maxalbert/bokeh,satishgoda/bokeh,ChristosChristofidis/bokeh,msarahan/bokeh,carlvlewis/bokeh,justacec/bokeh,Karel-van-de-Plassche/bokeh,lukebarnard1/bokeh,daodaoliang/bokeh,azjps/bokeh,awanke/bokeh,khkaminska/bokeh,gpfreitas/bokeh,aavanian/bokeh,quasiben/bokeh
5a6c809afc6b228d7f5d37154adda162802c0110
botcommands/vimtips.py
botcommands/vimtips.py
# coding: utf-8 import requests def vimtips(msg=None): try: tip = requests.get('http://vim-tips.com/random_tips/json').json() except Exception as e: return None return u'%s\n%s' % (tip['Content'], tip['Comment'], )
# coding: utf-8 import requests from redis_wrap import get_hash from rq.decorators import job def vimtips(msg=None): try: existing_tips = get_hash('vimtips') _len = len(existing_tips) if _len > 0: _index = randint(0, _len - 1) _k = existing_tips.keys()[_index] _v = existing_tips[_k] tip = { 'Content': _k, 'Comment': _v } else: tip = requests.get('http://vim-tips.com/random_tips/json').json() existing_tips.update({ tip['Content']: tip['Comment'] }) collect_tip() except Exception as e: return u'哦,不小心玩坏了……' return u'%s\n%s' % (tip['Content'], tip['Comment'], ) @job('default') def collect_tip(): tip = requests.get('http://vim-tips.com/random_tips/json').json() get_hash('vimtips').update({ tip['Content']: tip['Comment'] })
Use RQ to queue collecting job
Use RQ to queue collecting job
Python
bsd-2-clause
JokerQyou/bot
16d0f3f0ca4ce59f08e598b6f9f25bb6dc8e1713
benchmark/benchmark.py
benchmark/benchmark.py
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s)
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
Fix bad console output formatting
Fix bad console output formatting
Python
mit
jameshy/libtree,conceptsandtraining/libtree
2cf8d03324af2fadf905da811cfab4a29a6bc93a
pony_barn/settings/django_settings.py
pony_barn/settings/django_settings.py
DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db' } }
import os pid = os.getpid() DATABASES = { 'default': { 'ENGINE': '{{ db_engine }}', 'NAME': '{{ db_name }}', 'USER': '{{ db_user}}', 'PASSWORD': '{{ db_pass }}', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': 'other_db_%s' % pid, } }
Append PID to Django database to avoid conflicts.
Append PID to Django database to avoid conflicts.
Python
mit
ericholscher/pony_barn,ericholscher/pony_barn
0d8a28b62c4e54ee84861da75b0f0626bc4e46e7
get_data_from_twitter.py
get_data_from_twitter.py
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) #stream.filter(track=['#Trump2016', '#Hillary2016']) stream.filter(track=['#Trump2016'])
# -*- coding: UTF-8 -*- import numpy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import config #Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/ class StdOutListener(StreamListener): def on_data(self, data_str): data = json.loads(data_str) if len(data['entities']['urls']) != 0: newdata = {'created_at' : data['created_at'], 'text' : data['text'], 'urls' : [url['expanded_url'] for url in data['entities']['urls'] if url['url'] != '' ] } print json.dumps(newdata) return True def on_error(self, status): print status l = StdOutListener() auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_token_secret) stream = Stream(auth, l) stream.filter(track=['#Trump2016', '#Hillary2016'])
Add back filter for Hillary2016
Add back filter for Hillary2016
Python
mpl-2.0
aDataAlchemist/election-tweets
8f1fd73d6a88436d24f936adec997f88ad7f1413
neutron/tests/unit/objects/test_l3agent.py
neutron/tests/unit/objects/test_l3agent.py
# Copyright (c) 2016 Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] self.update_obj_fields( {'router_id': self._router.id, 'l3_agent_id': getter})
# Copyright (c) 2016 Intel Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron.objects import l3agent from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase): _test_class = l3agent.RouterL3AgentBinding class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = l3agent.RouterL3AgentBinding def setUp(self): super(RouterL3AgentBindingDbObjTestCase, self).setUp() self._create_test_router() def getter(): self._create_test_agent() return self._agent['id'] index = iter(range(1, len(self.objs) + 1)) self.update_obj_fields( {'router_id': self._router.id, 'binding_index': lambda: next(index), 'l3_agent_id': getter})
Use unique binding_index for RouterL3AgentBinding
Use unique binding_index for RouterL3AgentBinding This is because (router_id, binding_index) tuple is expected to be unique, as per db model. Closes-Bug: #1674434 Change-Id: I64fcee88f2ac942e6fa173644fbfb7655ea6041b
Python
apache-2.0
openstack/neutron,mahak/neutron,noironetworks/neutron,huntxu/neutron,eayunstack/neutron,openstack/neutron,huntxu/neutron,eayunstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron,noironetworks/neutron
867a8081646eb061555eda2471c5174a842dd6fd
tests/test_floodplain.py
tests/test_floodplain.py
from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
from unittest import TestCase import niche_vlaanderen as nv import numpy as np import rasterio class TestFloodPlain(TestCase): def test__calculate(self): fp = nv.FloodPlain() fp._calculate(depth=np.array([1, 2, 3]), frequency="T25", period="winter", duration=1) np.testing.assert_equal(np.array([3, 3, 3]), fp._veg[1]) def test_calculate(self): fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) with rasterio.open( "testcase/floodplains/result/F25-T10-P1-winter.asc") as dst: expected = dst.read(1) np.testing.assert_equal(expected, fp._veg[25]) def test_plot(self): import matplotlib as mpl mpl.use('agg') import matplotlib.pyplot as plt plt.show = lambda: None fp = nv.FloodPlain() fp.calculate("testcase/floodplains/ff_bt_t10_h.asc", "T10", period="winter", duration=1) fp.plot(7)
Fix tests for running floodplain model in ci
Fix tests for running floodplain model in ci
Python
mit
johanvdw/niche_vlaanderen
fc8ac6ba5081e7847847d31588a65db8ea13416c
openprescribing/matrixstore/build/dates.py
openprescribing/matrixstore/build/dates.py
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months((year, month), months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
DEFAULT_NUM_MONTHS = 60 def generate_dates(end_str, months=None): """ Given an end date as a string in YYYY-MM form (or the underscore separated equivalent), return a list of N consecutive months as strings in YYYY-MM-01 form, with that month as the final member """ if months is None: months = DEFAULT_NUM_MONTHS end_date = parse_date(end_str) assert months > 0 dates = [] for offset in range(1-months, 1): date = increment_months(end_date, offset) dates.append('{:04d}-{:02d}-01'.format(date[0], date[1])) return dates def parse_date(date_str): """ Given a date string in YYYY-MM form (or the underscore separated equivalent), return a pair of (year, month) integers """ year_str, month_str = date_str.replace('_', '-').split('-')[:2] assert len(year_str) == 4 assert len(month_str) == 2 return int(year_str), int(month_str) def increment_months(year_month, months): """ Given a pair of (year, month) integers return the (year, month) pair N months in the future """ year, month = year_month i = (year*12) + (month - 1) i += months return int(i/12), (i % 12) + 1
Fix another py27-ism which Black can't handle
Fix another py27-ism which Black can't handle Not sure how I missed this one last time.
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
68aeddc44d4c9ace7ab9d2475a92c5fd39b4a665
ckanext/requestdata/controllers/request_data.py
ckanext/requestdata/controllers/request_data.py
from ckan.lib import base from ckan.common import c, _ from ckan import logic from ckanext.requestdata import emailer from ckan.plugins import toolkit import ckan.model as model import ckan.plugins as p import json get_action = logic.get_action NotFound = logic.NotFound NotAuthorized = logic.NotAuthorized ValidationError = logic.ValidationError abort = base.abort BaseController = base.BaseController class RequestDataController(BaseController): def send_request(self): '''Send mail to resource owner. :param data: Contact form data. :type data: object ''' print "Entered" context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} try: if p.toolkit.request.method == 'POST': data = dict(toolkit.request.POST) content = data["message_content"] to = data['email_address'] user = context['auth_user_obj'] mail_subject = "Request data" user_email = user.email get_action('requestdata_request_create')(context, data) except NotAuthorized: abort(403, _('Unauthorized to update this dataset.')) except ValidationError: error = { 'success': False, 'error': { 'message': 'An error occurred while requesting the data.' } } return json.dumps(error) response_message = emailer.send_email(content, to, user_email, mail_subject) return json.dumps(response_message)
from ckan.lib import base from ckan.common import c, _ from ckan import logic from ckanext.requestdata import emailer from ckan.plugins import toolkit import ckan.model as model import ckan.plugins as p import json get_action = logic.get_action NotFound = logic.NotFound NotAuthorized = logic.NotAuthorized ValidationError = logic.ValidationError abort = base.abort BaseController = base.BaseController class RequestDataController(BaseController): def send_request(self): '''Send mail to resource owner. :param data: Contact form data. :type data: object :rtype: json ''' print "Entered" context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} try: if p.toolkit.request.method == 'POST': data = dict(toolkit.request.POST) content = data["message_content"] to = data['email_address'] mail_subject = "Request data" get_action('requestdata_request_create')(context, data) except NotAuthorized: abort(403, _('Unauthorized to update this dataset.')) except ValidationError: error = { 'success': False, 'error': { 'message': 'An error occurred while requesting the data.' } } return json.dumps(error) response_message = emailer.send_email(content, to, mail_subject) return json.dumps(response_message)
Remove user_mail from request data
Remove user_mail from request data
Python
agpl-3.0
ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata
73b61983de6ff655b4f11205c0acd2b2f92915f4
eva/util/nutil.py
eva/util/nutil.py
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): """ Stochastically binarize values in [0, 1] by treating them as p-values of a Bernoulli distribution. """ return (generate(size=arr.shape) < arr).astype('float32')
import numpy as np def to_rgb(pixels): return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2) def binarize(arr, generate=np.random.uniform): return (generate(size=arr.shape) < arr).astype('i')
Remove comment; change to int
Remove comment; change to int
Python
apache-2.0
israelg99/eva
a24c657ca84e553a39e23d201d605d84d828c322
examples/hello.py
examples/hello.py
from cell import Actor, Agent from cell.actors import Server from kombu import Connection from kombu.log import setup_logging connection = Connection() class GreetingActor(Server): default_routing_key = 'GreetingActor' class state: def greet(self, who='world'): return 'Hello %s' % who greeting = GreetingActor(connection) class Printer(Actor): default_routing_key = 'Printer' class state: def echo(self, msg = 'test'): print 'I am a printer:',msg #self.output_edge.send(msg) return msg printerActor = Printer(connection) class Ihu(Actor): default_routing_key = 'Printer' class state: def temp(self, msg = 'blabla'): self.output_server.send(msg) class GreetingAgent(Agent): actors = [greeting, printerActor] if __name__ == '__main__': consumer = GreetingAgent(connection).consume_from_commandline() for _ in consumer: print 'Received' # Run this script from the command line and try this # in another console: # # >>> from hello import greeting # >>> greeting.call('greet') # 'Hello world'
from cell import Actor, Agent from cell.actors import Server from kombu import Connection from kombu.log import setup_logging connection = Connection() class GreetingActor(Server): default_routing_key = 'GreetingActor' class state: def greet(self, who='world'): return 'Hello %s' % who greeting = GreetingActor(connection) class GreetingAgent(Agent): actors = [greeting] if __name__ == '__main__': GreetingAgent(connection).consume_from_commandline() # Run this script from the command line and try this # in another console: # # >>> from hello import greeting # >>> greeting.call('greet') # 'Hello world'
Use the Server class (an Actor derived class)
Use the Server class (an Actor derived class)
Python
bsd-3-clause
celery/cell,celery/cell
d70ccd856bb4ddb061ff608716ef15f778380d62
gnsq/stream/defalte.py
gnsq/stream/defalte.py
from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): self._decompressor = zlib.decompressobj(level) self._compressor = zlib.compressobj(level) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
from __future__ import absolute_import import zlib from .compression import CompressionSocket class DefalteSocket(CompressionSocket): def __init__(self, socket, level): wbits = -zlib.MAX_WBITS self._decompressor = zlib.decompressobj(wbits) self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits) super(DefalteSocket, self).__init__(socket) def compress(self, data): return self._compressor.compress(data) def decompress(self, data): return self._decompressor.decompress(data)
Set correct waits for deflate.
Set correct waits for deflate.
Python
bsd-3-clause
wtolson/gnsq,hiringsolved/gnsq,wtolson/gnsq
02ca8bc5908b0ff15cd97846e1fd1488eddb4087
backend/schedule/models.py
backend/schedule/models.py
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') square_footage = models.IntegerField capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
Add square feet to Location data model.
Add square feet to Location data model.
Python
mit
bable5/schdlr,bable5/schdlr,bable5/schdlr,bable5/schdlr
1fbb58a3f6692a7467f758ccedca6f8baa96a165
text/__init__.py
text/__init__.py
#! /usr/bin/env python import os def get_files(path, ext=None): """ Get all files in directory path, optionally with the specified extension """ if ext is None: ext = '' return [ os.path.abspath(fname) for fname in os.listdir(path) if os.path.isfile(fname) if fname.endswith(ext) ] def blob_text(filenames): """ Create a blob of text by reading in all filenames into a string """ return '\n'.join([open(fname).read() for fname in filenames])
#! /usr/bin/env python import os import re def get_files(path, ext=None): """ Get all files in directory path, optionally with the specified extension """ if ext is None: ext = '' return [ os.path.abspath(fname) for fname in os.listdir(path) if os.path.isfile(fname) if fname.endswith(ext) ] def blob_text(filenames): """ Create a blob of text by reading in all filenames into a string """ return '\n'.join([open(fname).read() for fname in filenames]) def get_definition(text, startswith): """ Parse text to retrieve the definitions that start with keyword """ return [ re.split('[ ()]', line.strip())[1] for line in [line.strip() for line in text.splitlines()] if line.startswith(startswith) ] def get_functions(text, startswith='def '): """ Parse text to retrive the functions and methods defined """ return get_definition(text, startswith) def get_classes(text, startswith='class '): """ Parse text to retrive the functions and methods defined """ return get_definition(text, startswith)
Add function to get the functions / classes that are defined
Add function to get the functions / classes that are defined
Python
mit
IanLee1521/utilities
8e75605e0511b85dfd500b644613739f29705da6
cfnf.py
cfnf.py
import sublime, sublime_plugin import time class cfnewfile(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\r\n Name:\r\n Description:\r\n Written By:\r\n Date Created: "+localtime+"\r\n History:\r\n--->\r\n")
import sublime, sublime_plugin import time class cfnfCommand(sublime_plugin.WindowCommand): def run(self): a = self.window.new_file() a.run_command("addheader") class addheaderCommand(sublime_plugin.TextCommand): def run(self, edit): localtime = time.asctime( time.localtime(time.time()) ) self.view.insert(edit,0,"<!---\n Name:\n Description:\n Written By:\n Date Created: "+localtime+"\n History:\n--->\n")
Send text to new file
Send text to new file
Python
bsd-2-clause
dwkd/SublimeCFNewFile
99af762edb7a8fa4b0914bdf157af151a814adb6
backend/api.py
backend/api.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json import boto3 table_name = os.environ.get("TABLE_NAME") table = boto3.resource("dynamodb").Table(table_name) def _log_dynamo(response): print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format( response.get("ResponseMetadata").get("HTTPStatusCode"), response.get("ResponseMetadata").get("RetryAttempts"), response.get("ScannedCount"), response.get("Count") ) def get_items(event, context): response = table.scan(Limit=10) _log_dynamo(response) return { "statusCode": 200, "body": json.dumps(response["Items"], indent=1) } def get_item(event, context): response = table.get_item(Key={"id": event.get("pathParameters").get("id")}) _log_dynamo(response) return { "statusCode": 200, "body": json.dumps(response["Item"], indent=1) }
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json import boto3 table_name = os.environ.get("TABLE_NAME") table = boto3.resource("dynamodb").Table(table_name) def _log_dynamo(response): print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format( response.get("ResponseMetadata").get("HTTPStatusCode"), response.get("ResponseMetadata").get("RetryAttempts"), response.get("ScannedCount"), response.get("Count") ) def get_items(event, context): response = table.scan(Limit=10) _log_dynamo(response) return { "statusCode": 200, "body": json.dumps(response["Items"], indent=1), "headers": {"Access-Control-Allow-Origin": "*"} } def get_item(event, context): response = table.get_item(Key={"id": event.get("pathParameters").get("id")}) _log_dynamo(response) return { "statusCode": 200, "body": json.dumps(response["Item"], indent=1) }
Add CORS header to function
Add CORS header to function
Python
mit
Vilsepi/no-servers,Vilsepi/no-servers,Vilsepi/no-servers,Vilsepi/no-servers
6589df70baad1b57c604736d75e424465cf8775e
djangoautoconf/auto_conf_admin_tools/reversion_feature.py
djangoautoconf/auto_conf_admin_tools/reversion_feature.py
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: from reversion import VersionAdmin parent_list.append(VersionAdmin)
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase from django.conf import settings __author__ = 'weijia' class ReversionFeature(AdminFeatureBase): def __init__(self): super(ReversionFeature, self).__init__() self.related_search_fields = {} def process_parent_class_list(self, parent_list, class_inst): if "reversion" in settings.INSTALLED_APPS: try: from reversion import VersionAdmin # for Django 1.5 except: from reversion.admin import VersionAdmin # for Django 1.8 parent_list.append(VersionAdmin)
Fix import issue for Django 1.5 above
Fix import issue for Django 1.5 above
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
6df7ee955c7dfaee9a597b331dbc4c448fe3738a
fpr/migrations/0017_ocr_unique_names.py
fpr/migrations/0017_ocr_unique_names.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ IDCommand = apps.get_model('fpr', 'IDCommand') ocr_command = IDCommand.objects.get( uuid='5d501dbf-76bb-4569-a9db-9e367800995e') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def data_migration(apps, schema_editor): """Migration that causes each OCR text file to include the UUID of its source file in its filename. This prevents OCR text files from overwriting one another when there are two identically named source files in a transfer. See https://github.com/artefactual/archivematica-fpr-admin/issues/66 """ FPCommand = apps.get_model('fpr', 'FPCommand') ocr_command = FPCommand.objects.get( uuid='4ea06c2b-ee42-4f80-ad10-4e044ba0676a') ocr_command.command = ( 'ocrfiles="%SIPObjectsDirectory%metadata/OCRfiles"\n' 'test -d "$ocrfiles" || mkdir -p "$ocrfiles"\n\n' 'tesseract %fileFullName% "$ocrfiles/%fileName%-%fileUUID%"') ocr_command.output_location = ( '%SIPObjectsDirectory%metadata/OCRfiles/%fileName%-%fileUUID%.txt') ocr_command.save() class Migration(migrations.Migration): dependencies = [ ('fpr', '0016_update_idtools'), ] operations = [ migrations.RunPython(data_migration), ]
Fix OCR command UUID typo
Fix OCR command UUID typo
Python
agpl-3.0
artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin
8c49359a79d815cc21acbd58adc36c52d75e20b7
dash2012/auth/views.py
dash2012/auth/views.py
from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) return render(r, 'auth.html') def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from cloudfish.models import Cloud def login(r): c = {} if r.POST: username = r.POST['username'] password = r.POST['password'] user = authenticate(username=username, password=password) if user is not None: auth_login(r, user) if not Cloud.objects.filter(account=user).exists(): return HttpResponseRedirect(reverse('connect-view')) return HttpResponseRedirect(reverse('myservers-view')) c['errors'] = "Login failed, please try again" return render(r, 'auth.html', c) def logout(request): auth_logout(request) return HttpResponseRedirect(reverse('index-view')) @login_required def connect(request): return render(request, 'connect.html')
Add login failed flash message
Add login failed flash message
Python
bsd-3-clause
losmiserables/djangodash2012,losmiserables/djangodash2012
e170a96859232d1436930be7a0cbfc7f2295c8a7
main.py
main.py
from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader("content-type", "text/plain") return "I am request #" + str(self.numberRequests) + "\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
from twisted.internet import reactor from twisted.web import server, resource from teiler.server import FileServerResource from teiler.client import FileRequestResource import sys from twisted.python import log class HelloResource(resource.Resource): isLeaf = False numberRequests = 0 def render_GET(self, request): request.setHeader("content-type", "text/plain") return "Welcome to teiler\n" if __name__ == '__main__': log.startLogging(sys.stdout) filesServed = [] transferRequests = [] downloadDirectory = "." root = resource.Resource() root.putChild('', HelloResource()) root.putChild('files', FileServerResource(filesServed)) root.putChild('requests', FileRequestResource(transferRequests, downloadDirectory)) reactor.listenTCP(8080, server.Site(root)) reactor.run()
Set root resource to welcome
Set root resource to welcome
Python
mit
derwolfe/teiler,derwolfe/teiler
73b6a84cfc0ccc20d04c3dd80c3e505cd118be4d
nsfw.py
nsfw.py
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel']) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
import random from discord.ext import commands from lxml import etree class NSFW: def __init__(self, bot): self.bot = bot @commands.command(aliases=['gel'], hidden=True) async def gelbooru(self, ctx, *, tags): async with ctx.typing(): entries = [] url = 'http://gelbooru.com/index.php' params = {'page': 'dapi', 's': 'post', 'q': 'index', 'tags': tags} async with self.bot.session.get(url, params=params) as resp: root = etree.fromstring((await resp.text()).encode(), etree.HTMLParser()) search_nodes = root.findall(".//post") for node in search_nodes: image = next((item[1] for item in node.items() if item[0] == 'file_url'), None) if image is not None: entries.append(image) try: message = f'http:{random.choice(entries)}' except IndexError: message = 'No images found.' await ctx.send(message) @commands.command(hidden=True) async def massage(self, ctx, *, tags=''): await ctx.invoke(self.gelbooru, tags='massage ' + tags) def setup(bot): bot.add_cog(NSFW(bot))
Make command invisible by default
Make command invisible by default
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
22e6cce28da8a700bd4cd45aa47913aaff559a9d
functional_tests/management/commands/create_testrecipe.py
functional_tests/management/commands/create_testrecipe.py
from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save()
import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command import random import string from recipes.models import Recipe class Command(BaseCommand): def handle(self, *args, **options): r = Recipe(name=''.join(random.choice(string.ascii_letters) for _ in range(10)), description='description') r.save() r.add_date = datetime.date.today() - datetime.timedelta(days=2) r.save()
Make sure that recipes created by the command show up
Make sure that recipes created by the command show up
Python
agpl-3.0
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
f96990118d51b56ad438a8efbf2a7f83ec0f3c63
conference_scheduler/tests/test_parameters.py
conference_scheduler/tests/test_parameters.py
from conference_scheduler import parameters def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
from conference_scheduler import parameters import numpy as np def test_tags(events): tags = parameters.tags(events) assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]])) def test_variables(shape): X = parameters.variables(shape) assert len(X) == 21 def test_schedule_all_events(shape, X): constraints = [c for c in parameters._schedule_all_events(shape, X)] assert len(constraints) == 3 def test_max_one_event_per_slot(shape, X): constraints = [c for c in parameters._max_one_event_per_slot(shape, X)] assert len(constraints) == 7 def test_constraints(shape, X): constraints = [c for c in parameters.constraints(shape, X)] assert len(constraints) == 10
Add failing test to function to build tags matrix.
Add failing test to function to build tags matrix.
Python
mit
PyconUK/ConferenceScheduler
24e65db624221d559f46ce74d88ad28ec970d754
profile_collection/startup/00-startup.py
profile_collection/startup/00-startup.py
import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd'
import logging session_mgr._logger.setLevel(logging.INFO) from dataportal import (DataBroker as db, StepScan as ss, DataBroker, StepScan, DataMuxer) from bluesky.standard_config import * from ophyd.commands import * gs.RE.md['config'] = {} gs.RE.md['owner'] = 'xf28id1' gs.RE.md['group'] = 'XPD' gs.RE.md['beamline_id'] = 'xpd' import bluesky.qt_kicker bluesky.qt_kicker.install_qt_kicker()
Update bluesky's API to the qt_kicker.
Update bluesky's API to the qt_kicker.
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
54b2a6953a4da2b217052d166ad1f069f683b9ee
scripts/nomenclature/nomenclature_map.py
scripts/nomenclature/nomenclature_map.py
"""Create a map from the input binomials to their ITIS accepted synonyms. """ import pandas as pd itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1")
"""Create a map from the input binomials to their ITIS accepted synonyms. """ import pandas as pd from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder # Globals INPUT_FILE_NAME = "search_results.csv" # Input nomenclature_folder = locate_nomenclature_folder() itis_results = pd.read_csv( str(nomenclature_folder / INPUT_FILE_NAME), encoding="ISO-8859-1")
Implement locator in nomenclature map
Implement locator in nomenclature map
Python
mit
jnfrye/local_plants_book
b77e39b21a326655a04dbd15fcacfd2cc57a6008
core/emails.py
core/emails.py
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(user, content, subject): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
from django.core.mail import EmailMessage from django.template.loader import render_to_string def notify_existing_user(user, event): """ Sends e-mail to existing organizer, that they're added to the new Event. """ content = render_to_string('emails/existing_user.html', { 'user': user, 'event': event }) subject = 'You have been granted access to new Django Girls event' send_email(content, subject, user) def notify_new_user(user, event, password): """ Sends e-mail to newly created organizer that their account was created and that they were added to the Event. """ content = render_to_string('emails/new_user.html', { 'user': user, 'event': event, 'password': password, }) subject = 'Access to Django Girls website' send_email(content, subject, user) def send_email(content, subject, user): msg = EmailMessage(subject, content, "Django Girls <hello@djangogirls.org>", [user.email]) msg.content_subtype = "html" msg.send()
Fix broken order of arguments in send_email
Fix broken order of arguments in send_email Ticket #342
Python
bsd-3-clause
patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls
badddd6aa9533a01e07477174dc7422ee4941014
wsgi.py
wsgi.py
# Yith Library Server is a password storage server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server 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. # # Yith Library Server 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. from newrelic import agent agent.initialize() from paste.deploy import loadapp from raven.middleware import Sentry application = loadapp('config:production.ini', relative_to='yithlibraryserver/config-templates') application = agent.WSGIApplicationWrapper(Sentry(application))
# Yith Library Server is a password storage server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server 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. # # Yith Library Server 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. import os import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp from pyramid.paster import setup_logging from raven.middleware import Sentry from waitress import serve basedir= os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join( basedir, 'yithlibraryserver', 'config-templates', 'production.ini' ) application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) scheme = os.environ.get("SCHEME", "https") setup_logging(conf_file) serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
Read the conf file using absolute paths
Read the conf file using absolute paths
Python
agpl-3.0
lorenzogil/yith-library-server,lorenzogil/yith-library-server,lorenzogil/yith-library-server
a6300723150d7d1ff9a58f4f3f1297e0fe2c6f78
css_updater/git/manager.py
css_updater/git/manager.py
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json self.config: Dict[str, Any] = json.loads(config.read()) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
"""manages github repos""" import os import tempfile from typing import Dict, Any import pygit2 as git from .webhook.handler import Handler class Manager(object): """handles git repos""" def __init__(self: Manager, handler: Handler) -> None: self.webhook_handler: Handler = handler self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory() self.repo: git.Repository = git.clone_repository( self.webhook_handler.git_url, path=self.temp_dir.name) with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config: import json try: self.config: Dict[str, Any] = json.loads(config.read())["css_updater"] except KeyError as invalid_json: print(invalid_json) except IOError as io_error: print(io_error) def __del__(self: Manager) -> None: self.temp_dir.cleanup()
Check for errors in config
Check for errors in config
Python
mit
neoliberal/css-updater
3d64eb4a7438b6b4f46f1fdf7f47d530cb11b09c
spacy/tests/regression/test_issue2396.py
spacy/tests/regression/test_issue2396.py
# coding: utf-8 from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all()
# coding: utf-8 from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
Update get_lca_matrix test for develop
Update get_lca_matrix test for develop
Python
mit
explosion/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy