commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
638b8be8a07262803c087e796e40a51858c08983
__init__.py
__init__.py
from . import LayerView def getMetaData(): return { "name": "LayerView", "type": "View" } def register(app): return LayerView.LayerView()
from . import LayerView def getMetaData(): return { 'type': 'view', 'plugin': { "name": "Layer View" }, 'view': { 'name': 'Layers' } } def register(app): return LayerView.LayerView()
Update plugin metadata to the new format
Update plugin metadata to the new format
Python
agpl-3.0
totalretribution/Cura,markwal/Cura,quillford/Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,senttech/Cura,bq/Ultimaker-Cura,ad1217/Cura,fieldOfView/Cura,fieldOfView/Cura,DeskboxBrazil/Cura,Curahelper/Cura,Curahelper/Cura,hmflash/Cura,bq/Ultimaker-Cura,hmflash/Cura,markwal/Cura,quillford/Cura,derekhe/Cura,totalretribution...
badba5070ac40a70de2be47b6d58afd0364ed7fe
staticassets/views.py
staticassets/views.py
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, en...
import mimetypes from django.http import HttpResponse, HttpResponseNotModified, Http404 from django.contrib.staticfiles.views import serve as staticfiles_serve from django.views.static import was_modified_since, http_date from staticassets import finder, settings def serve(request, path, **kwargs): mimetype, en...
Use correct argument for content type in serve view
Use correct argument for content type in serve view
Python
mit
davidelias/django-staticassets,davidelias/django-staticassets,davidelias/django-staticassets
d74e134ca63b7d3cd053d21168ca526a493999df
mysql.py
mysql.py
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Chec...
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(user = 'root', host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.c...
Use root user to connect
Use root user to connect
Python
mit
innogames/igcollect
297f42a2013428c2f6caefdf83735cc4a528e225
caching.py
caching.py
import os import cPickle as pickle try: DATA_DIR = os.path.dirname(os.path.realpath(__file__)) except: DATA_DIR = os.getcwd() cache_path = lambda name: os.path.join(DATA_DIR, '%s.cache' % name) def get_cache(name): return pickle.load(open(cache_path(name), 'r')) def save_cache(obj, name): pickle.dump(o...
import os import cPickle as pickle home_dir = os.path.expanduser('~') DATA_DIR = os.path.join(home_dir, '.tax_resolve') if not os.path.exists(DATA_DIR): try: os.mkdir(DATA_DIR) except: DATA_DIR = os.getcwd() cache_path = lambda name: os.path.join(DATA_DIR, '%s.cache' % name) def get_cache(name): ...
Use user's local application data directory instead of the module path.
Use user's local application data directory instead of the module path.
Python
mit
bendmorris/tax_resolve
310cebbe1f4a4d92c8f181d7e4de9cc4f75a14dc
indra/assemblers/__init__.py
indra/assemblers/__init__.py
try: from pysb_assembler import PysbAssembler except ImportError: pass try: from graph_assembler import GraphAssembler except ImportError: pass try: from sif_assembler import SifAssembler except ImportError: pass try: from cx_assembler import CxAssembler except ImportError: pass try: ...
try: from indra.assemblers.pysb_assembler import PysbAssembler except ImportError: pass try: from indra.assemblers.graph_assembler import GraphAssembler except ImportError: pass try: from indra.assemblers.sif_assembler import SifAssembler except ImportError: pass try: from indra.assemblers.c...
Update to absolute imports in assemblers
Update to absolute imports in assemblers
Python
bsd-2-clause
johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,jmuhlich/indra,pvtodorov/indra,sorgerlab/indra,jmuhlich/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,jmuhlich/ind...
d150db290a72590e0f7cf9dae485bf98901bb2c2
web_ui/helpers.py
web_ui/helpers.py
from web_ui import app from flask import session from datetime import datetime # For calculating scores epoch = datetime.utcfromtimestamp(0) epoch_seconds = lambda dt: (dt - epoch).total_seconds() - 1356048000 def score(star_object): import random return random.random() * 100 - random.random() * 10 def ge...
from web_ui import app from flask import session from datetime import datetime # For calculating scores epoch = datetime.utcfromtimestamp(0) epoch_seconds = lambda dt: (dt - epoch).total_seconds() - 1356048000 def score(star_object): import random return random.random() * 100 - random.random() * 10 def ge...
Add helper method for resetting user data
Add helper method for resetting user data
Python
apache-2.0
ciex/souma,ciex/souma,ciex/souma
7180aba7ce183e64ef12e4fc384408036c2fe901
product_template_tree_prices/__init__.py
product_template_tree_prices/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## from . import product # vim:expandtab:smartindent...
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop...
FIX produ template tree prices
FIX produ template tree prices
Python
agpl-3.0
ingadhoc/product,ingadhoc/product
186a72b91798b11d13ea7f2538141f620b0787a8
tests/test_metrics.py
tests/test_metrics.py
import json from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, [])...
from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def tes...
Add test for noop routes
Add test for noop routes
Python
apache-2.0
vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,GeorgeJahad/graphite-api,vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,alphapigger/graphite-api,raintank/graphite-api,hubrick/graphite-api,rackerlabs/graphite-api,Knewton/graphite-api,raintank/graphite-api,Knewton/graphite-api,bogus...
2410255e846c5fbd756ed97868299e1674c89467
flash_example.py
flash_example.py
from BlinkyTape import BlinkyTape bb = BlinkyTape('/dev/tty.usbmodemfa131') while True: for x in range(60): bb.sendPixel(10, 10, 10) bb.show() for x in range(60): bb.sendPixel(0, 0, 0) bb.show()
from BlinkyTape import BlinkyTape import time #bb = BlinkyTape('/dev/tty.usbmodemfa131') bb = BlinkyTape('COM8') while True: for x in range(60): bb.sendPixel(100, 100, 100) bb.show() time.sleep(.5) for x in range(60): bb.sendPixel(0, 0, 0) bb.show() time.sleep(.5)
Set it to flash black and white every second
Set it to flash black and white every second
Python
mit
Blinkinlabs/BlinkyTape_Python,jpsingleton/BlinkyTape_Python,railsagainstignorance/blinkytape
251a0d1b1df0fd857a86878ecb7e4c6bc26a93ef
paci/helpers/display_helper.py
paci/helpers/display_helper.py
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def print_table(entries): """Prints out a table""" print(tabulate(entries, tablefmt="plain")) def std_input(text, default): """...
Add function to just print a simple table
Add function to just print a simple table
Python
mit
tradebyte/paci,tradebyte/paci
bb768ef543469395ccbd0b2761442d9dcfa8e0c5
testanalyzer/analyze_repos.py
testanalyzer/analyze_repos.py
import pandas as pd import shutil import utils as u import validators from analyzer import Analyzer from git import Repo if __name__ == "__main__": repos = pd.read_pickle("data/test.pkl") for _, repo in repos.iterrows(): if not validators.url(repo["url"]): print("Error: Invalid URL.") ...
import pandas as pd import shutil import utils as u import validators from analyzer import Analyzer from git import Repo if __name__ == "__main__": repos = pd.read_pickle("data/repos.pkl") repos["code_lines"] = 0 repos["code_classes"] = 0 repos["code_functions"] = 0 repos["test_lines"] = 0 rep...
Update dataframe with counts and serialize
Update dataframe with counts and serialize
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
05d498cc1f216ba722ce887b212ac5e750fb0c8d
tests/test_player_creation.py
tests/test_player_creation.py
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': 'chapmang@dropshot.com'} app.post('/players', params) res = app.get('/players') assert res.status_int...
from webtest import TestApp import dropshot def test_create_player(): app = TestApp(dropshot.app) params = {'username': 'chapmang', 'password': 'deadparrot', 'email': 'chapmang@dropshot.com'} expected = {'count': 1, 'offset': 0, 'players': [ ...
Make player creation test check for valid response.
Make player creation test check for valid response.
Python
mit
dropshot/dropshot-server
fc904d8fd02cecfb2c3d69d6101caaab7b224e93
_bin/person_list_generator.py
_bin/person_list_generator.py
# Console outputs a person list import os import csv with open('tmp/person_list_input.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print """ - role: {} name: {}""".format(row[0], row[1])
# Console outputs a person list import os import csv with open('tmp/person_list_input.csv') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: stream = open('tmp/person_list_output.yml', 'a') stream.write( """ - role: {}\n name: {}\n""".format(row[0], row[1]) ) ...
Make person list generator output to file
Make person list generator output to file The console was going beyond the terminal history limit for 14-15
Python
mit
johnathan99j/history-project,johnathan99j/history-project,newtheatre/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project,johnathan99j/history-project,newtheatre/history-project
10b9d412c26b90bb86fe1abd04c3fe0f86826104
pelicanconf_with_pagination.py
pelicanconf_with_pagination.py
from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
import sys # Hack for Travis, where local imports don't work. if '' not in sys.path: sys.path.insert(0, '') from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
Fix Python import path on Travis.
Fix Python import path on Travis.
Python
apache-2.0
dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog,dhermes/bossylobster-blog
c6ecf6160664bc61cf6dc213af1f2fe3fd6a3617
editorsnotes/djotero/models.py
editorsnotes/djotero/models.py
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField() zotero_data = models.TextField(blank=True) date_information = models.TextF...
from django.db import models from editorsnotes.main.models import Document import utils import json class ZoteroLink(models.Model): doc = models.OneToOneField(Document, related_name='_zotero_link') zotero_url = models.URLField(blank=True) zotero_data = models.TextField() date_information = models.TextF...
Allow blank zotero url reference, but require zotero json data
Allow blank zotero url reference, but require zotero json data
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
9fda3df6ae1f31af139c03eaf8b385746816f3b4
spec/helper.py
spec/helper.py
from pygametemplate import Game from example_view import ExampleView class TestGame(Game): """An altered Game class for testing purposes.""" def __init__(self, StartingView, resolution): super(TestGame, self).__init__(StartingView, resolution) def log(self, *error_message): """Altered log...
from pygametemplate import Game from example_view import ExampleView class TestGame(Game): """An altered Game class for testing purposes.""" def __init__(self, StartingView, resolution): super(TestGame, self).__init__(StartingView, resolution) game = TestGame(ExampleView, (1280, 720))
Remove TestGame.log() method as log() isn't a method of Game anymore
Remove TestGame.log() method as log() isn't a method of Game anymore
Python
mit
AndyDeany/pygame-template
36b8ec51dc6e1caca90db41d83d4dc21d70005a5
app/task.py
app/task.py
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. """ class Task(Document): ...
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField, ValidationError import datetime, enum, Exception from app import logger class Priority(enum.IntEnum): """ This defines the priority levels a Task can have. """ LOW = 0, MIDDLE = 1, HIGH =...
Add a Status enum and documentation
Add a Status enum and documentation
Python
mit
Zillolo/lazy-todo
acf3819d433f3ebc3d3eed17c61f2542f7429f8e
trimesh/resources/__init__.py
trimesh/resources/__init__.py
import os import inspect # find the current absolute path using inspect _pwd = os.path.dirname( os.path.abspath( inspect.getfile( inspect.currentframe()))) def get_resource(name, decode=True): """ Get a resource from the trimesh/resources folder. Parameters ------------- ...
import os # find the current absolute path to this directory _pwd = os.path.dirname(__file__) def get_resource(name, decode=True): """ Get a resource from the trimesh/resources folder. Parameters ------------- name : str File path relative to `trimesh/resources` decode : bool Wh...
Use __file__ instead of inspect, for compatibility with frozen environments
RF: Use __file__ instead of inspect, for compatibility with frozen environments
Python
mit
mikedh/trimesh,mikedh/trimesh,dajusc/trimesh,mikedh/trimesh,mikedh/trimesh,dajusc/trimesh
83dabc9fc1142e1575843d3a68c6241185543936
fabtastic/db/__init__.py
fabtastic/db/__init__.py
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: raise NotImplementedError("Fabtastic: DB engine '%s' is not supported" % db_engine)
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine)
Make the warning for SQLite not being supported a print instead of an exception.
Make the warning for SQLite not being supported a print instead of an exception.
Python
bsd-3-clause
duointeractive/django-fabtastic
208f90497c7a6867f9aeece84b1161926ca1627b
nethud/nh_client.py
nethud/nh_client.py
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): data = '{"register": {"...
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): self.send_message('auth...
Simplify nethack protocol to a single method.
Simplify nethack protocol to a single method.
Python
mit
ryansb/netHUD
881e693d16d12109c3ececffda61336b020c172a
portable_mds/tests/conftest.py
portable_mds/tests/conftest.py
import os import tempfile import shutil import tzlocal import pytest from ..mongoquery.mds import MDS @pytest.fixture(params=[1], scope='function') def mds_all(request): '''Provide a function level scoped FileStore instance talking to temporary database on localhost:27017 with both v0 and v1. ''' ver...
import os import tempfile import shutil import tzlocal import pytest import portable_mds.mongoquery.mds import portable_mds.sqlite.mds variations = [portable_mds.mongoquery.mds, portable_mds.sqlite.mds] @pytest.fixture(params=variations, scope='function') def mds_all(request): '''Provide a function ...
Test sqlite and mongoquery variations.
TST: Test sqlite and mongoquery variations.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
bd5c215c1c481f3811753412bca6b509bb00591a
me_api/app.py
me_api/app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .cache import cache def _register_module(app, module): if module == 'douban': from .middleware import douban app.register_blueprint(...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from werkzeug.utils import import_string from me_api.middleware.me import me from me_api.cache import cache middlewares = { 'douban': 'me_api.middleware.douban:douban_api', 'githu...
Improve the way that import middlewares
Improve the way that import middlewares
Python
mit
lord63/me-api
af6f4868f4329fec75e43fe0cdcd1a7665c5238a
contentcuration/manage.py
contentcuration/manage.py
#!/usr/bin/env python import os import sys # Attach Python Cloud Debugger if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from dj...
#!/usr/bin/env python import os import sys if __name__ == "__main__": #import warnings #warnings.filterwarnings('ignore', message=r'Module .*? is being added to sys\.path', append=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings") from django.core.management import exe...
Remove comment on attaching cloud debugger
Remove comment on attaching cloud debugger
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
948b9987afa95d7a69bd61f3d8f9fea822323b01
wagtaildraftail/draft_text.py
wagtaildraftail/draft_text.py
from __future__ import absolute_import, unicode_literals import json from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(self, value, **kwargs): super(DraftText, self)....
from __future__ import absolute_import, unicode_literals import json from django.utils.functional import cached_property from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(se...
Implement equality check for DraftText nodes
Implement equality check for DraftText nodes Compare the (cached) rendered html of a node
Python
mit
gasman/wagtaildraftail,gasman/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail
5c851ee3d333518829ce26bfc06fd1038e70651c
corehq/util/decorators.py
corehq/util/decorators.py
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception def handle_uncaught_exceptions(mail_admins=True): """Decorator to log uncaught exceptions and prevent them from bubbling up the call chain. """ def _outer(fn)...
from functools import wraps import logging from corehq.util.global_request import get_request from dimagi.utils.logging import notify_exception class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. https://docs.python.org/3/library/contextlib.html#...
Add util to temporarily alter log levels
Add util to temporarily alter log levels Also backport ContextDecorator from python 3. I saw this just the other day and it looks like an awesome pattern, and a much clearer way to write decorators.
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
a35d6f59d214741f554dde1363d2eac7addb04cb
crypto_enigma/__init__.py
crypto_enigma/__init__.py
#!/usr/bin/env python # encoding: utf8 """An Enigma machine simulator with rich textual display functionality.""" from ._version import __version__, __author__ #__all__ = ['machine', 'components'] from .components import * from .machine import *
#!/usr/bin/env python # encoding: utf8 """An Enigma machine simulator with rich textual display functionality. Limitations ~~~~~~~~~~~ Note that the correct display of some characters used to represent components (thin Naval rotors) assumes support for Unicode, while some aspects of the display of machine state depe...
Add limitations to package documentation
Add limitations to package documentation
Python
bsd-3-clause
orome/crypto-enigma-py
08291f3948108da15b9832c495fade04cf2e22c4
tests/tests.py
tests/tests.py
#!/usr/bin/env python3 from selenium import webdriver import unittest class AdminPageTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_visit_admin_page(self): # V...
#!/usr/bin/env python3 from selenium import webdriver import unittest class AdminPageTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_visit_admin_page(self): # V...
Add test to check title of index
Add test to check title of index
Python
mit
jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails
44520918dc0fad40f3afcfc2cdfde6f3208543cd
garden_lighting/MCP23017/raspberry.py
garden_lighting/MCP23017/raspberry.py
import time import os import wiringpi from garden_lighting.MCP23017.MCP23017 import MCP23017 class RaspberryMCP23017(MCP23017): def __init__(self, dev_addr, rst_pin=0xFF, i2cport=1): super().__init__(dev_addr, rst_pin, i2cport) def initDevice(self): ''' Does a reset to put all registe...
import time import wiringpi from garden_lighting.MCP23017.MCP23017 import MCP23017 class RaspberryMCP23017(MCP23017): def __init__(self, dev_addr, rst_pin=0xFF, i2cport=1): super().__init__(dev_addr, rst_pin, i2cport) def initDevice(self): ''' Does a reset to put all registers in init...
Use wiringPiSetupGpio, which required root. With wiringPiSetupSys some gpios stayed on low after boot.
Use wiringPiSetupGpio, which required root. With wiringPiSetupSys some gpios stayed on low after boot.
Python
mit
ammannbros/garden-lighting,ammannbros/garden-lighting,ammannbros/garden-lighting,ammannbros/garden-lighting
f30a923b881e908fa607e276de1d152d803248f1
pgpdump/__main__.py
pgpdump/__main__.py
import sys from . import BinaryData for filename in sys.argv[1:]: with open(filename) as infile: data = BinaryData(infile.read()) for packet in data.packets(): print hex(packet.key_id), packet.creation_date
import sys import cProfile from . import AsciiData, BinaryData def parsefile(name): with open(name) as infile: if name.endswith('.asc'): data = AsciiData(infile.read()) else: data = BinaryData(infile.read()) counter = 0 for packet in data.packets(): counter ...
Update main to run a profiler
Update main to run a profiler Signed-off-by: Dan McGee <a6e5737275ff1276377ee261739f3ee963671241@gmail.com>
Python
bsd-3-clause
toofishes/python-pgpdump
fddc7e09bcebf9b4875906ad03e58699237b13be
src/nodeconductor_assembly_waldur/packages/filters.py
src/nodeconductor_assembly_waldur/packages/filters.py
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = mod...
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = mod...
Enable filtering OpenStack package by tenant.
Enable filtering OpenStack package by tenant.
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
f5d4f543cc7265433bf6040335b2f6d592b52b91
lmod/__init__.py
lmod/__init__.py
from functools import partial from os import environ from subprocess import Popen, PIPE LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '') def module(command, *args): cmd = (environ['LMOD_CMD'], 'python', '--terse', command) result = Popen(cmd + args, stdout=PIPE, stderr=PIPE) if command in ('load', ...
import os # require by lmod output evaluated by exec() from functools import partial from os import environ from subprocess import Popen, PIPE LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '') def module(command, *args): cmd = (environ['LMOD_CMD'], 'python', '--terse', command) result = Popen(cmd + arg...
Add import os in lmod to fix regression
Add import os in lmod to fix regression
Python
mit
cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod
5d7f2f84600abcede94a0aaee087ef299cf740a6
farmers_api/farmers/views.py
farmers_api/farmers/views.py
from rest_framework import viewsets from .models import Farmer from .serializers import FarmerSerializer class FarmerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Farmer.objects.all() serializer_class = FarmerSerializer
from rest_framework import viewsets from .models import Farmer from .serializers import FarmerSerializer class FarmerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Farmer.objects.all() serializer_class = FarmerSerializer filter_fields = ('town',)
Add filter on the town field on the Farmer model
Add filter on the town field on the Farmer model
Python
bsd-2-clause
tm-kn/farmers-api
d4e03bfcbc6292d3a50237f95c9d67ba5d89a475
swampdragon/pubsub_providers/redis_sub_provider.py
swampdragon/pubsub_providers/redis_sub_provider.py
import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscr...
import json import tornadoredis.pubsub import tornadoredis from .base_provider import BaseProvider class RedisSubProvider(BaseProvider): def __init__(self): self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client()) def close(self, broadcaster): for channel in self._subscr...
Use usubscribe rather than popping the broadcaster
Use usubscribe rather than popping the broadcaster
Python
bsd-3-clause
sahlinet/swampdragon,boris-savic/swampdragon,michael-k/swampdragon,denizs/swampdragon,aexeagmbh/swampdragon,jonashagstedt/swampdragon,jonashagstedt/swampdragon,d9pouces/swampdragon,boris-savic/swampdragon,sahlinet/swampdragon,aexeagmbh/swampdragon,jonashagstedt/swampdragon,bastianh/swampdragon,boris-savic/swampdragon,m...
e30e5e9780cfe674a70856609ad6010056936263
picdump/webadapter.py
picdump/webadapter.py
import urllib.request class WebAdapter: def get(self, urllike): url = self.mk_url(urllike) try: res = urllib.request.urlopen(url) return res.read() except Exception as e: raise e def open(self, urllike): url = self.mk_url(urllike) t...
import requests class WebAdapter: def __init__(self): self.cookies = {} def get(self, urllike): res = requests.get(str(urllike), cookies=self.cookies) self.cookies = res.cookies return res.text
Use requests instead of urllib.request
Use requests instead of urllib.request
Python
mit
kanosaki/PicDump,kanosaki/PicDump
b38f465e512f9b7e79935c156c60ef56d6122387
aiohttp_middlewares/constants.py
aiohttp_middlewares/constants.py
""" ============================= aiohttp_middlewares.constants ============================= Collection of constants for ``aiohttp_middlewares`` project. """ #: Set of idempotent HTTP methods IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'}) #: Set of non-idempotent HTTP methods NON_IDEMPOTENT_ME...
""" ============================= aiohttp_middlewares.constants ============================= Collection of constants for ``aiohttp_middlewares`` project. """ #: Set of idempotent HTTP methods IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'}) #: Set of non-idempotent HTTP methods NON_IDEMPOTENT_ME...
Order HTTP methods in constant.
chore: Order HTTP methods in constant.
Python
bsd-3-clause
playpauseandstop/aiohttp-middlewares,playpauseandstop/aiohttp-middlewares
fbb2c05aef76c02094c13f5edeaecd9b7428ff11
alignak_backend/models/uipref.py
alignak_backend/models/uipref.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Resource information of host """ def get_name(): """ Get name of this resource :return: name of this resource :rtype: str """ return 'uipref' def get_schema(): """ Schema structure of this resource :return: schema dictionnary ...
Update UI preferences model (dict)
Update UI preferences model (dict)
Python
agpl-3.0
Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend
53b9eff3ffc1768d3503021e7248351e24d59af7
tests/httpd.py
tests/httpd.py
import SimpleHTTPServer import BaseHTTPServer class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_POST(s): s.send_response(200) s.end_headers() if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class(('0.0.0.0', 8328), Handler) try: ...
import BaseHTTPServer class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): content_type = self.headers.getheader('content-type') content_length = int(self.headers.getheader('content-length')) self.send_response(200) self.send_header('Content-Type', content_type) ...
Fix test http server, change to echo back request body
Fix test http server, change to echo back request body
Python
bsd-2-clause
chop-dbhi/django-webhooks,pombredanne/django-webhooks,pombredanne/django-webhooks,chop-dbhi/django-webhooks
b9143462c004af7d18a66fa92ad94585468751b9
IndexedRedis/fields/classic.py
IndexedRedis/fields/classic.py
# Copyright (c) 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information. # # fields.classic - The IRField type which behaves like the "classic" IndexedRedis string-named fields. # # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab : from . import IRField, IR_NULL_STRINGS, irNull from ..co...
# Copyright (c) 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information. # # fields.classic - The IRField type which behaves like the "classic" IndexedRedis string-named fields. # # vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab : from . import IRField, IR_NULL_STRINGS, irNull from ..co...
Change IRFieldClassic to use 'encoded_str_type'
Change IRFieldClassic to use 'encoded_str_type'
Python
lgpl-2.1
kata198/indexedredis,kata198/indexedredis
effa5f84fc93ced38ad9e5d3b0a16bea2d3914ef
caminae/common/templatetags/field_verbose_name.py
caminae/common/templatetags/field_verbose_name.py
from django import template register = template.Library() def field_verbose_name(obj, field): """Usage: {{ object|get_object_field }}""" return obj._meta.get_field(field).verbose_name register.filter(field_verbose_name) register.filter('verbose', field_verbose_name)
from django import template from django.db.models.fields.related import FieldDoesNotExist register = template.Library() def field_verbose_name(obj, field): """Usage: {{ object|get_object_field }}""" try: return obj._meta.get_field(field).verbose_name except FieldDoesNotExist: a = getattr(o...
Allow column to be a property
Allow column to be a property
Python
bsd-2-clause
makinacorpus/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,Anaethelion/Geotrek,johan--/Geotrek,johan--/Geotrek,johan--/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-adm...
bdb78cd1bb13981a20ecb0cf9eb981d784c95b0e
fellowms/forms.py
fellowms/forms.py
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "inauguration_year", "mentor", ] class EventForm(ModelForm): class Meta: mo...
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "home_lon", "home_lat", "inauguration_year", "mentor", ] ...
Update form to handle home_lon and home_lat
Update form to handle home_lon and home_lat
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
ca2b02d551e9bb4c8625ae79f7878892673fa731
corehq/apps/es/domains.py
corehq/apps/es/domains.py
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): ...
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] +...
Add CommCare, CommTrack filters for DomainES
Add CommCare, CommTrack filters for DomainES
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq
11f933e986dd9e2c62b852ca38a37f959c10145e
tools/utils.py
tools/utils.py
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os....
#!/usr/bin/env python ''' This script provides utils for python scripts in cameo. ''' import os import sys import subprocess def TryAddDepotToolsToPythonPath(): depot_tools = FindDepotToolsInPath() if depot_tools: sys.path.append(depot_tools) def FindDepotToolsInPath(): paths = os.getenv('PATH').split(os....
Fix FindDepotToolsInPath not working in some cases
Fix FindDepotToolsInPath not working in some cases When depot tools' path in PATH is like '/home/project/depot_tools/', FindDepotToolsInPath will not detect it because os.path.basename will get empty string. Fix this by getting its parent if its basename is empty. BUG=https://github.com/otcshare/cameo/issues/29
Python
bsd-3-clause
shaochangbin/crosswalk,rakuco/crosswalk,RafuCater/crosswalk,DonnaWuDongxia/crosswalk,tomatell/crosswalk,mrunalk/crosswalk,jpike88/crosswalk,dreamsxin/crosswalk,stonegithubs/crosswalk,weiyirong/crosswalk-1,siovene/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk,fujunwei/crosswalk,ZhengXinCN/crosswalk,minggangw/c...
91ff0fcb40d5d5318b71f0eb4b0873fb470265a0
migrations/versions/f0c9c797c230_populate_application_settings_with_.py
migrations/versions/f0c9c797c230_populate_application_settings_with_.py
"""populate application_settings with started apps Revision ID: f0c9c797c230 Revises: 31850461ed3 Create Date: 2017-02-16 01:02:02.951573 """ # revision identifiers, used by Alembic. revision = 'f0c9c797c230' down_revision = '31850461ed3' from alembic import op import sqlalchemy as sa from puffin.core import docke...
"""populate application_settings with started apps Revision ID: f0c9c797c230 Revises: 31850461ed3 Create Date: 2017-02-16 01:02:02.951573 """ # revision identifiers, used by Alembic. revision = 'f0c9c797c230' down_revision = '31850461ed3' from alembic import op import sqlalchemy as sa from puffin.core import docke...
Add downgrade started applications migration
Add downgrade started applications migration
Python
agpl-3.0
loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin,loomchild/jenca-puffin,loomchild/puffin
50ead4fe13eec7ad9760f0f577212beb8e8a51be
pombola/info/views.py
pombola/info/views.py
from django.views.generic import DetailView from models import InfoPage class InfoPageView(DetailView): """Show the page, or 'index' if no slug""" model = InfoPage
from django.views.generic import DetailView from models import InfoPage class InfoPageView(DetailView): """Show the page for the given slug""" model = InfoPage queryset = InfoPage.objects.filter(kind=InfoPage.KIND_PAGE)
Use a queryset to display only kind=page
Use a queryset to display only kind=page
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,hzj123/56th,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,h...
528edba420089249bd58c0621e06225db84e223f
opps/contrib/logging/models.py
opps/contrib/logging/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, ...
Add missing translation on logging contrib app
Add missing translation on logging contrib app
Python
mit
jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps
411decbdb193b28bb3060e02e81bfa29483e85a9
staticgen_demo/blog/staticgen_views.py
staticgen_demo/blog/staticgen_views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
Remove debug code from staticgen views.
Remove debug code from staticgen views.
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
673d6cecfaeb0e919f30997f793ee2bb18e399ee
tempest/api_schema/response/compute/v2/hypervisors.py
tempest/api_schema/response/compute/v2/hypervisors.py
# Copyright 2014 NEC Corporation. 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 ...
# Copyright 2014 NEC Corporation. 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 ...
Fix V2 hypervisor server schema attribute
Fix V2 hypervisor server schema attribute Nova v2 hypervisor server API return attribute "uuid" in response's server dict. Current response schema does not have this attribute instead it contain "id" which is wrong. This patch fix the above issue. NOTE- "uuid" attribute in this API response is always a uuid. Change...
Python
apache-2.0
jaspreetw/tempest,openstack/tempest,Vaidyanath/tempest,vedujoshi/tempest,NexusIS/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,tonyli71/tempest,hayderimran7/tempest,xbezdick/tempest,akash1808/tempest,roopali8/tempest,tudorvio/tempest,alinbalutoiu/tempest,flyingfish007/tempest,manasi24/jiocloud-tempest-qatempest...
6de1083784d8a73e234dd14cabd17e7ee5852949
tools/clean_output_directory.py
tools/clean_output_directory.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import shutil import sys import utils def Main(): build_root = utils.GetBuild...
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # import shutil import sys import subprocess import utils def Main(): build_roo...
Add missing import to utility python script
Add missing import to utility python script BUG= R=kustermann@google.com Review URL: https://codereview.chromium.org//1222793010.
Python
bsd-3-clause
dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/da...
13c968f9f345f58775750f1f83ca7881cee2755a
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://pcawg_admin:pcawg@localhost:5432/germline_genotype_tracking') df.to_sql("pcawg_samples", engine)
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://pcawg_admin:pcawg@run-tracking-db.service.consul:5432/germline_genotype_tracking') df.to_sql("pcawg_samples", engine)
Use Tracking DB Service URL rather than localhost in the DB connection string.
Use Tracking DB Service URL rather than localhost in the DB connection string.
Python
mit
llevar/germline-regenotyper,llevar/germline-regenotyper
fedff2e76d8d96f1ea407f7a3a48aa8dc7a7e50a
analysis/opensimulator-stats-analyzer/src/ostagraph.py
analysis/opensimulator-stats-analyzer/src/ostagraph.py
#!/usr/bin/python import argparse import matplotlib.pyplot as plt from pylab import * from osta.osta import * ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--select', help = "Select the full name of a stat to gr...
#!/usr/bin/python import argparse import matplotlib.pyplot as plt from pylab import * from osta.osta import * ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--select', help = "Select the full name of a stat to gr...
Make x axis label samples for now, though eventually should have a date option
Make x axis label samples for now, though eventually should have a date option
Python
bsd-3-clause
justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools,justinccdev/opensimulator-tools
114b3f3403e970943618e7096b0b898b8aa5589f
microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py
microdrop/core_plugins/electrode_controller_plugin/on_plugin_install.py
from datetime import datetime import logging from path_helpers import path from pip_helpers import install if __name__ == '__main__': logging.basicConfig(level=logging.INFO) logging.info(str(datetime.now())) requirements_file = path(__file__).parent.joinpath('requirements.txt') if requirements_file.e...
from datetime import datetime import logging from path_helpers import path from pip_helpers import install if __name__ == '__main__': logging.basicConfig(level=logging.INFO) logging.info(str(datetime.now())) requirements_file = path(__file__).parent.joinpath('requirements.txt') if requirements_file.e...
Remove verbose keywork for pip install
Remove verbose keywork for pip install
Python
bsd-3-clause
wheeler-microfluidics/microdrop
7a78525bb8cc6176dfbe348e5f95373c1d70628f
functions.py
functions.py
#-*- coding: utf-8 -*- def getClientIP( req ): ''' Get the client ip address ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, trueOpts=['YES', 'Y', '1', 'TRUE', 'T'] ): ''' Retrieve the...
#-*- coding: utf-8 -*- def getClientIP( req ): ''' Get the client ip address @param req The request; ''' xForwardedFor=req.META.get('HTTP_X_FORWARDED_FOR') if xForwardedFor: ip=xForwardedFor.split(',')[0] else: ip=req.META.get('REMOTE_ADDR') return ip def getBool( val, defVal=False, trueOpts=['YES', 'Y',...
Add the checkRecaptcha( req, secret, simple=True ) function
Add the checkRecaptcha( req, secret, simple=True ) function
Python
apache-2.0
kensonman/webframe,kensonman/webframe,kensonman/webframe
f2f74f53fe8f5b4ac4cd728c4181b3a66b4e873d
euler009.py
euler009.py
# euler 009 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
# Project Euler # 9 - Special Pythagorean triplet # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc.
Change problem description so it actually makes sense
Change problem description so it actually makes sense
Python
mit
josienb/project_euler,josienb/project_euler
87f892731678049b5a706a36487982ebb9da3991
pybossa_discourse/globals.py
pybossa_discourse/globals.py
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app...
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] sel...
Add API client to global envar
Add API client to global envar
Python
bsd-3-clause
alexandermendes/pybossa-discourse
edb07b507aa93ead278cecd168da83a4be68b2ba
bluebottle/settings/travis.py
bluebottle/settings/travis.py
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci e...
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci e...
Disable front-end testing on Travis
Disable front-end testing on Travis Travis has dificulty running the front-end tests. For now we'll disable them.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
f3f428480a8e61bf22532503680e718fd5f0d286
fb/views.py
fb/views.py
from django.shortcuts import render # Create your views here.
from django.shortcuts import render from fb.models import UserPost def index(request): if request.method == 'GET': posts = UserPost.objects.all() context = { 'posts': posts, } return render(request, 'index.html', context)
Write the first view - news feed.
Write the first view - news feed.
Python
apache-2.0
pure-python/brainmate
e978b8be7ccfd9206d618f5a3de855a306ceccfe
test.py
test.py
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): ...
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): ...
Test if rotor encodes with different offset properly
Test if rotor encodes with different offset properly
Python
mit
ranisalt/enigma
691093e38598959f98b319f7c57852496a26ba90
apps/careers/models.py
apps/careers/models.py
import watson from cms.apps.pages.models import ContentBase from cms.models import HtmlField, SearchMetaBase from django.db import models class Careers(ContentBase): # The heading that the admin places this content under. classifier = "apps" # The urlconf used to power this content's views. urlconf ...
import watson from cms.apps.pages.models import ContentBase from cms.models import HtmlField, SearchMetaBase from django.db import models class Careers(ContentBase): # The heading that the admin places this content under. classifier = "apps" # The urlconf used to power this content's views. urlconf ...
Fix project name in urlconf
Fix project name in urlconf
Python
mit
onespacemedia/cms-jobs,onespacemedia/cms-jobs
88e0ec5ff58f7dabb531749472a410498c8e7827
py_skiplist/iterators.py
py_skiplist/iterators.py
from itertools import dropwhile, count, cycle import random def geometric(p): return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1])) def uniform(n): """ Simple deterministic distribution for testing internal of the skiplist """ return (n for _ in cyc...
from itertools import dropwhile, count, repeat import random def geometric(p): return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1)) # Simple deterministic distribution for testing internals of the skiplist. uniform = repeat
Use itertools.repeat over slower alternatives.
Use itertools.repeat over slower alternatives.
Python
mit
ZhukovAlexander/skiplist-python
52d65ff926a079b4e07e8bc0fda3e3c3fe8f9437
thumbor/detectors/queued_detector/__init__.py
thumbor/detectors/queued_detector/__init__.py
from remotecv import pyres_tasks from remotecv.unique_queue import UniqueQueue from thumbor.detectors import BaseDetector class QueuedDetector(BaseDetector): queue = UniqueQueue() def detect(self, callback): engine = self.context.modules.engine self.queue.enqueue_unique(pyres_tasks.DetectTask...
from remotecv.unique_queue import UniqueQueue from thumbor.detectors import BaseDetector class QueuedDetector(BaseDetector): queue = UniqueQueue() def detect(self, callback): engine = self.context.modules.engine self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect'...
Remove dependency from remotecv worker on queued detector
Remove dependency from remotecv worker on queued detector
Python
mit
fanhero/thumbor,fanhero/thumbor,fanhero/thumbor,fanhero/thumbor
c9f8663e6b0bf38f6c041a3a6b77b8a0007a9f09
urls.py
urls.py
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.views.generic.simple import direct_to_template admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^i4p/', include('i4p.foo.urls')), # Uncomment the admin/d...
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.views.generic.simple import direct_to_template admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^i4p/', include('i4p.foo.urls')), # Uncomment the admin/d...
Add a name to the index URL
Add a name to the index URL
Python
agpl-3.0
ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople
73ff56f4b8859e82b0d69a6505c982e26de27859
util.py
util.py
def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def ...
import colorsys import random def randcolor(): hue = random.random() sat = random.randint(700, 1000) / 1000 val = random.randint(700, 1000) / 1000 return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1 for n in nums: r *= n return r def choos...
Add randcolor function to uitl
Add randcolor function to uitl
Python
unlicense
joseph346/cellular
7801c5d7430233eb78ab8b2a91f5960bd808b2c7
app/admin/views.py
app/admin/views.py
from flask import Blueprint, render_template from flask_security import login_required admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') @login_required def index(): return render_template('admin/index.html', title='Admin')
from flask import Blueprint, render_template, redirect, url_for from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') def index(): return render_template('admin/index.html', title='Admin') @admin.before_request def require_login(): if not curr...
Move admin authentication into before_request handler
Move admin authentication into before_request handler
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
6ce14f21cec2c37939f68aaf40d5227c80636e53
app_bikes/forms.py
app_bikes/forms.py
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value ...
from dal import autocomplete from django import forms class BikeModelForm(forms.ModelForm): def __init__(self, *args, **kw): super(BikeModelForm, self).__init__(*args, **kw) if self.instance is not None: # Saved instance is loaded, setup choices to display the selected value ...
Add docstring to explain the code
Add docstring to explain the code
Python
agpl-3.0
laboiteproject/laboite-backend,laboiteproject/laboite-backend,bgaultier/laboitepro,bgaultier/laboitepro,bgaultier/laboitepro,laboiteproject/laboite-backend
0b1f38b8354a0ad6a021f247a7bc1336ae5d50fb
arcade/__init__.py
arcade/__init__.py
""" The Arcade Library A Python simple, easy to use module for creating 2D games. """ import arcade.key import arcade.color from .version import * from .window_commands import * from .draw_commands import * from .sprite import * from .physics_engines import * from .physics_engine_2d import * from .application import ...
""" The Arcade Library A Python simple, easy to use module for creating 2D games. """ import arcade.key import arcade.color from arcade.version import * from arcade.window_commands import * from arcade.draw_commands import * from arcade.sprite import * from arcade.physics_engines import * from arcade.physics_engine_2...
Change some of the relative imports, which fail in doctests, to absolute imports.
Change some of the relative imports, which fail in doctests, to absolute imports.
Python
mit
mikemhenry/arcade,mikemhenry/arcade
ed4f786de54dde50cb26cfe4859507579806a14b
portal_sale_distributor/models/ir_action_act_window.py
portal_sale_distributor/models/ir_action_act_window.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, api from odoo.tools.safe_eval import safe_eval ...
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, api from odoo.tools.safe_eval import safe_eval ...
Adjust to avoid bugs with other values in context
[FIX] portal_sale_distributor: Adjust to avoid bugs with other values in context closes ingadhoc/sale#493 X-original-commit: 441d30af0c3fa8cbbe129893107436ea69cca740 Signed-off-by: Juan José Scarafía <1d1652a8631a1f5a0ea40ef8dcad76f737ce6379@adhoc.com.ar>
Python
agpl-3.0
ingadhoc/sale,ingadhoc/sale,ingadhoc/sale,ingadhoc/sale
4f3234433b97e7f243d54e9e95399f5cabecd315
common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py
common/djangoapps/course_modes/migrations/0005_auto_20151217_0958.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.RemoveField( model_name='coursemode', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.SeparateDatabaseAndState( database_operat...
Change broken course_modes migration to not touch the database.
Change broken course_modes migration to not touch the database. Changing a field name in the way that we did (updating the Python variable name and switching it to point to the old DB column) confuses Django's migration autodetector. No DB changes are actually necessary, but it thinks that a field has been removed and...
Python
agpl-3.0
antoviaque/edx-platform,pepeportela/edx-platform,edx/edx-platform,teltek/edx-platform,ahmedaljazzar/edx-platform,mitocw/edx-platform,edx-solutions/edx-platform,hastexo/edx-platform,IndonesiaX/edx-platform,pepeportela/edx-platform,Lektorium-LLC/edx-platform,mitocw/edx-platform,marcore/edx-platform,romain-li/edx-platform...
faba2bc98f08cddea51d2e0093aa5c2981c8bf15
gdrived.py
gdrived.py
#!/usr/bin/env python # # Copyright 2012 Jim Lawton. 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 requir...
#!/usr/bin/env python # # Copyright 2012 Jim Lawton. 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 requir...
Add update interval constant. Add detail to constructor.
Add update interval constant. Add detail to constructor.
Python
apache-2.0
babycaseny/gdrive-linux,jimlawton/gdrive-linux-googlecode,jimlawton/gdrive-linux,jmfield2/gdrive-linux
ee3941e2c3a0355314b270c04de6a623f5a0730c
plugins/stats.py
plugins/stats.py
import operator class Plugin: def __call__(self, bot): bot.on_hear(r"(lol|:D|:P)", self.on_hear) bot.on_respond(r"stats", self.on_respond) bot.on_help("stats", self.on_help) def on_hear(self, bot, msg, reply): stats = bot.storage.get("stats", {}) for word in msg["match...
import operator class Plugin: def __call__(self, bot): bot.on_hear(r".*", self.on_hear_anything) bot.on_hear(r"(lol|:D|:P)", self.on_hear) bot.on_respond(r"stats", self.on_respond) bot.on_help("stats", self.on_help) def on_hear_anything(self, bot, msg, reply): stats = b...
Add statistics about general speaking
Add statistics about general speaking
Python
mit
thomasleese/smartbot-old,Cyanogenoid/smartbot,tomleese/smartbot,Muzer/smartbot
f2fd7fa693b5be7ae37445fc185611e80aacddf3
pebble/PblBuildCommand.py
pebble/PblBuildCommand.py
import sh, os from PblCommand import PblCommand class PblBuildCommand(PblCommand): name = 'build' help = 'Build your Pebble project' def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') def run(self, args): waf_path = os.path...
import sh, os from PblCommand import PblCommand class PblBuildCommand(PblCommand): name = 'build' help = 'Build your Pebble project' def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') def run(self, args): waf_path = os.path...
Fix bug to actually find the sdk
Fix bug to actually find the sdk
Python
mit
pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble
898028dea2e04d52c32854752bda34d331c7696f
ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py
ynr/apps/candidatebot/management/commands/candidatebot_import_email_from_csv.py
from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from candidatebot.helpers import CandidateBot from popolo.models import Person class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'filename', hel...
from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from candidatebot.helpers import CandidateBot from popolo.models import Person class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'filename', hel...
Move on if email exists
Move on if email exists
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
4616fdefc1c7df8acccdd89ea792fa24ecfa9ca6
perf-tests/src/perf-tests.py
perf-tests/src/perf-tests.py
def main(): pass if __name__ == "__main__": # execute only if run as a script main()
import json import time import datetime import subprocess import os.path import sys import queue import threading from coreapi import * from jobsapi import * import benchmarks import graph def check_environment_variable(env_var_name): print("Checking: {e} environment variable existence".format( e=env_var...
Check environment variables before the tests are started
Check environment variables before the tests are started
Python
apache-2.0
tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common
72f763d9759438abd731585a1b5ef67e62e27181
pyethapp/__init__.py
pyethapp/__init__.py
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.n...
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess import re GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$') __version__ = None try: _dist = get_d...
Use version gathering logic from hydrachain
Use version gathering logic from hydrachain
Python
mit
gsalgado/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,changwu-tw/pyethapp,changwu-tw/pyethapp,gsalgado/pyethapp
4541605e27c9fef6cc23b245de50867ff22ea6aa
erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py
erpnext/accounts/doctype/accounting_dimension/test_accounting_dimension.py
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestAccountingDimension(unittest.TestCase): pass
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.doctype.journal_entry.tes...
Test Case for accounting dimension
fix: Test Case for accounting dimension
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
27112881583e53d790e66d31a2bb4d2a996ee405
python/sparknlp/functions.py
python/sparknlp/functions.py
from pyspark.sql.functions import udf from pyspark.sql.types import * from pyspark.sql import DataFrame import sys import sparknlp def map_annotations(f, output_type: DataType): sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in top-level return udf( lambda con...
from pyspark.sql.functions import udf from pyspark.sql.types import * from pyspark.sql import DataFrame from sparknlp.annotation import Annotation import sys import sparknlp def map_annotations(f, output_type: DataType): sys.modules['sparknlp.annotation'] = sparknlp # Makes Annotation() pickle serializable in t...
Move import to top level to avoid import fail after fist time on sys.modules hack
Move import to top level to avoid import fail after fist time on sys.modules hack
Python
apache-2.0
JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp,JohnSnowLabs/spark-nlp
c266f5171e875d8dc3abe924e4b6c9ed2a486422
tests/sentry/web/frontend/test_organization_home.py
tests/sentry/web/frontend/test_organization_home.py
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationHomePermissionTest(PermissionTestCase): def setUp(self): super(OrganizationHomePermissionTest, self).setUp() self.path = reverse('sentry...
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationHomePermissionTest(PermissionTestCase): def setUp(self): super(OrganizationHomePermissionTest, self).setUp() self.path = reverse('sentry...
Add test for non-member access
Add test for non-member access
Python
bsd-3-clause
drcapulet/sentry,daevaorn/sentry,ifduyue/sentry,hongliang5623/sentry,Natim/sentry,wujuguang/sentry,jokey2k/sentry,korealerts1/sentry,llonchj/sentry,songyi199111/sentry,vperron/sentry,BayanGroup/sentry,BuildingLink/sentry,kevinlondon/sentry,fotinakis/sentry,imankulov/sentry,korealerts1/sentry,boneyao/sentry,jean/sentry,...
5e2aae6070d60f2149c49e1137ab2a99f3966b3a
python/volumeBars.py
python/volumeBars.py
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 4 pi = numpy.pi barHeights = numpy.array([0, pi / 4...
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 4 pi = numpy.pi barHeights = numpy.array([0, pi / 4...
Add specific colors for heights
Add specific colors for heights
Python
mit
DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix
214d5f7e09e9b5e854e7471c6dc337456f428647
quickavro/_compat.py
quickavro/_compat.py
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this...
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this...
Add missing ensure_str for PY2
Add missing ensure_str for PY2
Python
apache-2.0
ChrisRx/quickavro,ChrisRx/quickavro
a88eb2c7fc2c2d875836f0a4c201ede0c082aceb
selectable/tests/__init__.py
selectable/tests/__init__.py
from django.db import models from ..base import ModelLookup from ..registry import registry class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __unicode__(self): return self.name def __str__(self): return self.name ...
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __s...
Update the test model definitions.
Update the test model definitions.
Python
bsd-2-clause
affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable
c3b1f8c97f89e5b9e8b8e74992631bac33bdde5f
tests/test_read_user_choice.py
tests/test_read_user_choice.py
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI...
# -*- coding: utf-8 -*- import click import pytest from cookiecutter.compat import read_user_choice OPTIONS = ['hello', 'world', 'foo', 'bar'] EXPECTED_PROMPT = """Select varname: 1 - hello 2 - world 3 - foo 4 - bar Choose from 1, 2, 3, 4!""" @pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTI...
Implement a test if read_user_choice raises on invalid options
Implement a test if read_user_choice raises on invalid options
Python
bsd-3-clause
lucius-feng/cookiecutter,foodszhang/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,Vauxoo/cookiecutter,sp1rs/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,benthomasson/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,vintas...
47e79b3a01ca4541d79412cdab856f84871e68f8
templates/vnc_api_lib_ini_template.py
templates/vnc_api_lib_ini_template.py
import string template = string.Template(""" [global] ;WEB_SERVER = 127.0.0.1 ;WEB_PORT = 9696 ; connection through quantum plugin WEB_SERVER = 127.0.0.1 WEB_PORT = 8082 ; connection to api-server directly BASE_URL = / ;BASE_URL = /tenants/infra ; common-prefix for all URLs ; Authentication settings (optional) [aut...
import string template = string.Template(""" [global] ;WEB_SERVER = 127.0.0.1 ;WEB_PORT = 9696 ; connection through quantum plugin WEB_SERVER = 127.0.0.1 WEB_PORT = 8082 ; connection to api-server directly BASE_URL = / ;BASE_URL = /tenants/infra ; common-prefix for all URLs ; Authentication settings (optional) [aut...
Add auth protocol for keystone connection in vnc_api
Add auth protocol for keystone connection in vnc_api
Python
apache-2.0
Juniper/contrail-provisioning,Juniper/contrail-provisioning
e8b50a70fc7de1842ebe8bc796736459bf154432
dyconnmap/cluster/__init__.py
dyconnmap/cluster/__init__.py
# -*- coding: utf-8 -*- """ """ # Author: Avraam Marimpis <avraam.marimpis@gmail.com> from .ng import NeuralGas from .mng import MergeNeuralGas from .rng import RelationalNeuralGas from .gng import GrowingNeuralGas from .som import SOM from .umatrix import umatrix __all__ = [ "NeuralGas", "MergeNeuralGas",...
# -*- coding: utf-8 -*- """ """ # Author: Avraam Marimpis <avraam.marimpis@gmail.com> from .ng import NeuralGas from .mng import MergeNeuralGas from .rng import RelationalNeuralGas from .gng import GrowingNeuralGas from .som import SOM from .umatrix import umatrix from .validity import ray_turi, davies_bouldin __a...
Add the new cluster validity methods in the module.
Add the new cluster validity methods in the module.
Python
bsd-3-clause
makism/dyfunconn
3d38848287b168cfbe3c9fe5297e7f322027634d
tests/test_parsePoaXml_test.py
tests/test_parsePoaXml_test.py
import unittest import os import re os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import parsePoaXml import generatePoaXml # Import test settings last in order to override the regular settings import poa_test_settings as settings def override_settings(): # For now need to ov...
import unittest import os import re os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import parsePoaXml import generatePoaXml # Import test settings last in order to override the regular settings import poa_test_settings as settings class TestParsePoaXml(unittest.TestCase): d...
Delete excess code in the latest test scenario.
Delete excess code in the latest test scenario.
Python
mit
gnott/elife-poa-xml-generation,gnott/elife-poa-xml-generation
ddad1cf5c4b90ad7997fee72ecd4949dafa43315
custom/enikshay/model_migration_sets/private_nikshay_notifications.py
custom/enikshay/model_migration_sets/private_nikshay_notifications.py
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ( ENROLLED_IN_PRIVATE, REAL_DATASET_PROPERTY_VALUE, ) class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(...
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ENROLLED_IN_PRIVATE class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(self, domain, person, episode): se...
Remove redundant case property check
Remove redundant case property check
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
b3224d83dd1fea7a4b50f93c775a824d82aec806
scan/commands/include.py
scan/commands/include.py
''' Created on Mar 8,2015 @author: qiuyx ''' from scan.commands.command import Command import xml.etree.ElementTree as ET class Include(Command): ''' classdocs ''' def __init__(self, scanFile=None, macros=None,errHandler=None): ''' @param scanFile: The included scan file path located...
''' Created on Mar 8,2015 @author: qiuyx ''' from scan.commands.command import Command import xml.etree.ElementTree as ET class Include(Command): ''' classdocs ''' def __init__(self, scan, macros=None, errhandler=None): ''' @param scan: Name of included scan file, must be on the se...
Include command: All arguments lowercase. Require file, default to empty macros
Include command: All arguments lowercase. Require file, default to empty macros
Python
epl-1.0
PythonScanClient/PyScanClient,PythonScanClient/PyScanClient
b47ecb3464585d762c17694190286388c25dbaf8
examples/convert_units.py
examples/convert_units.py
# -*- coding: utf-8 -*- from chatterbot import ChatBot bot = ChatBot( "Unit Converter", logic_adapters=[ "chatterbot.logic.UnitConversion", ], input_adapter="chatterbot.input.VariableInputTypeAdapter", output_adapter="chatterbot.output.OutputAdapter" ) questions = ['How many meters are in...
# -*- coding: utf-8 -*- from chatterbot import ChatBot bot = ChatBot( "Unit Converter", logic_adapters=[ "chatterbot.logic.UnitConversion", ], input_adapter="chatterbot.input.VariableInputTypeAdapter", output_adapter="chatterbot.output.OutputAdapter" ) questions = ['How many meters are in...
Break list declaration in multiple lines
Break list declaration in multiple lines
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
d38617dd6bf5c7b0f17245dd5a5e95a335ac6626
tracpro/orgs_ext/middleware.py
tracpro/orgs_ext/middleware.py
from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest from temba_client.base import TembaAPIError class HandleTembaAPIError(object): """ Catch all Temba exception errors """ def process_exception(self, request, exception): if isinstance(exception, Tem...
from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseBadRequest from temba_client.base import TembaAPIError, TembaConnectionError class HandleTembaAPIError(object): """ Catch all Temba exception errors """ def process_exception(self, request, exception): rapid...
Check forerror codes from temba connection issues
Check forerror codes from temba connection issues
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro
be19869d76bb655990464094ad17617b7b48ab3b
server/create_tiff.py
server/create_tiff.py
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', ...
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', ...
Print command in failure case
Print command in failure case
Python
apache-2.0
DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image
e5acbfc176de3b531528c8b15f57e5d3feab3ad1
melody/constraints/abstract_constraint.py
melody/constraints/abstract_constraint.py
""" File: abstract_constraint.py Purpose: Define a constraint, in an abstract sense, related to a number of actors. """ from abc import ABCMeta, abstractmethod class AbstractConstraint(object): """ Class that represents a constraint, a set of actors that define a constraint amongst themselves. Paramet...
""" File: abstract_constraint.py Purpose: Define a constraint, in an abstract sense, related to a number of actors. """ from abc import ABCMeta, abstractmethod class AbstractConstraint(object): """ Class that represents a constraint, a set of actors that define a constraint amongst themselves. Paramet...
Add hash and eq methods
Add hash and eq methods
Python
mit
dpazel/music_rep
8c2ad666266d4dbe8310007bd82dc907a288ee5a
databroker/__init__.py
databroker/__init__.py
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, ...
# Import intake to run driver discovery first and avoid circular import issues. import intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, wrap_in_doc...
Include intake.cat. YAML is easier than entry_points.
Include intake.cat. YAML is easier than entry_points.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
0624417fbac1cf23316ee0a58ae41c0519a390c4
go/apps/surveys/definition.py
go/apps/surveys/definition.py
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) from go.apps.surveys.tasks import export_vxpolls_data class SendSurveyAction(ConversationAction): action_name = 'send_survey' action_display_name = 'Send Survey' needs_confirmation = True needs_gro...
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) from go.apps.surveys.tasks import export_vxpolls_data class SendSurveyAction(ConversationAction): action_name = 'send_survey' action_display_name = 'Send Survey' needs_confirmation = True needs_gro...
Change download survey data display verb to 'Send CSV via e-mail'.
Change download survey data display verb to 'Send CSV via e-mail'.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
7a3c4eed8888c8c2befc94020bebbfc18e1d6156
src/redis_client.py
src/redis_client.py
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None @defer.inlineCallbacks def run_redis_client(on_started): pony = yield redis.makeConnection(config.redis['host'], config.redis['port'], ...
import txredisapi as redis from twisted.internet import defer, reactor import config connection = None def run_redis_client(on_started): df = redis.makeConnection(config.redis['host'], config.redis['port'], config.redis['db'], ...
Fix the Redis client connection to actually work
Fix the Redis client connection to actually work It previously lied.
Python
mit
prophile/compd,prophile/compd
fdee90e6fd4669222c2da0530d9bc90131b5145e
djoser/social/views.py
djoser/social/views.py
from rest_framework import generics, permissions, status from rest_framework.response import Response from social_django.utils import load_backend, load_strategy from djoser.conf import settings from djoser.social.serializers import ProviderAuthSerializer class ProviderAuthView(generics.CreateAPIView): permissio...
from rest_framework import generics, permissions, status from rest_framework.response import Response from social_django.utils import load_backend, load_strategy from djoser.conf import settings from djoser.social.serializers import ProviderAuthSerializer class ProviderAuthView(generics.CreateAPIView): permissio...
Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS
Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS i forget add SOCIAL_AUTH_ALLOWED_REDIRECT_URIS to my config it return 400 error, i don't know why , i pay more time find the issues so i add Friendly tips -- sorry , my english is not well and thank you all
Python
mit
sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser
db14ed2c23b3838796e648faade2c73b786d61ff
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sys import threading import time import traceback from .singleton import Singleton def ...
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sys import threading import time import traceback from .singleton import Singleton def ...
Make exception message builder a nicer function
Make exception message builder a nicer function It is used by clients in other modules.
Python
mit
waltermoreira/tartpy
3976a5b38e1b5356b83d22d9113aa83c9f09fdec
admin/manage.py
admin/manage.py
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain...
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain...
Allow admin creation after initial setup
Allow admin creation after initial setup
Python
mit
kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io
2a7d28573d1e4f07250da1d30209304fdb6de90d
sqlobject/tests/test_blob.py
sqlobject/tests/test_blob.py
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', lengt...
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', lengt...
Use byte string for test
Tests(blob): Use byte string for test
Python
lgpl-2.1
sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject
95fa71c4439343764cac95a1667e08dc21cb6ebe
plugins.py
plugins.py
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_p...
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_p...
Fix plugin test by running scripts as user deploy
Fix plugin test by running scripts as user deploy
Python
bsd-3-clause
ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment
9c35a41c6594d0ac482a558abf4772150c2a67e9
squash/dashboard/urls.py
squash/dashboard/urls.py
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'job', views.JobViewSet) router.register(r'metric', views.MetricViewSet)...
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views <<<<<<< HEAD router = DefaultRouter() router.register(r'job', views.JobViewSet) router.register(r'metric', views.M...
Make all API resource collection endpoints plural
Make all API resource collection endpoints plural /api/job/ -> /api/jobs/ /api/metric/ -> /api/metrics/ It's a standard convention in RESTful APIs to make endpoints for collections plural.
Python
mit
lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard
32a61c6df871ad148a8c51b7b4cab3f392a2c61a
tsune/urls.py
tsune/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'tsune.views.home', name='home'), # url(r'^tsune/', include('tsune.foo.urls')), # Uncomment...
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.http import HttpResponseRedirect admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'tsune.views.home', name='home'), # url(r'^tsune/'...
Add redirect to cardbox if root url is accessed
Add redirect to cardbox if root url is accessed
Python
mit
DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune
171bbf488db643d01d6a58c9376ba85c200711d5
gtts/tokenizer/tests/test_pre_processors.py
gtts/tokenizer/tests/test_pre_processors.py
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) ...
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) ...
Update unit test for ad8bcd8
Update unit test for ad8bcd8
Python
mit
pndurette/gTTS