commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
b81ace397887cb6d0fc7db21d623667223adbfbf
python/frequency_queries.py
python/frequency_queries.py
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the freqQuery function below. def freqQuery(queries): output = [] occurences = Counter() frequencies = Counter() for operation, value in queries: if (operation == 1): frequencies[occur...
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the freqQuery function below. def freqQuery(queries): output = [] array = [] occurences = Counter() frequencies = Counter() for operation, value in queries: if (operation == 1): freq...
Fix bug with negative counts
Fix bug with negative counts
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
--- +++ @@ -10,6 +10,7 @@ # Complete the freqQuery function below. def freqQuery(queries): output = [] + array = [] occurences = Counter() frequencies = Counter() @@ -20,9 +21,10 @@ frequencies[occurences[value]] += 1 elif (operation == 2): - frequencies[occurences[value]] -= 1 - ...
8b731102036583099bda475ec1a857b19ff18f80
minimal.py
minimal.py
import sys from django.conf import settings from django.conf.urls import url from django.core.management import execute_from_command_line from django.http import HttpResponse settings.configure( DEBUG=True, ROOT_URLCONF=sys.modules[__name__], ) def index(request): return HttpResponse('<h1>A minimal Djan...
import sys from django.conf import settings from django.urls import path from django.core.management import execute_from_command_line from django.http import HttpResponse settings.configure( DEBUG=True, ROOT_URLCONF=sys.modules[__name__], ) def index(request): return HttpResponse('<h1>A minimal Django r...
Update `urlpatterns` for 4.0 removal of `django.conf.urls.url()`
Update `urlpatterns` for 4.0 removal of `django.conf.urls.url()`
Python
mit
rnevius/minimal-django
--- +++ @@ -1,7 +1,7 @@ import sys from django.conf import settings -from django.conf.urls import url +from django.urls import path from django.core.management import execute_from_command_line from django.http import HttpResponse @@ -14,8 +14,9 @@ def index(request): return HttpResponse('<h1>A minimal D...
fdc0bb75271b90a31072f79b95283e1156d50181
waffle/decorators.py
waffle/decorators.py
from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): if flag_name.startswith('!'): active = is_active(request, flag_name[1:]) else: active =...
from functools import wraps from django.http import Http404 from django.utils.decorators import available_attrs from waffle import is_active def waffle(flag_name): def decorator(view): @wraps(view, assigned=available_attrs(view)) def _wrapped_view(request, *args, **kwargs): if flag_n...
Make the decorator actually work again.
Make the decorator actually work again.
Python
bsd-3-clause
isotoma/django-waffle,TwigWorld/django-waffle,rlr/django-waffle,webus/django-waffle,groovecoder/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,safarijv/django-waffle,paulcwatts/django-waffle,JeLoueMonCampingCar/django-waffle,11craft/django-waffle,festicket/django-waffle,styleseat/django-waffle,m...
--- +++ @@ -8,13 +8,13 @@ def waffle(flag_name): def decorator(view): - if flag_name.startswith('!'): - active = is_active(request, flag_name[1:]) - else: - active = is_active(request, flag_name) - @wraps(view, assigned=available_attrs(view)) def _wrapped_...
6c578b67753e7a3fd646e5d91259b50c0b39bec6
tests/test_add_target.py
tests/test_add_target.py
""" Tests for helper function for adding a target to a Vuforia database. """ import io from vws import VWS class TestSuccess: """ Tests for successfully adding a target. """ def test_add_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ ...
""" Tests for helper function for adding a target to a Vuforia database. """ import io from mock_vws import MockVWS from vws import VWS class TestSuccess: """ Tests for successfully adding a target. """ def test_add_target( self, client: VWS, high_quality_image: io.BytesIO,...
Add test for custom base URL
Add test for custom base URL
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
--- +++ @@ -3,6 +3,8 @@ """ import io + +from mock_vws import MockVWS from vws import VWS @@ -32,3 +34,28 @@ """ client.add_target(name='x', width=1, image=high_quality_image) client.add_target(name='a', width=1, image=high_quality_image) + + +class TestCustomBaseURL: + """ + ...
b6711f27146279ee419143b560cf32d3b3dfc80c
tools/conan/conanfile.py
tools/conan/conanfile.py
from conans import ConanFile, CMake, tools class VarconfConan(ConanFile): name = "varconf" version = "1.0.3" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/varconf" description = "Configuration li...
from conans import ConanFile, CMake, tools class VarconfConan(ConanFile): name = "varconf" version = "1.0.3" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/varconf" description = "Configuration li...
Include binaries when importing (for Windows).
Include binaries when importing (for Windows).
Python
lgpl-2.1
worldforge/varconf,worldforge/varconf,worldforge/varconf,worldforge/varconf
--- +++ @@ -22,6 +22,9 @@ "revision": "auto" } + def imports(self): + self.copy("*.dll", "bin", "bin") + def build(self): cmake = CMake(self) cmake.configure(source_folder=".")
4307fa24a27a2c623836a7518e3aceb4546abcf6
scholrroles/behaviour.py
scholrroles/behaviour.py
from collections import defaultdict from .utils import get_value_from_accessor class RoleBehaviour(object): ids = [] object_accessors = {} def __init__(self, user, request): self.user = user self.request = request def has_role(self): return False def has_role_for(self, ob...
from collections import defaultdict from .utils import get_value_from_accessor class RoleBehaviour(object): ids = [] object_accessors = {} def __init__(self, user, request): self.user = user self.request = request def has_role(self): return False def has_role_for(self, ob...
Validate Model function to allow permission
Validate Model function to allow permission
Python
bsd-3-clause
Scholr/scholr-roles
--- +++ @@ -20,6 +20,7 @@ def can_apply_permission(self, obj, perm): method = 'has_{}_{}_permission'.format(self.role, perm.name) + print method, hasattr(obj, method), getattr(obj, method), callable(getattr(obj, method)) if hasattr(obj, method): function = getattr(obj, met...
bdd842f55f3a234fefee4cd2a701fa23e07c3789
scikits/umfpack/setup.py
scikits/umfpack/setup.py
#!/usr/bin/env python # 05.12.2005, c from __future__ import division, print_function, absolute_import def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, dict_append config = Configuration('umfpack', par...
#!/usr/bin/env python # 05.12.2005, c from __future__ import division, print_function, absolute_import import sys def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, dict_append config = Configuration('um...
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
Python
bsd-3-clause
scikit-umfpack/scikit-umfpack,scikit-umfpack/scikit-umfpack,rc/scikit-umfpack-rc,rc/scikit-umfpack,rc/scikit-umfpack,rc/scikit-umfpack-rc
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # 05.12.2005, c from __future__ import division, print_function, absolute_import +import sys def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration @@ -14,7 +15,8 @@ ## The following addition is needed when ...
6c4a2d6f80d7ee5f9c06c3d678bb86661c94a793
tools/np_suppressions.py
tools/np_suppressions.py
suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, an...
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be sup...
Add documentation on one assertion, convert RE's to raw strings.
Add documentation on one assertion, convert RE's to raw strings.
Python
bsd-3-clause
numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor
--- +++ @@ -1,11 +1,14 @@ suppressions = [ - [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], + # This one cannot be covered by any Python language test because there is + # no code pathway to it. But it is part of the C API, so must not be + # excised from the code. + [ r".*/multiarray/mapping...
dcba8b90b84506a7325f8e576d10ccb8d2e9a415
setuptools/py24compat.py
setuptools/py24compat.py
""" Forward-compatibility support for Python 2.4 and earlier """ # from jaraco.compat 1.2 try: from functools import wraps except ImportError: def wraps(func): "Just return the function unwrapped" return lambda x: x
""" Forward-compatibility support for Python 2.4 and earlier """ # from jaraco.compat 1.2 try: from functools import wraps except ImportError: def wraps(func): "Just return the function unwrapped" return lambda x: x try: import hashlib except ImportError: from setuptools._backport imp...
Add a shim for python 2.4 compatability with hashlib
Add a shim for python 2.4 compatability with hashlib --HG-- extra : rebase_source : 5f573e600aadbe9c95561ee28c05cee02c7db559
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
--- +++ @@ -9,3 +9,9 @@ def wraps(func): "Just return the function unwrapped" return lambda x: x + + +try: + import hashlib +except ImportError: + from setuptools._backport import hashlib
03977d24d5862373a881b7098bc78adc30fe8256
make_src_bem.py
make_src_bem.py
from __future__ import print_function import mne from my_settings import * subject = sys.argv[1] # make source space src = mne.setup_source_space(subject, spacing='oct6', subjects_dir=subjects_dir, add_dist=False, overwrite=True) # save source space mne.writ...
from __future__ import print_function import mne import subprocess from my_settings import * subject = sys.argv[1] cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis" # make source space src = mne.setup_source_space(subject, spacing='oct6', subjects_dir=subjects_dir, ...
Change to make BEM solution from mne-C
Change to make BEM solution from mne-C
Python
bsd-3-clause
MadsJensen/RP_scripts,MadsJensen/RP_scripts,MadsJensen/RP_scripts
--- +++ @@ -1,21 +1,30 @@ from __future__ import print_function import mne +import subprocess from my_settings import * subject = sys.argv[1] + +cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis" # make source space src = mne.setup_source_space(subject, spacing='oct6', ...
27c614b30eda339ca0c61f35e498be6456f2280f
scoring/__init__.py
scoring/__init__.py
import numpy as np from sklearn.cross_validation import cross_val_score from sklearn.externals import joblib as pickle class scorer(object): def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}): self.model = model() self.descriptor_generator = descriptor_generator(**desc...
import numpy as np from sklearn.cross_validation import cross_val_score from sklearn.externals import joblib as pickle class scorer(object): def __init__(self, model_instance, descriptor_generator_instance): self.model = model_instance self.descriptor_generator = descriptor_generator_instance ...
Make scorer accept instances of model and desc. gen.
Make scorer accept instances of model and desc. gen.
Python
bsd-3-clause
mwojcikowski/opendrugdiscovery
--- +++ @@ -3,9 +3,9 @@ from sklearn.externals import joblib as pickle class scorer(object): - def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}): - self.model = model() - self.descriptor_generator = descriptor_generator(**desc_opts) + def __init__(self, model_ins...
c9b6cec70b2162b98d836f8100bc039f19fe23cb
googleapiclient/__init__.py
googleapiclient/__init__.py
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
Bump version number to 1.4.1
Bump version number to 1.4.1
Python
apache-2.0
googleapis/google-api-python-client,googleapis/google-api-python-client
--- +++ @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "1.4.0" +__version__ = "1.4.1"
3963037eb008d077e439029a33b60516cde399c6
massa/config.py
massa/config.py
# -*- coding: utf-8 -*- import logging class Production(object): DEBUG = False TESTING = False SECRET_KEY = '##CHANGEME##' SQLALCHEMY_DATABASE_URI = 'postgresql://massa:secret@localhost/massa' SQLALCHEMY_ECHO = False class Development(Production): DEBUG = True LOGGER_LEVEL = logging.DEB...
# -*- coding: utf-8 -*- class Production(object): DEBUG = False TESTING = False SECRET_KEY = '##CHANGEME##' SQLALCHEMY_DATABASE_URI = 'postgresql://massa:secret@localhost/massa' SQLALCHEMY_ECHO = False class Development(Production): DEBUG = True LOGGER_LEVEL = 10
Define logging level with a numeric value.
Define logging level with a numeric value.
Python
mit
jaapverloop/massa
--- +++ @@ -1,7 +1,4 @@ # -*- coding: utf-8 -*- - -import logging - class Production(object): DEBUG = False @@ -13,4 +10,4 @@ class Development(Production): DEBUG = True - LOGGER_LEVEL = logging.DEBUG + LOGGER_LEVEL = 10
b5477239d7b1ee9e73265b023355e8e83826ec49
scrapy_rss/items.py
scrapy_rss/items.py
# -*- coding: utf-8 -*- import scrapy from scrapy.item import BaseItem from scrapy_rss.elements import * from scrapy_rss import meta import six @six.add_metaclass(meta.ItemMeta) class RssItem: title = TitleElement() link = LinkElement() description = DescriptionElement() author = AuthorElement() ...
# -*- coding: utf-8 -*- import scrapy from scrapy.item import BaseItem from scrapy_rss.elements import * from scrapy_rss import meta import six @six.add_metaclass(meta.ItemMeta) class RssItem(BaseItem): title = TitleElement() link = LinkElement() description = DescriptionElement() author = AuthorElem...
Fix RssItem when each scraped item is instance of RssItem
Fix RssItem when each scraped item is instance of RssItem
Python
bsd-3-clause
woxcab/scrapy_rss
--- +++ @@ -8,7 +8,7 @@ @six.add_metaclass(meta.ItemMeta) -class RssItem: +class RssItem(BaseItem): title = TitleElement() link = LinkElement() description = DescriptionElement()
c3937702d8d9fa4ef7661a555876ad69654f88fd
scenarios/passtr/bob_cfg.py
scenarios/passtr/bob_cfg.py
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig class AUTH_CREDS(AUTH_CREDS_orig): enalgs = ('SHA-256-sess', 'SHA-256', 'MD5-sess', 'MD5', None) realm = 'VoIPTests.NET' def __init__(self): AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
Enable all auth algorithms that might be emitted by the alice.
Enable all auth algorithms that might be emitted by the alice.
Python
bsd-2-clause
sippy/voiptests,sippy/voiptests
--- +++ @@ -0,0 +1,8 @@ +from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig + +class AUTH_CREDS(AUTH_CREDS_orig): + enalgs = ('SHA-256-sess', 'SHA-256', 'MD5-sess', 'MD5', None) + realm = 'VoIPTests.NET' + + def __init__(self): + AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
ee69971832120f4492e8f41abfbcb9c87e398d6a
DeepFried2/utils.py
DeepFried2/utils.py
import theano as _th import numpy as _np def create_param(shape, init, fan=None, name=None, type=_th.config.floatX): return _th.shared(init(shape, fan).astype(type), name=name) def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX): val = init(shape, fan).astype(type) param ...
import theano as _th import numpy as _np def create_param(shape, init, fan=None, name=None, type=_th.config.floatX): return _th.shared(init(shape, fan).astype(type), name=name) def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX): val = init(shape, fan).astype(type) param ...
Add utility to save/load parameters, i.e. models.
Add utility to save/load parameters, i.e. models. Also adds a utility to compute the number of parameters, because that's always interesting and often reported in papers.
Python
mit
yobibyte/DeepFried2,lucasb-eyer/DeepFried2,elPistolero/DeepFried2,Pandoro/DeepFried2
--- +++ @@ -19,3 +19,20 @@ broadcastable=other.broadcastable, name=prefix + str(other.name) ) + + +def count_params(module): + params, _ = module.parameters() + return sum(p.get_value().size for p in params) + + +def save_params(module, where): + params, _ = module.parameters() + _n...
29e4dc4b11f691a8aaf4b987e6a9e74214f19365
journal.py
journal.py
# -*- coding: utf-8 -*- from flask import Flask import os import psycopg2 from contextlib import closing DB_SCHEMA = """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ app = Flask(__name__) ...
# -*- coding: utf-8 -*- from flask import Flask from flask import g import os import psycopg2 from contextlib import closing DB_SCHEMA = """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ ap...
Add flask.g and connection/teardown operators.
Add flask.g and connection/teardown operators.
Python
mit
lfritts/learning_journal,lfritts/learning_journal
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from flask import Flask +from flask import g import os import psycopg2 from contextlib import closing @@ -35,6 +36,27 @@ db.commit() +def get_database_connection(): + db = getattr(g, 'db', None) + if db is None: + g.db = db = connect_db() ...
9e7e61256eb2ca2b4f4f19ce5b926709a593a28b
vispy/app/tests/test_interactive.py
vispy/app/tests/test_interactive.py
from nose.tools import assert_equal, assert_true, assert_false, assert_raises from vispy.testing import assert_in, run_tests_if_main from vispy.app import set_interactive from vispy.ext.ipy_inputhook import inputhook_manager # Expect the inputhook_manager to set boolean `_in_event_loop` # on instances of this class ...
from nose.tools import assert_equal, assert_true, assert_false from vispy.testing import assert_in, run_tests_if_main from vispy.app import set_interactive from vispy.ext.ipy_inputhook import inputhook_manager # Expect the inputhook_manager to set boolean `_in_event_loop` # on instances of this class when enabled. c...
Fix for flake8 checks on new test file.
Fix for flake8 checks on new test file.
Python
bsd-3-clause
jay3sh/vispy,ghisvail/vispy,hronoses/vispy,kkuunnddaannkk/vispy,michaelaye/vispy,dchilds7/Deysha-Star-Formation,sh4wn/vispy,QuLogic/vispy,srinathv/vispy,sh4wn/vispy,QuLogic/vispy,julienr/vispy,kkuunnddaannkk/vispy,drufat/vispy,Eric89GXL/vispy,jay3sh/vispy,jdreaver/vispy,RebeccaWPerry/vispy,RebeccaWPerry/vispy,jay3sh/vi...
--- +++ @@ -1,4 +1,4 @@ -from nose.tools import assert_equal, assert_true, assert_false, assert_raises +from nose.tools import assert_equal, assert_true, assert_false from vispy.testing import assert_in, run_tests_if_main from vispy.app import set_interactive
efc0f438e894fa21ce32665ec26c19751ec2ce10
ureport_project/wsgi_app.py
ureport_project/wsgi_app.py
# wsgi_app.py import sys, os filedir = os.path.dirname(__file__) sys.path.append(os.path.join(filedir)) #print sys.path os.environ["CELERY_LOADER"] = "django" os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import sys print sys.path from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler()
# wsgi_app.py import sys, os filedir = os.path.dirname(__file__) sys.path.append(os.path.join(filedir)) #print sys.path os.environ["CELERY_LOADER"] = "django" os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import sys print sys.path from django.core.handlers.wsgi import WSGIHandler from linesman.middleware import...
Apply linesman profiler to the wsgi app
Apply linesman profiler to the wsgi app I fully expect this commit to be backed out when we get the profiling stuff sorted out, but thankfully, this profiler can be disabled for a live site. check out http://<site>/__profiler__ after installing linesman, and running the uwsgi server
Python
bsd-3-clause
unicefuganda/ureport,unicefuganda/ureport,unicefuganda/ureport,mbanje/ureport_uganda,mbanje/ureport_uganda
--- +++ @@ -12,5 +12,7 @@ print sys.path from django.core.handlers.wsgi import WSGIHandler +from linesman.middleware import make_linesman_middleware application = WSGIHandler() +application = make_linesman_middleware(application)
5ba9888d267d663fb0ab0dfbfd9346dc20f4c0c1
test/test_turtle_serialize.py
test/test_turtle_serialize.py
import rdflib from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = rdflib.Graph() u = rdflib.URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (u, u, u) ) s=g.serialize(format='turtle') assert b("ns:bob."...
from rdflib import Graph, URIRef, BNode, RDF, Literal from rdflib.collection import Collection from rdflib.py3compat import b def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ g = Graph() u = URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") g.add( (...
Test boolean list serialization in Turtle
Test boolean list serialization in Turtle
Python
bsd-3-clause
RDFLib/rdflib,ssssam/rdflib,armandobs14/rdflib,yingerj/rdflib,RDFLib/rdflib,ssssam/rdflib,ssssam/rdflib,avorio/rdflib,marma/rdflib,marma/rdflib,RDFLib/rdflib,ssssam/rdflib,dbs/rdflib,armandobs14/rdflib,dbs/rdflib,dbs/rdflib,marma/rdflib,avorio/rdflib,marma/rdflib,yingerj/rdflib,RDFLib/rdflib,yingerj/rdflib,dbs/rdflib,a...
--- +++ @@ -1,19 +1,45 @@ -import rdflib +from rdflib import Graph, URIRef, BNode, RDF, Literal +from rdflib.collection import Collection from rdflib.py3compat import b + def testTurtleFinalDot(): """ https://github.com/RDFLib/rdflib/issues/282 """ - g = rdflib.Graph() - u = rdflib.URIRef(...
8126ca21bcf8da551906eff348c92cb71fe79e6e
readthedocs/doc_builder/base.py
readthedocs/doc_builder/base.py
import os def restoring_chdir(fn): def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """ The Base for all Builders. Defines the API for subclasses. """...
import os from functools import wraps def restoring_chdir(fn): @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """ The Base for all Builder...
Call wraps on the restoring_chdir decorator.
Call wraps on the restoring_chdir decorator.
Python
mit
alex/readthedocs.org,safwanrahman/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,safwanrahman/readthedocs.org,alex/readthedocs.org,tddv/readthedocs.org,dirn/readthedocs.org,takluyver/readthedocs.org,nikolas/readthedocs.org,LukasBoersma/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.or...
--- +++ @@ -1,7 +1,8 @@ import os - +from functools import wraps def restoring_chdir(fn): + @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd()
e229d8f731b8b34294127702b1333eefec6f95bc
server/main.py
server/main.py
from flask import Flask import yaml app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config =...
from flask import Flask import yaml import sql import psycopg2 app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.ya...
Add SQL imports to python
Add SQL imports to python
Python
mit
aradler/Card-lockout,aradler/Card-lockout,aradler/Card-lockout
--- +++ @@ -1,5 +1,7 @@ from flask import Flask import yaml +import sql +import psycopg2 app = Flask(__name__)
9428a6181cd33b5847dd1a348a651a4c794092ab
salt/modules/logmod.py
salt/modules/logmod.py
""" On-demand logging ================= .. versionadded:: 2017.7.0 The sole purpose of this module is logging messages in the (proxy) minion. It comes very handy when debugging complex Jinja templates, for example: .. code-block:: jinja {%- for var in range(10) %} {%- do salt.log.info(var) -%} {%- end...
""" On-demand logging ================= .. versionadded:: 2017.7.0 The sole purpose of this module is logging messages in the (proxy) minion. It comes very handy when debugging complex Jinja templates, for example: .. code-block:: jinja {%- for var in range(10) %} {%- do salt["log.info"](var) -%} {%- ...
Update jinja example to recommended syntax
Update jinja example to recommended syntax
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -10,7 +10,7 @@ .. code-block:: jinja {%- for var in range(10) %} - {%- do salt.log.info(var) -%} + {%- do salt["log.info"](var) -%} {%- endfor %} CLI Example:
76bf8966a25932822fca1c94586fccfa096ee02b
tests/misc/test_base_model.py
tests/misc/test_base_model.py
# -*- coding: UTF-8 -*- from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_repr(self): self.generate_fixture_project_status() self.generate_fixture_project() self.assertEqual(str(self.project), "<Project Cosmos Landromat>") self.project.name = u"...
# -*- coding: UTF-8 -*- from tests.base import ApiDBTestCase class BaseModelTestCase(ApiDBTestCase): def test_repr(self): self.generate_fixture_project_status() self.generate_fixture_project() self.assertEqual(str(self.project), "<Project %s>" % self.project.id) def test_query(self):...
Change base model string representation
Change base model string representation
Python
agpl-3.0
cgwire/zou
--- +++ @@ -7,9 +7,7 @@ def test_repr(self): self.generate_fixture_project_status() self.generate_fixture_project() - self.assertEqual(str(self.project), "<Project Cosmos Landromat>") - self.project.name = u"Big Buck Bunny" - self.assertEqual(str(self.project), "<Project Bi...
c908edadadb866292a612103d2854bef4673efab
shinken/__init__.py
shinken/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can r...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can r...
Remove superfluous import of shinken.objects in shinken/_init__.py.
Remove superfluous import of shinken.objects in shinken/_init__.py. Every script or test-case importing shinken has all the objects loaded, even if they are not required by the script or test-case at all. Also see <http://sourceforge.net/mailarchive/message.php?msg_id=29553474>.
Python
agpl-3.0
naparuba/shinken,claneys/shinken,naparuba/shinken,tal-nino/shinken,mohierf/shinken,titilambert/alignak,lets-software/shinken,KerkhoffTechnologies/shinken,Simage/shinken,mohierf/shinken,gst/alignak,lets-software/shinken,Aimage/shinken,Aimage/shinken,geektophe/shinken,Aimage/shinken,staute/shinken_package,savoirfairelinu...
--- +++ @@ -21,6 +21,3 @@ # # You should have received a copy of the GNU Affero General Public License # along with Shinken. If not, see <http://www.gnu.org/licenses/>. - -# shinken.objects must be imported first: -import objects
3153d1d25e8b6c25729880abca4da9a79f8036ff
editorsnotes/main/admin_views.py
editorsnotes/main/admin_views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect from django.template import RequestContext from django.contrib.auth.models import User, Group from django.contrib import messages from models import Project from forms import ProjectUserFormSet def project_r...
from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect from django.template import RequestContext from django.contrib.auth.models import User, Group from django.contrib import messages from models import Project from forms import ProjectUserFormSet def project_r...
Check if user can edit project roster
Check if user can edit project roster
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
--- +++ @@ -9,6 +9,25 @@ def project_roster(request, project_id): o = {} project = get_object_or_404(Project, id=project_id) + + user = request.user + user_affiliation = user.get_profile().affiliation + editor = Group.objects.get(name='Editors') + admin = Group.objects.get(name='Admins') + + ...
85f759a9446cf988cc859d3b74d11e6b224bbd16
request/managers.py
request/managers.py
from datetime import timedelta, datetime from django.db import models from django.contrib.auth.models import User class RequestManager(models.Manager): def active_users(self, **options): """ Returns a list of active users. Any arguments passed to this method will be given t...
from datetime import timedelta, datetime from django.db import models from django.contrib.auth.models import User class RequestManager(models.Manager): def active_users(self, **options): """ Returns a list of active users. Any arguments passed to this method will be given t...
Use a list comprehension and set() to make the active_users query simpler and faster.
Use a list comprehension and set() to make the active_users query simpler and faster.
Python
bsd-2-clause
kylef/django-request,gnublade/django-request,Derecho/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request,kylef/django-request
--- +++ @@ -23,12 +23,4 @@ requests = qs.select_related('user').only('user') - users = [] - done = [] - - for request in requests: - if not (request.user.pk in done): - done.append(request.user.pk) - users.append(reques...
cad9194d64786acadb49174f8797295f1bf0bcca
website/celery_worker.py
website/celery_worker.py
from app import celery from app import create_app app = create_app(config_override={'BDB_READONLY': True}) celery
from app import celery from app import create_app app = create_app(config_override={'HDB_READONLY': True}) celery
Update config variable name of HDB in celery worker
Update config variable name of HDB in celery worker
Python
lgpl-2.1
reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Gen...
--- +++ @@ -1,5 +1,5 @@ from app import celery from app import create_app -app = create_app(config_override={'BDB_READONLY': True}) +app = create_app(config_override={'HDB_READONLY': True}) celery
11583cfca501164c5c08af70f66d430cd180dbc5
examples/basic_nest/make_nest.py
examples/basic_nest/make_nest.py
#!/usr/bin/env python import collections import os import os.path import sys from nestly import nestly wd = os.getcwd() input_dir = os.path.join(wd, 'inputs') ctl = collections.OrderedDict() ctl['strategy'] = nestly.repeat_iterable(('exhaustive', 'approximate')) ctl['run_count'] = nestly.repeat_iterable([10**(i + 1...
#!/usr/bin/env python import glob import os import os.path from nestly import Nest wd = os.getcwd() input_dir = os.path.join(wd, 'inputs') nest = Nest() nest.add_level('strategy', ('exhaustive', 'approximate')) nest.add_level('run_count', [10**i for i in xrange(3)]) nest.add_level('input_file', glob.glob(os.path.joi...
Update basic_nest for new API
Update basic_nest for new API
Python
mit
fhcrc/nestly
--- +++ @@ -1,18 +1,17 @@ #!/usr/bin/env python -import collections +import glob import os import os.path -import sys -from nestly import nestly +from nestly import Nest wd = os.getcwd() input_dir = os.path.join(wd, 'inputs') -ctl = collections.OrderedDict() +nest = Nest() +nest.add_level('strategy', ('exh...
978b41a29eda295974ed5cf1a7cd5b79b148f479
coverage/execfile.py
coverage/execfile.py
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.arg...
"""Execute files of Python code.""" import imp, os, sys def run_python_file(filename, args): """Run a python source file as if it were the main program on the python command line. `filename` is the path to the file to execute, must be a .py file. `args` is the argument array to present as sys.arg...
Move the open outside the try, since the finally is only needed once the file is successfully opened.
Move the open outside the try, since the finally is only needed once the file is successfully opened.
Python
apache-2.0
7WebPages/coveragepy,blueyed/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,ne...
--- +++ @@ -20,8 +20,8 @@ sys.argv = args sys.path[0] = os.path.dirname(filename) + src = open(filename) try: - src = open(filename) imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE)) finally: src.close()
84d3738d2eb8a24dcb66cb329994f88bd55128c0
tests/test_utils.py
tests/test_utils.py
import pytest def test_scrub_doi(): from vdm.utils import scrub_doi d = 'http://dx.doi.org/10.1234' scrubbed = scrub_doi(d) assert(scrubbed == '10.1234') d = '10.123 4' assert( scrub_doi(d) == '10.1234' ) d = '<p>10.1234</p>' assert( scrub_doi(d) == '10.1234' ...
import pytest def test_scrub_doi(): from vdm.utils import scrub_doi d = 'http://dx.doi.org/10.1234' scrubbed = scrub_doi(d) assert(scrubbed == '10.1234') d = '10.123 4' assert( scrub_doi(d) == '10.1234' ) d = '<p>10.1234</p>' assert( scrub_doi(d) == '10.1234' ...
Add utils tests. Rework pull.
Add utils tests. Rework pull.
Python
mit
Brown-University-Library/vivo-data-management,Brown-University-Library/vivo-data-management
--- +++ @@ -18,3 +18,12 @@ assert( scrub_doi(d) == '10.1234' ) + + +def test_pull(): + from vdm.utils import pull + d = {} + d['mykey'] = 'Value' + assert( + pull(d, 'mykey') == 'Value' + )
c34840a7ac20d22e650be09a515cee9dbfcf6043
tests/test_views.py
tests/test_views.py
from django.http import HttpResponse from djproxy.views import HttpProxy DOWNSTREAM_INJECTION = lambda x: x class LocalProxy(HttpProxy): base_url = "http://sitebuilder.qa.yola.net/en/ide/Yola/Yola.session.jsp" class SBProxy(HttpProxy): base_url = "http://sitebuilder.qa.yola.net/en/APIController" def ind...
from django.http import HttpResponse from djproxy.views import HttpProxy class LocalProxy(HttpProxy): base_url = "http://localhost:8000/some/content/" def index(request): return HttpResponse('Some content!', status=200) class BadTestProxy(HttpProxy): pass class GoodTestProxy(HttpProxy): base_ur...
Remove accidentally committed test code
Remove accidentally committed test code
Python
mit
thomasw/djproxy
--- +++ @@ -2,19 +2,12 @@ from djproxy.views import HttpProxy -DOWNSTREAM_INJECTION = lambda x: x - class LocalProxy(HttpProxy): - base_url = "http://sitebuilder.qa.yola.net/en/ide/Yola/Yola.session.jsp" - - -class SBProxy(HttpProxy): - base_url = "http://sitebuilder.qa.yola.net/en/APIController" + b...
2351100234180afc6f6510140e9f989051fb6511
PyFVCOM/__init__.py
PyFVCOM/__init__.py
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '2.0.0' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy from PyFVCOM im...
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '2.0.0' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy from PyFVCOM im...
Fix module name to import.
Fix module name to import.
Python
mit
pwcazenave/PyFVCOM
--- +++ @@ -25,5 +25,5 @@ from PyFVCOM import tidal_ellipse from PyFVCOM import tide from PyFVCOM import plot -from PyFVCOM import read_results +from PyFVCOM import read from PyFVCOM import utilities
ab418734f432691ec4a927be32364ee85baab35c
__init__.py
__init__.py
import inspect import python2.httplib2 as httplib2 globals().update(inspect.getmembers(httplib2))
import inspect import sys if sys.version_info[0] == 2: from .python2 import httplib2 else: from .python3 import httplib2 globals().update(inspect.getmembers(httplib2))
Use python version dependent import
Use python version dependent import Change-Id: Iae6bc0cc8d526162b91d0c18cf1fba1461aa9f98
Python
mit
wikimedia/pywikibot-externals-httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,jayvdb/httplib2
--- +++ @@ -1,3 +1,7 @@ import inspect -import python2.httplib2 as httplib2 +import sys +if sys.version_info[0] == 2: + from .python2 import httplib2 +else: + from .python3 import httplib2 globals().update(inspect.getmembers(httplib2))
9ab7efa44a8e7267b2902b6e23ff61381d31692c
profile_collection/startup/85-robot.py
profile_collection/startup/85-robot.py
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C class Robot(Device): robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') robot_execute_cmd = C(EpicsSignal, ...
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.utils import set_and_wait class Robot(Device): sample_number = C(EpicsSignal, 'ID:Tgt-SP') load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') execute_cmd = C(E...
Add sample loading logic to Robot.
WIP: Add sample loading logic to Robot.
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
--- +++ @@ -1,13 +1,35 @@ from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C - +from ophyd.utils import set_and_wait class Robot(Device): - robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') - robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') - robot_unload_cmd = C(E...
2c6f5cfb2e90e815d74dca11c395e25875d475be
corehq/ex-submodules/phonelog/tasks.py
corehq/ex-submodules/phonelog/tasks.py
from datetime import datetime, timedelta from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from phonelog.models import DeviceReportEntry, UserErrorEntry, ForceCloseEntry, UserEntry @periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr(settings, 'CE...
from datetime import datetime, timedelta from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db import connection from phonelog.models import UserErrorEntry, ForceCloseEntry, UserEntry @periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr...
Drop table for device report logs.
Drop table for device report logs.
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -2,13 +2,17 @@ from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings -from phonelog.models import DeviceReportEntry, UserErrorEntry, ForceCloseEntry, UserEntry +from django.db import connection +from phonelog.models import UserErrorEntry, ForceCloseE...
02c18a46935d58ac08a340e5011fb345ffb7f83a
h2o-py/tests/testdir_algos/gbm/pyunit_cup98_01GBM_medium.py
h2o-py/tests/testdir_algos/gbm/pyunit_cup98_01GBM_medium.py
import sys sys.path.insert(1, "../../../") import h2o def cupMediumGBM(ip,port): # Connect to h2o h2o.init(ip,port) train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv")) test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv")) train["TARGET_B"] = trai...
import sys sys.path.insert(1, "../../../") import h2o def cupMediumGBM(ip,port): # Connect to h2o h2o.init(ip,port) train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv")) test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv")) train["TARGET_B"] = trai...
Update test for new column naming rules. Remove '' as a name and call column 'C1'
Update test for new column naming rules. Remove '' as a name and call column 'C1'
Python
apache-2.0
bospetersen/h2o-3,spennihana/h2o-3,mrgloom/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,jangorecki/h2o-3,junwucs/h2o-3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,datachand/h2o-3,ChristosChristofidis/h2o-3,bospetersen/h2o-3,brightchen/h2o-3,jangorecki/h2o-3,m...
--- +++ @@ -13,7 +13,7 @@ # Train H2O GBM Model: train_cols = train.names() - for c in ['', "TARGET_D", "TARGET_B", "CONTROLN"]: + for c in ['C1', "TARGET_D", "TARGET_B", "CONTROLN"]: train_cols.remove(c) model = h2o.gbm(x=train[train_cols], y=train["TARGET_B"], distribution = "bernoulli", ntrees = ...
5025bff2ca9a4f31a371ecbd9255b1fb92b9cc4d
kafka_influxdb/encoder/echo_encoder.py
kafka_influxdb/encoder/echo_encoder.py
class Encoder(object): @staticmethod def encode(msg): """ Don't change the message at all :param msg: """ return msg
try: # Test for mypy support (requires Python 3) from typing import Text except: pass class Encoder(object): @staticmethod def encode(msg): # type: (bytes) -> List[bytes] """ Don't change the message at all :param msg: """ return [msg]
Return a list of messages in echo encoder and add mypy type hints
Return a list of messages in echo encoder and add mypy type hints
Python
apache-2.0
mre/kafka-influxdb,mre/kafka-influxdb
--- +++ @@ -1,8 +1,15 @@ +try: + # Test for mypy support (requires Python 3) + from typing import Text +except: + pass + class Encoder(object): @staticmethod def encode(msg): + # type: (bytes) -> List[bytes] """ Don't change the message at all :param msg: ...
2722a59aad0775f1bcd1e81232ff445b9012a2ae
ssim/compat.py
ssim/compat.py
"""Compatibility routines.""" from __future__ import absolute_import import sys try: import Image # pylint: disable=import-error,unused-import except ImportError: from PIL import Image # pylint: disable=unused-import try: import ImageOps # pylint: disable=import-error,unused-import except ImportError...
"""Compatibility routines.""" from __future__ import absolute_import import sys try: import Image # pylint: disable=import-error,unused-import except ImportError: from PIL import Image # pylint: disable=unused-import try: import ImageOps # pylint: disable=import-error,unused-import except ImportError...
Add pylint to disable redefined variable.
Add pylint to disable redefined variable.
Python
mit
jterrace/pyssim
--- +++ @@ -17,4 +17,5 @@ if sys.version_info[0] > 2: basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name else: + # pylint: disable=redefined-variable-type basestring = basestring # pylint: disable=invalid-name
659659270ef067baf0edea5de5bb10fdab532eaa
run-tests.py
run-tests.py
#!/usr/bin/env python from __future__ import print_function from optparse import OptionParser from subprocess import Popen import os import sys def run_command(cmdline): proc = Popen(cmdline, shell=True) proc.communicate() return proc.returncode def main(): parser = OptionParser() parser.add_o...
#!/usr/bin/env python from __future__ import print_function from optparse import OptionParser from subprocess import Popen import os import sys def run_command(cmdline): proc = Popen(cmdline, shell=True) proc.communicate() return proc.returncode def main(): parser = OptionParser() parser.add_o...
Remove SALADIR from environment if present
tests: Remove SALADIR from environment if present
Python
mit
akheron/sala,akheron/sala
--- +++ @@ -41,6 +41,10 @@ os.environ['COVERAGE'] = 'yes' os.environ['COVERAGE_FILE'] = os.path.abspath('.coverage') + if 'SALADIR' in os.environ: + # Remove SALADIR from environ to avoid failing tests + del os.environ['SALADIR'] + run_command('cram test') if options.c...
431720194c20dde7b19236d2302c0f9910fd7ea4
pseudorandom.py
pseudorandom.py
import os from flask import Flask, render_template from names import get_full_name app = Flask(__name__) @app.route("/") def index(): return render_template('index.html', name=get_full_name()) if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, render_template, request from names import get_full_name app = Flask(__name__) @app.route("/") def index(): if request.headers.get('User-Agent', '')[:4].lower() == 'curl': return u"{0}\n".format(get_full_name()) else: return render_template('index.html', na...
Send just plaintext name if curl is used
Send just plaintext name if curl is used
Python
mit
treyhunner/pseudorandom.name,treyhunner/pseudorandom.name
--- +++ @@ -1,5 +1,5 @@ import os -from flask import Flask, render_template +from flask import Flask, render_template, request from names import get_full_name @@ -8,7 +8,10 @@ @app.route("/") def index(): - return render_template('index.html', name=get_full_name()) + if request.headers.get('User-Agent...
411ae98889d3611151a6f94d661b86b1bbc5e026
apis/Google.Cloud.Speech.V1/synth.py
apis/Google.Cloud.Speech.V1/synth.py
import os from synthtool import shell from pathlib import Path # Parent of the script is the API-specific directory # Parent of the API-specific directory is the apis directory # Parent of the apis directory is the repo root root = Path(__file__).parent.parent.parent package = Path(__file__).parent.name shell.run( ...
import sys from synthtool import shell from pathlib import Path # Parent of the script is the API-specific directory # Parent of the API-specific directory is the apis directory # Parent of the apis directory is the repo root root = Path(__file__).parent.parent.parent package = Path(__file__).parent.name bash = '/bin...
Use the right bash command based on platform
Use the right bash command based on platform
Python
apache-2.0
googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet
--- +++ @@ -1,4 +1,4 @@ -import os +import sys from synthtool import shell from pathlib import Path @@ -8,7 +8,11 @@ root = Path(__file__).parent.parent.parent package = Path(__file__).parent.name +bash = '/bin/bash' +if sys.platform == 'win32': + bash = '"C:\\Program Files\\Git\\bin\\bash.exe"' + shell.run...
a1f26386bec0c4d39bce77d0fd3975ae4b0930d0
apps/package/tests/test_handlers.py
apps/package/tests/test_handlers.py
from django.test import TestCase class TestRepoHandlers(TestCase): def test_repo_registry(self): from package.handlers import get_repo, supported_repos g = get_repo("github") self.assertEqual(g.title, "Github") self.assertEqual(g.url, "https://github.com") self.assertTrue("...
from django.test import TestCase class TestRepoHandlers(TestCase): def test_repo_registry(self): from package.handlers import get_repo, supported_repos g = get_repo("github") self.assertEqual(g.title, "Github") self.assertEqual(g.url, "https://github.com") self.assertTrue("...
Test what get_repo() does for unsupported repos
Test what get_repo() does for unsupported repos
Python
mit
nanuxbe/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,miketheman/opencomparison,benracine/opencomparison,QLGu/djangopackages,cartwheelweb/packaginator,miketheman/opencomparison,audreyr/opencomparison,benracine/opencomparison,audreyr/opencomparison,QLGu/djangopackages,cartwheelweb/pack...
--- +++ @@ -8,3 +8,5 @@ self.assertEqual(g.url, "https://github.com") self.assertTrue("github" in supported_repos()) + + self.assertRaises(ImportError, lambda: get_repo("xyzzy"))
ab91d525abb5bb1ef476f3aac2c034e50f85617a
src/apps/contacts/mixins.py
src/apps/contacts/mixins.py
from apps.contacts.models import BaseContact class ContactMixin(object): """ Would be used for adding contacts functionality to models with contact data. """ def get_contacts(self, is_primary=False): """ Returns dict with all contacts. Example: >> obj.get_contacts() ...
from apps.contacts.models import BaseContact class ContactMixin(object): """ Would be used for adding contacts functionality to models with contact data. """ def get_contacts(self, is_primary=False): """ Returns dict with all contacts. Example: >> obj.get_contacts() ...
Fix description for contact mixin
Fix description for contact mixin
Python
mit
wis-software/office-manager
--- +++ @@ -13,8 +13,8 @@ >> obj.get_contacts() << {'email': [], 'skype': []} - :param is_primary: - :return: + :param is_primary: bool Return only primary contacts. + :return: dict """ subclasses = BaseContact.__subclasses__() results = {}
51d09e2552c31e74b85c2e6bd12bcbab7e1b2047
pygs/test/stress_utils.py
pygs/test/stress_utils.py
import os import sys def get_mem_usage(): """returns percentage and vsz mem usage of this script""" pid = os.getpid() psout = os.popen( "ps -p %s u"%pid ).read() parsed_psout = psout.split("\n")[1].split() return float(parsed_psout[3]), int( parsed_psout[4] )
import os import sys def get_mem_usage(): """returns percentage and vsz mem usage of this script""" pid = os.getpid() psout = os.popen( "ps u -p %s"%pid ).read() parsed_psout = psout.split("\n")[1].split() return float(parsed_psout[3]), int( parsed_psout[4] )
Make ps shell-out Mac and debian compliant.
Make ps shell-out Mac and debian compliant.
Python
bsd-3-clause
jeriksson/graphserver,jeriksson/graphserver,graphserver/graphserver,bmander/graphserver,brendannee/Bikesy-Backend,brendannee/Bikesy-Backend,brendannee/Bikesy-Backend,jeriksson/graphserver,jeriksson/graphserver,bmander/graphserver,jeriksson/graphserver,graphserver/graphserver,brendannee/Bikesy-Backend,brendannee/Bikesy-...
--- +++ @@ -4,7 +4,7 @@ def get_mem_usage(): """returns percentage and vsz mem usage of this script""" pid = os.getpid() - psout = os.popen( "ps -p %s u"%pid ).read() + psout = os.popen( "ps u -p %s"%pid ).read() parsed_psout = psout.split("\n")[1].split()
b05eacfa7f2a3fb653ec4a9653780d211245bfb1
pyvac/helpers/calendar.py
pyvac/helpers/calendar.py
import logging import caldav from dateutil.relativedelta import relativedelta log = logging.getLogger(__file__) def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:...
import logging import caldav from dateutil.relativedelta import relativedelta log = logging.getLogger(__file__) def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:...
Use now 'oop' method from creating principal object, prevent 'path handling error' with baikal caldav server
Use now 'oop' method from creating principal object, prevent 'path handling error' with baikal caldav server
Python
bsd-3-clause
doyousoft/pyvac,sayoun/pyvac,doyousoft/pyvac,sayoun/pyvac,doyousoft/pyvac,sayoun/pyvac
--- +++ @@ -20,7 +20,7 @@ """ client = caldav.DAVClient(url) - principal = caldav.Principal(client, url) + principal = client.principal() calendars = principal.calendars() if not len(calendars): return False
548e54c0a3e5fe7115b6f92e449c53f5a08ba5de
tests/setup.py
tests/setup.py
import os import os.path def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('tests',parent_package,top_path) config.add_subpackage('examples') return config if __name__ == '__main__': from numpy.distutils.core import setu...
import os import os.path def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numsconstests',parent_package,top_path) config.add_subpackage('examples') return config if __name__ == '__main__': from numpy.distutils.core imp...
Change the name for end-to-end numscons tests
Change the name for end-to-end numscons tests
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
--- +++ @@ -3,7 +3,7 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration - config = Configuration('tests',parent_package,top_path) + config = Configuration('numsconstests',parent_package,top_path) config.add_subpackage('examples') return...
d51d9cc67eca9566673e963e824dc335eb47a9af
recipy/utils.py
recipy/utils.py
import sys from .log import log_input, log_output def open(*args, **kwargs): """Built-in open replacement that logs input and output Workaround for issue #44. Patching `__builtins__['open']` is complicated, because many libraries use standard open internally, while we only want to log inputs and out...
import six from .log import log_input, log_output def open(*args, **kwargs): """Built-in open replacement that logs input and output Workaround for issue #44. Patching `__builtins__['open']` is complicated, because many libraries use standard open internally, while we only want to log inputs and out...
Use six instead of sys.version_info
Use six instead of sys.version_info
Python
apache-2.0
recipy/recipy,recipy/recipy
--- +++ @@ -1,4 +1,4 @@ -import sys +import six from .log import log_input, log_output @@ -16,13 +16,20 @@ If python 2 is used, and an `encoding` parameter is passed to this function, `codecs` is used to open the file with proper encoding. """ - if 'mode' in kwargs.keys(): - mode = kwarg...
9e1cf6ecf8104b38c85a00e973873cbfa7d78236
bytecode.py
bytecode.py
class BytecodeBase: def __init__(self): # Eventually might want to add subclassed bytecodes here # Though __subclasses__ works quite well pass def execute(self, machine): pass class Push(BytecodeBase): def __init__(self, data): self.data = data def execute(sel...
class BytecodeBase: autoincrement = True # For jump def __init__(self): # Eventually might want to add subclassed bytecodes here # Though __subclasses__ works quite well pass def execute(self, machine): pass class Push(BytecodeBase): def __init__(self, data): ...
Add autoincrement for jump in the future
Add autoincrement for jump in the future
Python
bsd-3-clause
darbaga/simple_compiler
--- +++ @@ -1,4 +1,6 @@ class BytecodeBase: + autoincrement = True # For jump + def __init__(self): # Eventually might want to add subclassed bytecodes here # Though __subclasses__ works quite well
864653259bdcddf62f6d3c8f270099e99fbb8457
numba/cuda/tests/cudapy/test_userexc.py
numba/cuda/tests/cudapy/test_userexc.py
from __future__ import print_function, absolute_import, division from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim from numba import cuda, config class MyError(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file ([\.\/\\a-zA-Z_0-9]+), line \d+' ) class TestUserEx...
from __future__ import print_function, absolute_import, division from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim from numba import cuda, config class MyError(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+' ) class TestUserEx...
Fix up regex for path matching
Fix up regex for path matching
Python
bsd-2-clause
stuartarchibald/numba,numba/numba,jriehl/numba,jriehl/numba,IntelLabs/numba,seibert/numba,seibert/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,jriehl/numba,IntelLabs/numba,numba/numba,stonebig/numba,sklam/numba,jriehl/numba,seibert/numba,cpcloud/numba,sklam/numba,stuartarchibald/numba,numba/numba,sklam/numba,jrieh...
--- +++ @@ -9,7 +9,7 @@ regex_pattern = ( - r'In function [\'"]test_exc[\'"], file ([\.\/\\a-zA-Z_0-9]+), line \d+' + r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+' )
2034c8280800291227232435786441bfb0edace0
tests/cli.py
tests/cli.py
import os from spec import eq_ from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run("invok...
import os from spec import eq_, skip from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run(...
Add common CLI invocation test stubs.
Add common CLI invocation test stubs. Doesn't go into positional args.
Python
bsd-2-clause
frol/invoke,alex/invoke,mkusz/invoke,mattrobenolt/invoke,mattrobenolt/invoke,kejbaly2/invoke,kejbaly2/invoke,pyinvoke/invoke,pfmoore/invoke,sophacles/invoke,pfmoore/invoke,mkusz/invoke,tyewang/invoke,pyinvoke/invoke,singingwolfboy/invoke,frol/invoke
--- +++ @@ -1,6 +1,6 @@ import os -from spec import eq_ +from spec import eq_, skip from invoke import run @@ -23,3 +23,47 @@ # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n") + + def boolean_args(self): + cmd = "taskname --boolean" + ...
2e0286632b9120fe6a788db4483911513a39fe04
fabfile.py
fabfile.py
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git pull --rebase") sudo("pip3 install -r requirements.txt") ...
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git reset --hard origin/master") sudo("pip3 install -r requiremen...
Reset to upstream master instead of rebasing during deployment
Reset to upstream master instead of rebasing during deployment
Python
bsd-3-clause
FreeMusicNinja/api.freemusic.ninja
--- +++ @@ -11,7 +11,7 @@ def deploy(): with cd(env.directory): - run("git pull --rebase") + run("git reset --hard origin/master") sudo("pip3 install -r requirements.txt") sudo("python3 manage.py collectstatic --noinput", user='django') sudo("python3 manage.py migrate ...
caf94786ca8c0bc9e3995da0a160c84921a3bfc6
fabfile.py
fabfile.py
from fabric.api import task, sudo, env, local from fabric.contrib.project import rsync_project from fabric.contrib.console import confirm @task def upload_docs(): target = "/var/www/paramiko.org" staging = "/tmp/paramiko_docs" sudo("mkdir -p %s" % staging) sudo("chown -R %s %s" % (env.user, staging)) ...
from fabric.api import task, sudo, env, local, hosts from fabric.contrib.project import rsync_project from fabric.contrib.console import confirm @task @hosts("paramiko.org") def upload_docs(): target = "/var/www/paramiko.org" staging = "/tmp/paramiko_docs" sudo("mkdir -p %s" % staging) sudo("chown -R ...
Update doc upload task w/ static hostname
Update doc upload task w/ static hostname
Python
lgpl-2.1
torkil/paramiko,redixin/paramiko,SebastianDeiss/paramiko,fvicente/paramiko,zpzgone/paramiko,mirrorcoder/paramiko,reaperhulk/paramiko,jaraco/paramiko,rcorrieri/paramiko,paramiko/paramiko,CptLemming/paramiko,anadigi/paramiko,digitalquacks/paramiko,ameily/paramiko,selboo/paramiko,remram44/paramiko,varunarya10/paramiko,dav...
--- +++ @@ -1,9 +1,10 @@ -from fabric.api import task, sudo, env, local +from fabric.api import task, sudo, env, local, hosts from fabric.contrib.project import rsync_project from fabric.contrib.console import confirm @task +@hosts("paramiko.org") def upload_docs(): target = "/var/www/paramiko.org" ...
06c8c91b05e0bf5f15271560df4101d90adfeb39
Lib/test/test_capi.py
Lib/test/test_capi.py
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _test exports whose name begins with 'test_'. import sys import test_support import _testcapi for name in dir(_testcapi): if name.startswith('test_'): test = getattr(_testcapi, name) if test_support....
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _testcapi exports whose name begins with 'test_'. import sys import test_support import _testcapi for name in dir(_testcapi): if name.startswith('test_'): test = getattr(_testcapi, name) if test_supp...
Fix typo in comment (the module is now called _testcapi, not _test).
Fix typo in comment (the module is now called _testcapi, not _test).
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,5 +1,5 @@ # Run the _testcapi module tests (tests for the Python/C API): by defn, -# these are all functions _test exports whose name begins with 'test_'. +# these are all functions _testcapi exports whose name begins with 'test_'. import sys import test_support
b7cc9c5d2275a87849701e8a7307e26680bb740a
xvistaprof/reader.py
xvistaprof/reader.py
#!/usr/bin/env python # encoding: utf-8 """ Reader for XVISTA .prof tables. """ import numpy as np from astropy.table import Table from astropy.io import registry def xvista_table_reader(filename): dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float), ('ELL', np.float), ('PA', np.float), ('EMA...
#!/usr/bin/env python # encoding: utf-8 """ Reader for XVISTA .prof tables. """ import numpy as np from astropy.table import Table from astropy.io import registry def xvista_table_reader(filename): dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float), ('ELL', np.float), ('PA', np.float), ('EMA...
Update genfromtxt skip_header for numpy 1.10+
Update genfromtxt skip_header for numpy 1.10+
Python
bsd-2-clause
jonathansick/xvistaprof
--- +++ @@ -15,7 +15,7 @@ ('ELLMAG', np.float), ('ELLMAG_err', np.float), ('XC', np.float), ('YC', np.float), ('FRACONT', np.float), ('A1', np.float), ('A2', np.float), ('A4', np.float), ('CIRCMAG', np.float)] - data = np.genfromtxt(filename, dtype=np.dtype(dt), skiprows=15, + d...
e0b7b6ccdd947324ac72b48a28d6c68c7e980d96
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
--- +++ @@ -14,7 +14,7 @@ import ibmcnx.functions -dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/')) +dbs = AdminConfig.list('DataSource',AdminConfig.getid('/Cell:cnxwas1Cell01/')).splitlines() for db in dbs: print db
c6275896adb429fad7f8bebb74ce932739ecfb63
edx_shopify/views.py
edx_shopify/views.py
import copy, json from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .utils import hmac_is_valid from .models import Order from .tasks import ProcessOrder @csrf_exempt @require_POST def ...
import copy, json from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .utils import hmac_is_valid from .models import Order from .tasks import ProcessOrder @csrf_exempt @require_POST def ...
Use get_or_create correctly on Order
Use get_or_create correctly on Order
Python
agpl-3.0
hastexo/edx-shopify,fghaas/edx-shopify
--- +++ @@ -30,9 +30,12 @@ # Record order order, created = Order.objects.get_or_create( id=data['id'], - email=data['customer']['email'], - first_name=data['customer']['first_name'], - last_name=data['customer']['last_name']) + defaults={ + 'email': data['cust...
cfdbe06da6e35f2cb166374cf249d51f18e1224e
pryvate/blueprints/packages/packages.py
pryvate/blueprints/packages/packages.py
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', ...
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', ...
Return a 404 if the package was not found
Return a 404 if the package was not found
Python
mit
Dinoshauer/pryvate,Dinoshauer/pryvate
--- +++ @@ -21,3 +21,4 @@ mimetype = magic.from_file(filepath, mime=True) contents = egg.read() return make_response(contents, 200, {'Content-Type': mimetype}) + return make_response('Package not found', 404)
e1b0222c8a3ed39bf76af10484a94aa4cfe5adc8
googlesearch/templatetags/search_tags.py
googlesearch/templatetags/search_tags.py
import math from django import template from ..conf import settings register = template.Library() @register.inclusion_tag('googlesearch/_pagination.html', takes_context=True) def show_pagination(context, pages_to_show=10): max_pages = int(math.ceil(context['total_results'] / setting...
import math from django import template from ..conf import settings register = template.Library() @register.inclusion_tag('googlesearch/_pagination.html', takes_context=True) def show_pagination(context, pages_to_show=10): max_pages = int(math.ceil(context['total_results'] / setting...
Remove last_page not needed anymore.
Remove last_page not needed anymore.
Python
mit
hzdg/django-google-search,hzdg/django-google-search
--- +++ @@ -10,9 +10,6 @@ max_pages = int(math.ceil(context['total_results'] / settings.GOOGLE_SEARCH_RESULTS_PER_PAGE)) - last_page = int(context['current_page']) + pages_to_show - 1 - last_page = max_pages if last_page > max_pages else last_page - prev_page = context...
451a435ca051305517c79216d7ab9441939f4004
src/amr.py
src/amr.py
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = df.grad(u) costheta = df.dot(m, E) ...
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = -df.grad(u) costheta ...
Add sigma0 and alpha AMR parameters to the function.
Add sigma0 and alpha AMR parameters to the function.
Python
bsd-2-clause
fangohr/fenics-anisotropic-magneto-resistance
--- +++ @@ -1,6 +1,6 @@ import dolfin as df -def amr(mesh, m, DirichletBoundary, g, d): +def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition @@ -9,9 +9,9 @@ # Define variational problem u = df.Function(V) v = df.TestFu...
704e1457480d6baa8db7fff245d733303f8a17f5
gpytorch/kernels/white_noise_kernel.py
gpytorch/kernels/white_noise_kernel.py
import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): super(WhiteNoiseKernel, self).__init__() self.register_buffer("variances", variances) def forward(self, x1, x2): if self.traini...
import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): super(WhiteNoiseKernel, self).__init__() self.register_buffer("variances", variances) def forward(self, x1, x2): if self.traini...
Fix ZeroLazyVariable size returned by white noise kernel
Fix ZeroLazyVariable size returned by white noise kernel
Python
mit
jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch
--- +++ @@ -14,4 +14,4 @@ elif x1.size(-2) == x2.size(-2) and x1.size(-2) == self.variances.size(-1) and torch.equal(x1, x2): return DiagLazyVariable(self.variances.unsqueeze(0)) else: - return ZeroLazyVariable(x1.size(-3), x1.size(-2), x1.size(-1), device=x1.device) + ...
9a2169e38374429db7792537e2c4c1a78281200d
src/application/models.py
src/application/models.py
""" models.py App Engine datastore models """ from google.appengine.ext import ndb class ExampleModel(ndb.Model): """Example Model""" example_name = ndb.StringProperty(required=True) example_description = ndb.TextProperty(required=True) added_by = ndb.UserProperty() timestamp = ndb.DateTimePro...
""" models.py App Engine datastore models """ from google.appengine.ext import ndb class SchoolModel(ndb.Model): """"Basic Model"""" name = ndb.StringProperty(required=True) place = ndb.StringProperty(required=True) added_by = ndb.UserProperty() timestamp = ndb.DateTimeProperty(auto_now_add=Tru...
Add Docstrings and fix basic model
Add Docstrings and fix basic model
Python
mit
shashisp/reWrite-SITA,shashisp/reWrite-SITA,shashisp/reWrite-SITA
--- +++ @@ -8,18 +8,10 @@ from google.appengine.ext import ndb - -class ExampleModel(ndb.Model): - """Example Model""" - example_name = ndb.StringProperty(required=True) - example_description = ndb.TextProperty(required=True) +class SchoolModel(ndb.Model): + """"Basic Model"""" + name = ndb.String...
08ae805a943be3cdd5e92c050512374180b9ae35
indra/sources/geneways/geneways_api.py
indra/sources/geneways/geneways_api.py
""" This module provides a simplified API for invoking the Geneways input processor , which converts extracted information collected with Geneways into INDRA statements. See publication: Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ...
""" This module provides a simplified API for invoking the Geneways input processor , which converts extracted information collected with Geneways into INDRA statements. See publication: Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ...
Update API to look at one folder and return processor
Update API to look at one folder and return processor
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy
--- +++ @@ -12,28 +12,32 @@ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str - +import os from indra.sources.geneways.processor import GenewaysProcessor -def process_geneways(search_path=None): + +# Path to the INDRA data folder +path_this = os.path.dirnam...
69aa0ec7c79139167e7a2adce1e0effac960755a
flaskrst/__init__.py
flaskrst/__init__.py
# -*- coding: utf-8 -*- """ flask-rstblog ~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from flask import Flask, url_for app = Flask("flaskrst") @app.context_processor def inject_navigation(): navigation = [] for item in app.config.get...
# -*- coding: utf-8 -*- """ flask-rstblog ~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from flask import Flask, url_for app = Flask("flaskrst") @app.context_processor def inject_navigation(): navigation = [] for item in app.config.get...
Rename navigation config key name to label and add support for links to external sites over the url key name
Rename navigation config key name to label and add support for links to external sites over the url key name
Python
bsd-3-clause
jarus/flask-rst
--- +++ @@ -15,11 +15,14 @@ def inject_navigation(): navigation = [] for item in app.config.get('NAVIGATION', []): - kwargs = item.copy() - del kwargs['route'] - del kwargs['name'] + if item.has_key('route') and item.has_key('label'): + kwargs = item.copy() + ...
5c21f105057f8c5d10721b6de2c5cf698668fd3c
src/events/admin.py
src/events/admin.py
from django.contrib import admin from .models import SponsoredEvent @admin.register(SponsoredEvent) class SponsoredEventAdmin(admin.ModelAdmin): fields = [ 'host', 'title', 'slug', 'category', 'language', 'abstract', 'python_level', 'detailed_description', 'recording_policy', 'slide_link'...
from django.contrib import admin from .models import SponsoredEvent @admin.register(SponsoredEvent) class SponsoredEventAdmin(admin.ModelAdmin): fields = [ 'host', 'title', 'slug', 'category', 'language', 'abstract', 'python_level', 'detailed_description', 'recording_policy', 'slide_link'...
Make host field raw ID instead of select
Make host field raw ID instead of select
Python
mit
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
--- +++ @@ -14,3 +14,4 @@ list_display = ['title', 'category', 'language', 'python_level'] list_filter = ['category', 'language', 'python_level'] prepopulated_fields = {'slug': ['title']} + raw_id_fields = ['host']
74e8bf6574ce3658e1b276479c3b6ebec36844a4
kuhn_poker/agents/kuhn_random_agent.py
kuhn_poker/agents/kuhn_random_agent.py
import random import sys import acpc_python_client as acpc class KuhnRandomAgent(acpc.Agent): def __init__(self): super().__init__() def on_game_start(self, game): pass def on_next_turn(self, game, match_state, is_acting_player): if not is_acting_player: return ...
import random import sys import acpc_python_client as acpc class KuhnRandomAgent(acpc.Agent): def __init__(self): super().__init__() def on_game_start(self, game): pass def on_next_turn(self, game, match_state, is_acting_player): if not is_acting_player: return ...
Remove unnecessary log from random agent
Remove unnecessary log from random agent
Python
mit
JakubPetriska/poker-cfr,JakubPetriska/poker-cfr
--- +++ @@ -14,12 +14,6 @@ def on_next_turn(self, game, match_state, is_acting_player): if not is_acting_player: return - - print('%s: %s %s' % ( - match_state.get_viewing_player(), - self.is_fold_valid(), - self.is_raise_valid() - )) ...
fe76abc03f7152f318712e1a233aad42f2e9870a
jsonfield/widgets.py
jsonfield/widgets.py
from django import forms from django.utils import simplejson as json import staticmedia class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) ...
from django import forms from django.utils import simplejson as json from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, ind...
Use staticfiles instead of staticmedia
Use staticfiles instead of staticmedia
Python
bsd-3-clause
SideStudios/django-jsonfield,chrismeyersfsu/django-jsonfield
--- +++ @@ -1,6 +1,6 @@ from django import forms from django.utils import simplejson as json -import staticmedia +from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): @@ -17,8 +17,8 @@ class JSONTableWidget(JSONWidget): class Media: js ...
c13208dcc4fe1715db10d86e4dfd584c18f396fa
sympy/calculus/singularities.py
sympy/calculus/singularities.py
from sympy.solvers import solve from sympy.simplify import simplify def singularities(expr, sym): """ Finds singularities for a function. Currently supported functions are: - univariate real rational functions Examples ======== >>> from sympy.calculus.singularities import singularities ...
from sympy.solvers import solve from sympy.solvers.solveset import solveset from sympy.simplify import simplify def singularities(expr, sym): """ Finds singularities for a function. Currently supported functions are: - univariate real rational functions Examples ======== >>> from sympy.c...
Replace solve with solveset in sympy.calculus
Replace solve with solveset in sympy.calculus
Python
bsd-3-clause
skidzo/sympy,chaffra/sympy,pandeyadarsh/sympy,VaibhavAgarwalVA/sympy,abhiii5459/sympy,jbbskinny/sympy,aktech/sympy,lindsayad/sympy,kevalds51/sympy,Titan-C/sympy,hargup/sympy,yukoba/sympy,farhaanbukhsh/sympy,moble/sympy,emon10005/sympy,bukzor/sympy,sahmed95/sympy,mafiya69/sympy,kaushik94/sympy,VaibhavAgarwalVA/sympy,jbb...
--- +++ @@ -1,4 +1,5 @@ from sympy.solvers import solve +from sympy.solvers.solveset import solveset from sympy.simplify import simplify @@ -30,4 +31,4 @@ " non rational functions are not yet" " implemented") else: - return tuple(...
b71f3c726aa6bde4ab0e2b471c5cb9064abfb3fa
apps/webdriver_testing/api_v2/test_user_resources.py
apps/webdriver_testing/api_v2/test_user_resources.py
from apps.webdriver_testing.webdriver_base import WebdriverTestCase from apps.webdriver_testing import data_helpers from apps.webdriver_testing.data_factories import UserFactory class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase): """TestSuite for uploading subtitles via the api. """ def setUp(s...
from apps.webdriver_testing.webdriver_base import WebdriverTestCase from apps.webdriver_testing import data_helpers from apps.webdriver_testing.data_factories import UserFactory class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase): """TestSuite for uploading subtitles via the api. """ def setUp(s...
Fix webdriver user creation bug
Fix webdriver user creation bug
Python
agpl-3.0
eloquence/unisubs,ofer43211/unisubs,eloquence/unisubs,eloquence/unisubs,pculture/unisubs,norayr/unisubs,pculture/unisubs,norayr/unisubs,wevoice/wesub,pculture/unisubs,ujdhesa/unisubs,ofer43211/unisubs,ujdhesa/unisubs,pculture/unisubs,ReachingOut/unisubs,ofer43211/unisubs,wevoice/wesub,ujdhesa/unisubs,wevoice/wesub,Reac...
--- +++ @@ -17,7 +17,7 @@ POST /api2/partners/users/ """ - create_url = 'users' + create_url = 'users/' create_data = {'username': None, 'email': None, 'password': 'password', @@ -42,10 +42,4 @@ 'last_n...
fff33f238d840b89350d50e2349af8f60f298a2a
openprescribing/openprescribing/settings/test.py
openprescribing/openprescribing/settings/test.py
from __future__ import absolute_import import os from .local import * EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' if 'TRAVIS' not in os.environ: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'file': { 'level': 'DE...
from __future__ import absolute_import import os from .base import * DEBUG = True TEMPLATES[0]['OPTIONS']['debug'] = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': utils.get_env_setting('DB_NAME'), 'USER': utils.get_env_setting('DB_USER'), ...
Test settings which don't depend on local ones
Test settings which don't depend on local ones By overriding local settings we were cargo-culting things we didn't want. Prefer explicit settings (still using the `base.py` environment as a starting point)
Python
mit
annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc
--- +++ @@ -1,7 +1,31 @@ from __future__ import absolute_import import os -from .local import * +from .base import * + +DEBUG = True +TEMPLATES[0]['OPTIONS']['debug'] = DEBUG +DATABASES = { + 'default': { + 'ENGINE': 'django.contrib.gis.db.backends.postgis', + 'NAME': utils.get_env_setting('DB_NA...
236ad637e05ab8ff48b7c169dd54228e48470e1b
mediacloud/mediawords/util/test_sql.py
mediacloud/mediawords/util/test_sql.py
from mediawords.util.sql import * import time import datetime def test_get_sql_date_from_epoch(): assert get_sql_date_from_epoch(int(time.time())) == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') def test_sql_now(): assert sql_now() == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') def...
from mediawords.util.sql import * import time import datetime def test_get_sql_date_from_epoch(): assert get_sql_date_from_epoch(int(time.time())) == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') assert get_sql_date_from_epoch(0) == datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S') ...
Add some more unit tests for get_sql_date_from_epoch()
Add some more unit tests for get_sql_date_from_epoch()
Python
agpl-3.0
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
--- +++ @@ -6,6 +6,9 @@ def test_get_sql_date_from_epoch(): assert get_sql_date_from_epoch(int(time.time())) == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') + assert get_sql_date_from_epoch(0) == datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S') + # noinspection PyTypeChecker +...
d2991a6385be74debf71eb8404e362c6027e6d50
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 assert host.comma...
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0
Remove redundant xorg command test
Remove redundant xorg command test
Python
mit
nephelaiio/ansible-role-i3,nephelaiio/ansible-role-i3
--- +++ @@ -9,4 +9,3 @@ def test_command(host): assert host.command('i3 --version').rc == 0 assert host.command('pactl --version').rc == 0 - assert host.command('Xorg -version').rc == 0
50e62304276c1daa2d0ef03b094f4c444ff995e1
openassessment/workflow/serializers.py
openassessment/workflow/serializers.py
""" Serializers are created to ensure models do not have to be accessed outside the scope of the ORA2 APIs. """ from rest_framework import serializers from openassessment.workflow.models import AssessmentWorkflow, AssessmentWorkflowCancellation class AssessmentWorkflowSerializer(serializers.ModelSerializer): scor...
""" Serializers are created to ensure models do not have to be accessed outside the scope of the ORA2 APIs. """ from rest_framework import serializers from openassessment.workflow.models import AssessmentWorkflow, AssessmentWorkflowCancellation class AssessmentWorkflowSerializer(serializers.ModelSerializer): scor...
Fix display of page after score override.
Fix display of page after score override.
Python
agpl-3.0
Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2
--- +++ @@ -8,7 +8,7 @@ class AssessmentWorkflowSerializer(serializers.ModelSerializer): score = serializers.ReadOnlyField(required=False) - override_score = serializers.Field(required=False) + override_score = serializers.ReadOnlyField(required=False) class Meta: model = AssessmentWorkf...
325902c169424ec76307efa71a2e4885180e5cbb
tests/integration/shell/call.py
tests/integration/shell/call.py
# -*- coding: utf-8 -*- """ tests.integration.shell.call ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)` :license: Apache 2.0, see LICENSE for more details. """ import sys # Import salt libs from saltunittest import TestLoader, TextTestRunner i...
# -*- coding: utf-8 -*- """ tests.integration.shell.call ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)` :license: Apache 2.0, see LICENSE for more details. """ import sys # Import salt libs from saltunittest import TestLoader, TextTestRunner, ...
Test to make sure we're outputting kwargs on the user.delete documentation.
Test to make sure we're outputting kwargs on the user.delete documentation.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -10,7 +10,7 @@ import sys # Import salt libs -from saltunittest import TestLoader, TextTestRunner +from saltunittest import TestLoader, TextTestRunner, skipIf import integration from integration import TestDaemon @@ -29,6 +29,15 @@ out = self.run_call('--text-out test.fib 3') self...
981bac39056584ec9c16e5a8d0f7a972d7365a3f
tests/test_module_dispatcher.py
tests/test_module_dispatcher.py
import pytest from conftest import (POSITIVE_HOST_PATTERNS, NEGATIVE_HOST_PATTERNS) @pytest.mark.parametrize("host_pattern, num_hosts", POSITIVE_HOST_PATTERNS) def test_len(host_pattern, num_hosts, hosts): assert len(getattr(hosts, host_pattern)) == num_hosts @pytest.mark.parametrize("host_pattern, num_hosts", ...
import pytest from conftest import (POSITIVE_HOST_PATTERNS, NEGATIVE_HOST_PATTERNS) @pytest.mark.parametrize("host_pattern, num_hosts", POSITIVE_HOST_PATTERNS) def test_len(host_pattern, num_hosts, hosts): assert len(getattr(hosts, host_pattern)) == num_hosts @pytest.mark.parametrize("host_pattern, num_hosts", ...
Use more prefered exc_info inspection technique
Use more prefered exc_info inspection technique
Python
mit
jlaska/pytest-ansible
--- +++ @@ -22,12 +22,6 @@ def test_ansible_module_error(hosts): '''Verify that AnsibleModuleError is raised when no such module exists.''' from pytest_ansible.errors import AnsibleModuleError - with pytest.raises(AnsibleModuleError): - # The following allows us to introspect the exception object...
9a1c34c7b3ff4de9dda7d8dbf6fb3234a40dc0b1
src/sas/sasview/__init__.py
src/sas/sasview/__init__.py
from distutils.version import StrictVersion __version__ = "5.0.5a1" StrictVersion(__version__) __DOI__ = "Zenodo, DOI:10.5281/zenodo.4467703" __release_date__ = "2021" __build__ = "GIT_COMMIT"
from distutils.version import StrictVersion __version__ = "5.0.5-alpha.1" StrictVersion(__version__) __DOI__ = "Zenodo, DOI:10.5281/zenodo.4467703" __release_date__ = "2021" __build__ = "GIT_COMMIT"
Revert the version string fix, so the proper fix can be merged without conflict
Revert the version string fix, so the proper fix can be merged without conflict
Python
bsd-3-clause
SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview
--- +++ @@ -1,5 +1,5 @@ from distutils.version import StrictVersion -__version__ = "5.0.5a1" +__version__ = "5.0.5-alpha.1" StrictVersion(__version__) __DOI__ = "Zenodo, DOI:10.5281/zenodo.4467703" __release_date__ = "2021"
ba564c7e2cacc8609d52f03e501786be3c7c8f44
tests/config.py
tests/config.py
import sys sys.path.append("../ideascaly") from ideascaly.auth import AuthNonSSO from ideascaly.api import API import ConfigParser import unittest config = ConfigParser.ConfigParser() config.read('config') class IdeascalyTestCase(unittest.TestCase): def setUp(self): self.auth = create_auth() s...
import sys sys.path.append('../ideascaly') from ideascaly.auth import AuthNonSSO from ideascaly.api import API import unittest testing_community = 'fiveheads.ideascale.com' testing_token = '5b3326f8-50a5-419d-8f02-eef6a42fd61a' class IdeascalyTestCase(unittest.TestCase): def setUp(self): self.auth = c...
Change the way used to read the testing information
Change the way used to read the testing information
Python
mit
joausaga/ideascaly
--- +++ @@ -1,14 +1,13 @@ import sys -sys.path.append("../ideascaly") +sys.path.append('../ideascaly') from ideascaly.auth import AuthNonSSO from ideascaly.api import API -import ConfigParser import unittest -config = ConfigParser.ConfigParser() -config.read('config') +testing_community = 'fiveheads.ideasca...
d07109e07e4d9fab488dfbbcf56fdfe18baa56ab
lib/python/plow/test/test_static.py
lib/python/plow/test/test_static.py
import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.findJobs() if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests) unittest.TextTestRunner(verbosity=2).run(suite)
import unittest import manifest import plow class StaticModuletests(unittest.TestCase): def testFindJobs(self): plow.getJobs() def testGetGroupedJobs(self): result = [ {"id": 1, "parent":0, "name": "High"}, {"id": 2, "parent":1, "name": "Foo"} ] for...
Set the column count value based on size of header list.
Set the column count value based on size of header list.
Python
apache-2.0
Br3nda/plow,Br3nda/plow,chadmv/plow,Br3nda/plow,chadmv/plow,chadmv/plow,Br3nda/plow,Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow
--- +++ @@ -6,7 +6,20 @@ class StaticModuletests(unittest.TestCase): def testFindJobs(self): - plow.findJobs() + plow.getJobs() + + + def testGetGroupedJobs(self): + + result = [ + {"id": 1, "parent":0, "name": "High"}, + {"id": 2, "parent":1, "name": "Foo"} + ...
189c7a7c982739cd7a3026e34a9969ea9278a12b
api/data/src/lib/middleware.py
api/data/src/lib/middleware.py
import os import re class SetBaseEnv(object): """ Figure out which port we are on if we are running and set it. So that the links will be correct. Not sure if we need this always... """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request...
import os class SetBaseEnv(object): """ Figure out which port we are on if we are running and set it. So that the links will be correct. Not sure if we need this always... """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): ...
Fix so we can do :5000 queries from api container
Fix so we can do :5000 queries from api container
Python
mit
xeor/hohu,xeor/hohu,xeor/hohu,xeor/hohu
--- +++ @@ -1,5 +1,4 @@ import os -import re class SetBaseEnv(object): @@ -14,7 +13,7 @@ self.get_response = get_response def __call__(self, request): - if os.environ.get('HTTP_PORT'): + if os.environ.get('HTTP_PORT') and ':' not in request.META['HTTP_HOST']: request.M...
e0c70b2b20349b8f1c0f6df8cc641c3267a63a06
crypto.py
crypto.py
""" Sending a message: Encrypt your plaintext with encrypt_message Your id will serve as your public key Reading a message Use decrypt_message and validate contents """ from Crypto.PublicKey import RSA # Generates and writes byte string with object of RSA key object def create_key(): key = RSA.genera...
""" Sending a message: Encrypt your plaintext with encrypt_message Your id will serve as your public key Reading a message Use decrypt_message and validate contents """ from Crypto.PublicKey import RSA # Generates and writes byte string with object of RSA key object def create_key(): key = RSA.genera...
Use 'with ... as ...' for file opening. Standardize variable names.
Use 'with ... as ...' for file opening. Standardize variable names.
Python
mit
Tribler/decentral-market
--- +++ @@ -12,16 +12,15 @@ # Generates and writes byte string with object of RSA key object def create_key(): key = RSA.generate(2048) - f = open('key.pem', 'w') - f.write(key.exportKey('PEM')) - f.close() + with open('key.pem', 'w') as f: + f.write(key.exportKey('PEM')) # Reads an exp...
ca0b10484ca92709be4b30b2aab7079a2f4a2fe1
tracker.py
tracker.py
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy #Get Hashtag to track argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at #W...
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy #Get String to track on argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at ...
Change comments to make sense
Change comments to make sense
Python
mit
tim-thompson/TweetTimeTracker
--- +++ @@ -4,7 +4,7 @@ from tweepy import Stream import tweepy -#Get Hashtag to track +#Get String to track on argTag = sys.argv[1] #Class for listening to all tweets
3b568b0343e1cbf9256caa181c672449faf01ddc
pavement.py
pavement.py
from paver.easy import * import paver.doctools from paver.setuputils import setup @task def dumpdb(): print "Downloading data from App Engine" sh("python2.5 ../../google_appengine/bulkloader.py --dump --app_id=zongo --email=alex.marandon@gmail.com --url=http://www.zongosound.com/remote_api --filename=data.csv"...
from paver.easy import * import paver.doctools from paver.setuputils import setup @task def dumpdb(): print "Downloading data from App Engine" sh("python2.5 ../../lib/google_appengine/bulkloader.py --dump --app_id=zongo --email=alex.marandon@gmail.com --url=http://www.zongosound.com/remote_api --filename=data....
Adjust path to GAE DSK
Adjust path to GAE DSK
Python
bsd-3-clause
amarandon/zongo-engine,amarandon/zongo-engine,amarandon/zongo-engine
--- +++ @@ -5,9 +5,9 @@ @task def dumpdb(): print "Downloading data from App Engine" - sh("python2.5 ../../google_appengine/bulkloader.py --dump --app_id=zongo --email=alex.marandon@gmail.com --url=http://www.zongosound.com/remote_api --filename=data.csv") + sh("python2.5 ../../lib/google_appengine/bulkl...
f75e245f461e57cc868ee5452c88aea92b6681bf
chainer/functions/parameter.py
chainer/functions/parameter.py
import numpy from chainer import function class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: array: Initial parameter array. """...
import numpy from chainer import function from chainer.utils import type_check class Parameter(function.Function): """Function that outputs its weight array. This is a parameterized function that takes no input and returns a variable holding a shallow copy of the parameter array. Args: arr...
Add typecheck to Parameter function
Add typecheck to Parameter function
Python
mit
t-abe/chainer,chainer/chainer,pfnet/chainer,jnishi/chainer,sou81821/chainer,ikasumi/chainer,tigerneil/chainer,delta2323/chainer,1986ks/chainer,chainer/chainer,yanweifu/chainer,ronekko/chainer,muupan/chainer,truongdq/chainer,chainer/chainer,muupan/chainer,okuta/chainer,jnishi/chainer,anaruse/chainer,hvy/chainer,cupy/cup...
--- +++ @@ -1,6 +1,7 @@ import numpy from chainer import function +from chainer.utils import type_check class Parameter(function.Function): @@ -21,6 +22,9 @@ self.W = array self.gW = numpy.empty_like(array) + def check_type_forward(self, in_types): + type_check.expect(in_types.s...
3cf9473bdf1714460478b4cd36a54b09b2a57173
lib/feedeater/validate.py
lib/feedeater/validate.py
"""Validate GTFS""" import os import mzgtfs.feed import mzgtfs.validation import task class FeedEaterValidate(task.FeedEaterTask): def run(self): # Validate feeds self.log("===== Feed: %s ====="%self.feedid) feed = self.registry.feed(self.feedid) filename = self.filename or os.path.join(self.workdi...
"""Validate GTFS""" import os import mzgtfs.feed import mzgtfs.validation import task class FeedEaterValidate(task.FeedEaterTask): def __init__(self, *args, **kwargs): super(FeedEaterValidate, self).__init__(*args, **kwargs) self.feedvalidator = kwargs.get('feedvalidator') def parser(self): parser =...
Add --feedvaldiator option to validator
Add --feedvaldiator option to validator
Python
mit
transitland/transitland-datastore,transitland/transitland-datastore,transitland/transitland-datastore,brechtvdv/transitland-datastore,brechtvdv/transitland-datastore,brechtvdv/transitland-datastore
--- +++ @@ -7,6 +7,18 @@ import task class FeedEaterValidate(task.FeedEaterTask): + def __init__(self, *args, **kwargs): + super(FeedEaterValidate, self).__init__(*args, **kwargs) + self.feedvalidator = kwargs.get('feedvalidator') + + def parser(self): + parser = super(FeedEaterValidate, self).parser()...
d1174017c6b282aa1d808b784ffde8a3d3190472
fabfile.py
fabfile.py
# -*- coding: utf-8 -*- """Generic Fabric-commands which should be usable without further configuration""" from fabric.api import * from os.path import dirname, split, abspath import os import sys import glob # Hacking our way into __init__.py of current package current_dir = dirname(abspath(__file__)) sys_path, pack...
# -*- coding: utf-8 -*- """Generic Fabric-commands which should be usable without further configuration""" from fabric.api import * from os.path import dirname, split, abspath import os import sys import glob # Hacking our way into __init__.py of current package current_dir = dirname(abspath(__file__)) sys_path, pack...
Allow running tasks even if roledefs.pickle is missing
Allow running tasks even if roledefs.pickle is missing Signed-off-by: Samuli Seppänen <be49b59234361de284476e9a2215fb6477f46673@openvpn.net>
Python
bsd-2-clause
mattock/fabric,mattock/fabric
--- +++ @@ -16,4 +16,8 @@ __package__ = package_name from . import * -env.roledefs = hostinfo.load_roledefs() +try: + open("roledefs.pickle") + env.roledefs = hostinfo.load_roledefs() +except IOError: + pass
3f394e47841b2d9e49554b21c67b06a46f99f25c
celery_app.py
celery_app.py
# -*- encoding: utf-8 -*- import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app...
# -*- encoding: utf-8 -*- import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app...
Add corporation task in celery data
Add corporation task in celery data
Python
bsd-3-clause
Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith
--- +++ @@ -35,4 +35,5 @@ 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', + 'lazyblacksmith.tasks.corporation.blueprints', ]
35c47f00f914935bd886c0b28ef618f451abc3b3
local_settings_example.py
local_settings_example.py
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', } } TIME_ZONE = 'Europe/Paris' LANGUAGE_CO...
import os PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '',...
Update settings example for tpl directories and other stuff
Update settings example for tpl directories and other stuff
Python
bsd-3-clause
RocknRoot/LIIT
--- +++ @@ -1,3 +1,6 @@ +import os + +PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG @@ -21,12 +24,12 @@ # Make this unique, and don't share it with anybody. SECRET_KEY = 'DO-SOMETHING-FOR-FRAKS-SAKE' -MEDIA_ROOT = '/usr/local/www/LIIT/media' +MEDIA_ROOT = os.path...
9d94a753c4824df210753996edaa9f7910df5fa8
tests/test_sample_app.py
tests/test_sample_app.py
import pytest @pytest.fixture def app(): import sys sys.path.append('.') from sample_app import create_app return create_app() @pytest.fixture def client(app): return app.test_client() def test_index(client): client.get('/')
import pytest @pytest.fixture def app(): import sys sys.path.append('.') from sample_app import create_app return create_app() @pytest.fixture def client(app): return app.test_client() def test_index(client): resp = client.get('/') assert resp.status == 200
Check for status code of 200 in sample app.
Check for status code of 200 in sample app.
Python
apache-2.0
JingZhou0404/flask-bootstrap,scorpiovn/flask-bootstrap,suvorom/flask-bootstrap,BeardedSteve/flask-bootstrap,ser/flask-bootstrap,suvorom/flask-bootstrap,victorbjorklund/flask-bootstrap,BeardedSteve/flask-bootstrap,ser/flask-bootstrap,livepy/flask-bootstrap,victorbjorklund/flask-bootstrap,dingocuster/flask-bootstrap,Coxi...
--- +++ @@ -17,4 +17,5 @@ def test_index(client): - client.get('/') + resp = client.get('/') + assert resp.status == 200
f48afc99a7e7aa076aa27b33deda824b5509bab2
test_qt_helpers_qt5.py
test_qt_helpers_qt5.py
from __future__ import absolute_import, division, print_function import os import sys import pytest from mock import MagicMock # At the moment it is not possible to have PyQt5 and PyQt4 installed # simultaneously because one requires the Qt4 libraries while the other # requires the Qt5 libraries class TestQT5(obj...
from __future__ import absolute_import, division, print_function import os import sys import pytest from mock import MagicMock # At the moment it is not possible to have PyQt5 and PyQt4 installed # simultaneously because one requires the Qt4 libraries while the other # requires the Qt5 libraries class TestQT5(obje...
Comment out problematic test for now
Comment out problematic test for now
Python
bsd-3-clause
glue-viz/qt-helpers
--- +++ @@ -8,13 +8,12 @@ # At the moment it is not possible to have PyQt5 and PyQt4 installed -# simultaneously because one requires the Qt4 libraries while the other +# simultaneously because one requires the Qt4 libraries while the other # requires the Qt5 libraries class TestQT5(object): def setu...
15fe43d0be3c665c09c898864bd2815b39fbc8a5
toolbox/config/common.py
toolbox/config/common.py
CURRENT_MIN_VERSION = 'v3.0' CURRENT_MAX_VERSION = 'v3.1' ACTIVE_REMOTE_BRANCHES = ['master', 'staging', 'demo'] DEFAULT_COMMAND_TIMEOUT = 60 * 60 CONTROLLER_PROTOCOL = 'controller' PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL} CRP_TYPES = {'docker', 'gce', 'static'}
CURRENT_MIN_VERSION = 'v3.0' CURRENT_MAX_VERSION = 'v3.1' # Once the Next platform supports challenge versions this can be extended. ACTIVE_REMOTE_BRANCHES = ['master'] DEFAULT_COMMAND_TIMEOUT = 60 * 60 CONTROLLER_PROTOCOL = 'controller' PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL} CRP_TYPES =...
Change v3 active branches to
Change v3 active branches to [master] Extend the list when it becomes relevant. The old platform shall use the legacy branch.
Python
apache-2.0
avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox
--- +++ @@ -1,7 +1,8 @@ CURRENT_MIN_VERSION = 'v3.0' CURRENT_MAX_VERSION = 'v3.1' -ACTIVE_REMOTE_BRANCHES = ['master', 'staging', 'demo'] +# Once the Next platform supports challenge versions this can be extended. +ACTIVE_REMOTE_BRANCHES = ['master'] DEFAULT_COMMAND_TIMEOUT = 60 * 60 CONTROLLER_PROTOCOL = 'co...
c2060336b7d20a774ce9e5ae93960ad680836274
modoboa_radicale/forms.py
modoboa_radicale/forms.py
"""Radicale extension forms.""" from django import forms from django.utils.translation import ugettext_lazy from modoboa.lib import form_utils from modoboa.parameters import forms as param_forms class ParametersForm(param_forms.AdminParametersForm): """Global parameters.""" app = "modoboa_radicale" se...
"""Radicale extension forms.""" from django import forms from django.utils.translation import ugettext_lazy from modoboa.lib import form_utils from modoboa.parameters import forms as param_forms class ParametersForm(param_forms.AdminParametersForm): """Global parameters.""" app = "modoboa_radicale" se...
Change form field to URLField.
Change form field to URLField. see #31
Python
mit
modoboa/modoboa-radicale,modoboa/modoboa-radicale,modoboa/modoboa-radicale
--- +++ @@ -16,7 +16,7 @@ label=ugettext_lazy("Server settings") ) - server_location = forms.CharField( + server_location = forms.URLField( label=ugettext_lazy("Server URL"), help_text=ugettext_lazy( "The URL of your Radicale server. "
6bcc15b6d018560ebc368efcfc2c2c7d435c7dcc
strictify-coqdep.py
strictify-coqdep.py
#!/usr/bin/env python2 import sys, subprocess import re if __name__ == '__main__': p = subprocess.Popen(sys.argv[1:], stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() reg = re.compile(r'''Warning(: in file .*?,\s*required library .*? matches several files in path)''') if reg.search(stderr): ...
#!/usr/bin/env python3 import sys, subprocess import re if __name__ == '__main__': p = subprocess.Popen(sys.argv[1:], stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() stderr = stderr.decode('utf-8') reg = re.compile(r'''Warning(: in file .*?,\s*required library .*? matches several files in pa...
Switch from python2 to python3
Switch from python2 to python3 Closes #6
Python
mit
JasonGross/coq-scripts,JasonGross/coq-scripts
--- +++ @@ -1,10 +1,11 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 import sys, subprocess import re if __name__ == '__main__': p = subprocess.Popen(sys.argv[1:], stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() + stderr = stderr.decode('utf-8') reg = re.compile(r'''Warning(: in...
0415bc9e4a174b7cebb634a449473131fe16b3b2
bulbs/content/management/commands/reindex_content.py
bulbs/content/management/commands/reindex_content.py
from django.core.management.base import NoArgsCommand from bulbs.content.models import Content class Command(NoArgsCommand): help = 'Runs Content.index on all content.' def handle(self, **options): num_processed = 0 content_count = Content.objects.all().count() chunk_size = 10 ...
from django.core.management.base import NoArgsCommand from bulbs.content.models import Content class Command(NoArgsCommand): help = 'Runs Content.index on all content.' def handle(self, **options): num_processed = 0 content_count = Content.objects.all().count() chunk_size = 10 ...
Add ordering to queryset in reindex admin command
Add ordering to queryset in reindex admin command
Python
mit
theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs,theonion/django-bulbs
--- +++ @@ -10,7 +10,7 @@ content_count = Content.objects.all().count() chunk_size = 10 while num_processed < content_count: - for content in Content.objects.all()[num_processed:num_processed + chunk_size]: + for content in Content.objects.all().order_by('id')[num_proc...
8247d3c1b6a9720f14db1130e087293c57587b54
weather.py
weather.py
""" Implementation of the OpenWeatherMap API. """ __author__ = 'ajay@roopakalu.com (Ajay Roopakalu)' OPEN_WEATHER_MAP_URL = 'api.openweathermap.org/data/2.5' WEATHER_URL = '/weather' import requests import log logging = log.Log(__name__) def GetCurrentExternalTemperature(appid, latitude, longitude): params = { ...
""" Implementation of the OpenWeatherMap API. """ __author__ = 'ajay@roopakalu.com (Ajay Roopakalu)' OPEN_WEATHER_MAP_URL = 'http://api.openweathermap.org/data/2.5' WEATHER_URL = '/weather' import requests import log logging = log.Log(__name__) def GetCurrentExternalTemperature(appid, latitude, longitude): param...
Fix URL scheme for OpenWeatherMap.
Fix URL scheme for OpenWeatherMap.
Python
mit
jrupac/nest-wfh
--- +++ @@ -3,7 +3,7 @@ """ __author__ = 'ajay@roopakalu.com (Ajay Roopakalu)' -OPEN_WEATHER_MAP_URL = 'api.openweathermap.org/data/2.5' +OPEN_WEATHER_MAP_URL = 'http://api.openweathermap.org/data/2.5' WEATHER_URL = '/weather' import requests
a9a55f87abc0a26d41e3fa3091f2f2efad7a2543
autoencoder/encode.py
autoencoder/encode.py
import numpy as np from .network import autoencoder, get_encoder from .io import read_records, load_model def encode(input_file, output_file, log_dir): X = read_records(input_file) size = X.shape[1] model = load_model(log_dir) encoder = get_encoder(model) predictions = encoder.predict(X) np....
import numpy as np from .network import autoencoder, get_encoder from .io import read_records, load_model def encode(input_file, output_file, log_dir): X = read_records(input_file) size = X.shape[1] model = load_model(log_dir) assert model.input_shape[1] == size, \ 'Input size of data and...
Check input dimensions of pretrained model and input file
Check input dimensions of pretrained model and input file
Python
apache-2.0
theislab/dca,theislab/dca,theislab/dca
--- +++ @@ -9,6 +9,10 @@ size = X.shape[1] model = load_model(log_dir) + assert model.input_shape[1] == size, \ + 'Input size of data and pretrained model must be same' + + encoder = get_encoder(model) predictions = encoder.predict(X) np.savetxt(output_file, predictions)
68d7b3995c49abd8f7096f9498bdbddf6b696d81
back_office/models.py
back_office/models.py
from django.db import models from django.utils.translation import ugettext as _ from Django.contrib.auth.models import User FEMALE = 'F' MALE = 'M' class Teacher(models.Model): """ halaqat teachers informations """ GENDET_CHOICES = ( (MALE, _('Male')), (FEMALE, _('Female')), ) ...
from django.db import models from django.utils.translation import ugettext as _ from Django.contrib.auth.models import User FEMALE = 'F' MALE = 'M' class Teacher(models.Model): """ halaqat teachers informations """ GENDET_CHOICES = ( (MALE, _('Male')), (FEMALE, _('Female')), ) ...
Add enabled field to teacher model
Add enabled field to teacher model
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
--- +++ @@ -21,4 +21,21 @@ phone_number = models.CharField(max_length=15, verbose_name=_('Phone Number')) job_title = models.CharField(max_length=15, verbose_name=_('Title')) + enabled = models.BooleanField(default=True) user = models.OneToOneField(to=User, relat...
7bdd06f568856c010a4eacb1e70c262fa4c3388c
bin/trigger_upload.py
bin/trigger_upload.py
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. Useful for manually triggering Fedimg jobs. """ import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.s...
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. """ import logging import logging.config import multiprocessing.pool import sys import fedmsg import fedmsg.config import fedimg import fedimg.services from fedimg.services.ec2 import EC2Service, EC2ServiceExceptio...
Fix the manual upload trigger script
scripts: Fix the manual upload trigger script Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
--- +++ @@ -1,8 +1,6 @@ #!/bin/env python # -*- coding: utf8 -*- - -""" Triggers an upload process with the specified raw.xz URL. Useful for - manually triggering Fedimg jobs. """ +""" Triggers an upload process with the specified raw.xz URL. """ import logging import logging.config @@ -18,8 +16,8 @@ import...
b503a6e893d71b96b3737e567dde16f110db5fc7
src/prepare_turk_batch.py
src/prepare_turk_batch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for fname in os.listdir(args.input): if not fname.endswith('.j...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import os import sys import csv import json import html def do_command(args): assert os.path.exists(args.input) writer = csv.writer(args.output) writer.writerow(["document"]) for i, fname in enumerate(os.listdir(args.input)): if not fnam...
Prepare data with the new fiields and prompts
Prepare data with the new fiields and prompts
Python
mit
arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly
--- +++ @@ -15,11 +15,16 @@ writer = csv.writer(args.output) writer.writerow(["document"]) - for fname in os.listdir(args.input): + for i, fname in enumerate(os.listdir(args.input)): if not fname.endswith('.json'): continue with open(os.path.join(args.input, fname)) as f: ...
dfb79b9f148663617048a3c2a310b2a66a1c7103
marxbot.py
marxbot.py
from errbot import BotPlugin, botcmd, webhook class MarxBot(BotPlugin): """Your daily dose of Marx""" min_err_version = '1.6.0' @botcmd(split_args_with=None) def marx(self, message, args): return "what a guy"
from errbot import BotPlugin, botcmd, webhook import pytumblr class MarxBot(BotPlugin): """Your daily dose of Marx""" min_err_version = '1.6.0' tumblr_client = None def activate(self): super().activate() if self.config is None or self.config["consumer_key"] == "" or self.config["consu...
Use the Tumblr API to get Marx quotes
Use the Tumblr API to get Marx quotes
Python
mit
AbigailBuccaneer/err-dailymarx
--- +++ @@ -1,10 +1,36 @@ from errbot import BotPlugin, botcmd, webhook +import pytumblr class MarxBot(BotPlugin): """Your daily dose of Marx""" min_err_version = '1.6.0' + tumblr_client = None - @botcmd(split_args_with=None) + def activate(self): + super().activate() + if sel...
19354bd82a89383d795cdada8d6af78e8f12eed8
src/server/test_client.py
src/server/test_client.py
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so...
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so...
Update call method in test client
Update call method in test client
Python
mit
cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim
--- +++ @@ -30,8 +30,8 @@ caller = RemoteFunctionCaller(nw) try: - caller.setData("test", "success") - print(caller.getData("test", default="failish")) + print(caller.SharedClientDataStore__set("test", "success")) + print(caller.SharedClientDtaStore__get("test", default="failish")) except TimeoutErro...