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 |
|---|---|---|---|---|---|---|---|---|---|---|
08ce22e8c467f7fb7da056e098ac88b64c3096dc | step_stool/content.py | step_stool/content.py | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... | Fix file open/read/close - there was no close() call in previous version! Use context handler instead. | Fix file open/read/close - there was no close() call in previous version! Use context handler instead.
| Python | mit | chriskrycho/step-stool,chriskrycho/step-stool | ---
+++
@@ -25,10 +25,11 @@
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
- md_text = open(file_path, 'r').read()
- content = md.convert(md_text)
+ plain_slug, extension = ... |
4e3eeba94423399411a763487411b097c4c7972e | rasterfairy/__init__.py | rasterfairy/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Top-level module for RasterFairy"""
from rasterfairy import *
from coonswarp import *
from rfoptimizer import *
from images2gif import *
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Top-level module for RasterFairy"""
from .rasterfairy import *
from .coonswarp import *
from .rfoptimizer import *
# from images2gif import *
| Optimize internal imports from python2 to python3. | Optimize internal imports from python2 to python3.
Also, ignore images2gif import.
| Python | bsd-3-clause | Quasimondo/RasterFairy | ---
+++
@@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
"""Top-level module for RasterFairy"""
-from rasterfairy import *
-from coonswarp import *
-from rfoptimizer import *
-from images2gif import *
+from .rasterfairy import *
+from .coonswarp import *
+from .rfoptimizer import *
+# from images2gif import *
|
6930782947f604630142b106cb079e627fcff499 | readthedocs/v3/views.py | readthedocs/v3/views.py | import django_filters.rest_framework
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_flex_field... | import django_filters.rest_framework as filters
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest... | Use a class filter to allow expansion | Use a class filter to allow expansion
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | ---
+++
@@ -1,4 +1,4 @@
-import django_filters.rest_framework
+import django_filters.rest_framework as filters
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
@@ -8,6 +8,7 @... |
11860d9181d7a8e1a3924bc42234903ba96e304d | ForgeGit/forgegit/tests/test_git_app.py | ForgeGit/forgegit/tests/test_git_app.py | import unittest
from pylons import c, g
from ming.orm import ThreadLocalORMSession
from pyforge.tests import helpers
from pyforge.lib import helpers as h
class TestGitApp(unittest.TestCase):
def setUp(self):
helpers.setup_basic_test()
helpers.setup_global_objects()
h.set_context('test',... | import unittest
from pylons import c, g
from ming.orm import ThreadLocalORMSession
from pyforge.tests import helpers
from pyforge.lib import helpers as h
class TestGitApp(unittest.TestCase):
def setUp(self):
helpers.setup_basic_test()
helpers.setup_global_objects()
h.set_context('test',... | Update test to reflect changing git codebase | Update test to reflect changing git codebase
| Python | apache-2.0 | apache/incubator-allura,lym/allura-git,Bitergia/allura,lym/allura-git,leotrubach/sourceforge-allura,Bitergia/allura,leotrubach/sourceforge-allura,lym/allura-git,heiths/allura,Bitergia/allura,leotrubach/sourceforge-allura,apache/incubator-allura,heiths/allura,lym/allura-git,apache/incubator-allura,heiths/allura,lym/allu... | ---
+++
@@ -20,7 +20,7 @@
assert c.app.templates.endswith('forgegit/templates')
def test_admin_menu(self):
- assert c.app.admin_menu() == []
+ assert len(c.app.admin_menu()) == 1
def test_uninstall(self):
c.app.uninstall(c.project) |
a494260a8f9cf0e3ecf0c428bb70d4066623f1dd | wqflask/utility/elasticsearch_tools.py | wqflask/utility/elasticsearch_tools.py | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | es = None
try:
from elasticsearch import Elasticsearch, TransportError
from utility.tools import ELASTICSEARCH_HOST, ELASTICSEARCH_PORT
es = Elasticsearch([{
"host": ELASTICSEARCH_HOST
, "port": ELASTICSEARCH_PORT
}]) if (ELASTICSEARCH_HOST and ELASTICSEARCH_PORT) else None
except:
... | Refactor common items to more generic methods. | Refactor common items to more generic methods.
* Refactor code that can be used in more than one place to a more
generic method/function that's called by other methods
| Python | agpl-3.0 | pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,... | ---
+++
@@ -11,25 +11,27 @@
es = None
def get_user_by_unique_column(column_name, column_value):
- user_details = None
+ return get_item_by_unique_column(column_name, column_value, index="users", doc_type="local")
+
+def save_user(user, user_id):
+ es_save_data("users", "local", user, user_id)
+
+def ... |
c5b8ea3c7f3bf111e36515f92ab3aeb70026771e | openstack-dashboard/dashboard/tests.py | openstack-dashboard/dashboard/tests.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
from django import test
from django.core import mail
from mailer import engine
from mailer import send_mail
class DjangoMailerPresenceTest(test.TestCase):
def test_mailsent(self):
send_mail('subject', 'message_body', 'from@test.com', ['to@test.com'])
en... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
''' Test for django mailer.
This test is pretty much worthless, and should be removed once real testing of
views that send emails is implemented
'''
from django import test
from django.core import mail
from mailer import engine
from mailer import send_mail
class DjangoMa... | Add comment ot openstack test | Add comment ot openstack test
| Python | apache-2.0 | usc-isi/horizon-old,coreycb/horizon,Daniex/horizon,gochist/horizon,saydulk/horizon,CiscoSystems/avos,NCI-Cloud/horizon,pnavarro/openstack-dashboard,Solinea/horizon,promptworks/horizon,Mirantis/mos-horizon,tuskar/tuskar-ui,yjxtogo/horizon,mandeepdhami/horizon,cloud-smokers/openstack-dashboard,Metaswitch/horizon,asomya/t... | ---
+++
@@ -1,4 +1,9 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
+''' Test for django mailer.
+
+This test is pretty much worthless, and should be removed once real testing of
+views that send emails is implemented
+'''
from django import test
from django.core import mail |
f5cab8249d5e162285e5fc94ded8bf7ced292986 | test/test_ev3_key.py | test/test_ev3_key.py | from ev3.ev3dev import Key
import unittest
from util import get_input
import time
class TestTone(unittest.TestCase):
def test_tone(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input(... | from ev3.ev3dev import Key
import unittest
from util import get_input
class TestKey(unittest.TestCase):
def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard... | Change dname of key test | Change dname of key test
| Python | apache-2.0 | topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3 | ---
+++
@@ -1,12 +1,11 @@
from ev3.ev3dev import Key
import unittest
from util import get_input
-import time
-class TestTone(unittest.TestCase):
+class TestKey(unittest.TestCase):
- def test_tone(self):
+ def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
p... |
a11cc4bae9fa48144b8a755eb3cb17fd707f2a7c | lib/ansible/release.py | lib/ansible/release.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | Add post modifier to version | Add post modifier to version
| Python | mit | thaim/ansible,thaim/ansible | ---
+++
@@ -19,6 +19,6 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
-__version__ = '2.7.0.a1'
+__version__ = '2.7.0.a1.post0'
__author__ = 'Ansible, Inc.'
__codename__ = 'In the Light' |
517a76bc9aec3dbe8c21c96be424da838b5fcc02 | apistar/wsgi.py | apistar/wsgi.py | from typing import Iterable, List, Tuple
from werkzeug.http import HTTP_STATUS_CODES
from apistar import http
__all__ = ['WSGIEnviron', 'WSGIResponse']
STATUS_CODES = {
code: "%d %s" % (code, msg)
for code, msg in HTTP_STATUS_CODES.items()
}
WSGIEnviron = http.WSGIEnviron
class WSGIResponse(object):
... | from typing import Iterable, List, Tuple
from werkzeug.http import HTTP_STATUS_CODES
from apistar import http
__all__ = ['WSGIEnviron', 'WSGIResponse']
STATUS_CODES = {
code: "%d %s" % (code, msg)
for code, msg in HTTP_STATUS_CODES.items()
}
ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'
WSG... | Set "Access-Control-Allow-Origin: *" by default | Set "Access-Control-Allow-Origin: *" by default
| Python | bsd-3-clause | encode/apistar,rsalmaso/apistar,encode/apistar,tomchristie/apistar,tomchristie/apistar,tomchristie/apistar,encode/apistar,rsalmaso/apistar,tomchristie/apistar,encode/apistar,rsalmaso/apistar,rsalmaso/apistar | ---
+++
@@ -12,6 +12,7 @@
for code, msg in HTTP_STATUS_CODES.items()
}
+ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'
WSGIEnviron = http.WSGIEnviron
@@ -34,8 +35,13 @@
except KeyError:
status_text = str(response.status)
+ headers = list(response.headers.items(... |
c0ab344235fdd7df8e32c499124596d20f9d9e52 | src/tempel/forms.py | src/tempel/forms.py | from django import forms
from tempel import utils
class EntryForm(forms.Form):
language = forms.ChoiceField(choices=utils.get_languages(),
initial="python")
content = forms.CharField(widget=forms.Textarea)
private = forms.BooleanField(required=False)
| from django import forms
from tempel import utils
class EntryForm(forms.Form):
language = forms.ChoiceField(choices=utils.get_languages(),
initial="python")
content = forms.CharField(widget=forms.Textarea)
private = forms.BooleanField(required=False)
class EditForm(forms.... | Add EditForm that does not have 'private' field. | Add EditForm that does not have 'private' field.
| Python | agpl-3.0 | fajran/tempel | ---
+++
@@ -8,3 +8,8 @@
content = forms.CharField(widget=forms.Textarea)
private = forms.BooleanField(required=False)
+class EditForm(forms.Form):
+ language = forms.ChoiceField(choices=utils.get_languages(),
+ initial="python")
+ content = forms.CharField(widget=form... |
73fa0f555ec140254ecdc09ab17ba1a065861e0c | metakernel/__init__.py | metakernel/__init__.py | from ._metakernel import MetaKernel, IPythonKernel, register_ipython_magics
from . import pexpect
from .replwrap import REPLWrapper, u
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.10.6'
del m... | from ._metakernel import MetaKernel, IPythonKernel, register_ipython_magics
from . import pexpect
from .replwrap import REPLWrapper, u
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.11.0'
del m... | Bump version to 0.11.0 and upload to pypi | Bump version to 0.11.0 and upload to pypi
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -7,6 +7,6 @@
__all__ = ['Magic', 'MetaKernel', 'option']
-__version__ = '0.10.6'
+__version__ = '0.11.0'
del magic, _metakernel, parser, process_metakernel |
c96da14b7bc05d6de7f1ddb9b634ef04ae2e2213 | tests/test_trivia.py | tests/test_trivia.py |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
if __name__ == "__mai... |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parenthes... | Test trivia answers in parentheses with article prefixes | [Tests] Test trivia answers in parentheses with article prefixes
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot | ---
+++
@@ -12,6 +12,17 @@
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
+ def test_parentheses_with_article_prefix(self):
+ self.assertTrue(
+ check_answer(
+ "the ISS (the International Space Station)",
+ "I... |
e3cc22064ebb709788c770a8940d0b0f742a8741 | mpfmonitor/_version.py | mpfmonitor/_version.py | # mpf-monitor
__version__ = '0.54.0-dev.0'
__short_version__ = '0.54'
__bcp_version__ = '1.1'
__config_version__ = '5'
__mpf_version_required__ = '0.54.0-dev.0'
version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format(
__version__, __config_version__, __bcp_version__, __mpf_version_require... | # mpf-monitor
__version__ = '0.54.0-dev.1'
__short_version__ = '0.54'
__bcp_version__ = '1.1'
__config_version__ = '5'
__mpf_version_required__ = '0.54.0-dev.0'
version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format(
__version__, __config_version__, __bcp_version__, __mpf_version_require... | Increment dev version, expect push to PyPi | Increment dev version, expect push to PyPi
| Python | mit | missionpinball/mpf-monitor | ---
+++
@@ -1,5 +1,5 @@
# mpf-monitor
-__version__ = '0.54.0-dev.0'
+__version__ = '0.54.0-dev.1'
__short_version__ = '0.54'
__bcp_version__ = '1.1'
__config_version__ = '5' |
e371842b0efb9a7d160f7909415190fd583b6c68 | tool_requirements.py | tool_requirements.py | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
# Version requirements for various tools. Checked by tooling (e.g. fusesoc),
# and inserted into the documentation.
#
# Entries are keyed by tool name. The value is either ... | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
# Version requirements for various tools. Checked by tooling (e.g. fusesoc),
# and inserted into the documentation.
#
# Entries are keyed by tool name. The value is either ... | Move to hugo version 0.82.0 | [docs/hugo] Move to hugo version 0.82.0
When adding more pinmux signals and pads, we run into a
funny error where HUGO can't read the generated pinmux register
documentation anymore since the file is too big. This file
limitation has just recently (3 months ago) been removed.
See https://github.com/gohugoio/hugo/pull... | Python | apache-2.0 | lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan,lowRISC/opentitan | ---
+++
@@ -21,7 +21,7 @@
'verilator': '4.104',
'hugo_extended': {
- 'min_version': '0.71.0',
+ 'min_version': '0.82.0',
'as_needed': True
},
'verible': { |
ebb3b727b8d7592b7e9755b3f7665314e668a19d | node/string_literal.py | node/string_literal.py | #!/usr/bin/env python
from nodes import Node
class StringLiteral(Node):
args = 0
results = 1
char = '"'
def __init__(self, string):
self.string = string
@Node.test_func([], [""], "")
@Node.test_func([], ["World"], "World\"")
@Node.test_func([], ["Hello"], "Hello")
def func(se... | #!/usr/bin/env python
from nodes import Node
class StringLiteral(Node):
args = 0
results = 1
char = '"'
def __init__(self, string):
self.string = string
@Node.test_func([], [""], "")
@Node.test_func([], ["World"], "World\"")
@Node.test_func([], ["Hello"], "Hello")
def func(se... | Allow `"` to appear in string literals | Allow `"` to appear in string literals
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -23,10 +23,22 @@
@classmethod
def accepts(cls, code, accept = False):
if accept: code = '"'+code
- if code == "": return None, None
- if code[0] != StringLiteral.char:return None, None
+ if code == "":
+ return None, None
+ if code[0] != StringLiter... |
5c2a691ff928c336c35a6ddef38c222b4bb3d2a4 | testproject/manage.py | testproject/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
try:
import pymysql
pymysql.install_as_MySQLdb()
except ImportError:
pass
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")
from django.core.management import execute_from_command_line
execute_from_co... | Add support for testing with pymysql | Add support for testing with pymysql
| Python | bsd-3-clause | uranusjr/django-mosql | ---
+++
@@ -1,6 +1,12 @@
#!/usr/bin/env python
import os
import sys
+try:
+ import pymysql
+ pymysql.install_as_MySQLdb()
+except ImportError:
+ pass
+
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") |
1271f3b978d2ab46824ca7b33472bba5b725f9ac | tests/test_profile.py | tests/test_profile.py | import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
def test_profile_cre... | import os
import tempfile
import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326... | Rework tmpdir for nose (no pytest) | Rework tmpdir for nose (no pytest)
| Python | bsd-3-clause | perrygeo/Fiona,perrygeo/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona,rbuffat/Fiona | ---
+++
@@ -1,3 +1,6 @@
+import os
+import tempfile
+
import fiona
@@ -6,8 +9,9 @@
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
-def test_profile_cr... |
f0e67ca657915e77b1f28bab9fa29f84bfbb8f06 | tests/unit/test_DB.py | tests/unit/test_DB.py | # standard modules
import StringIO
from unittest import TestCase
# custom modules
from iago.DatabaseProvider import DB
class TestDB(TestCase):
def test_read_empty(self):
s = StringIO.StringIO('{}')
d = DB()
try:
d.read(s)
except KeyError:
self.fail('DB cannot handle empty JSON files.')
| # standard modules
import StringIO
from unittest import TestCase
# custom modules
from iago.DatabaseProvider import DB
class TestDB(TestCase):
def test_read_empty(self):
s = StringIO.StringIO('{}')
d = DB()
try:
d.read(s, format='json')
except KeyError:
self.fail('DB cannot handle empty JSON files.')
| Fix test to specify file format | Fix test to specify file format
| Python | mit | ferchault/iago | ---
+++
@@ -11,6 +11,6 @@
s = StringIO.StringIO('{}')
d = DB()
try:
- d.read(s)
+ d.read(s, format='json')
except KeyError:
self.fail('DB cannot handle empty JSON files.') |
0e195e93e0a2f80bc85f8425254e8a1d3c324654 | bockus/books/search_indexes.py | bockus/books/search_indexes.py | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(... | from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(... | Add library property to series search index | Add library property to series search index
| Python | mit | phildini/bockus,phildini/bockus,phildini/bockus | ---
+++
@@ -17,6 +17,7 @@
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
+ library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series |
2094f2ef5a47703a881643b8ca25a632fe54e892 | under_overfitting.py | under_overfitting.py | import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import cross_val_score
def main():
np.random.seed(0)
n_samples = 30
degrees = range(1, 16)
true_fn = lambd... | import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import cross_val_score
def main():
np.random.seed(0)
n_samples = 30
degrees = range(1, 16)
true_fn = lambd... | Complete walk of polynomial degrees to find most balance between under and overfitting | Complete walk of polynomial degrees to find most balance between under and overfitting
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -18,15 +18,15 @@
for d in degrees:
poly_features = PolynomialFeatures(degree=d, include_bias=False)
model = LinearRegression()
- pipeline = Pipeline([("polynomial_features", poly_features),
- ("linear_regression", model)])
+ pipeline = Pipeli... |
f915b101b635e644eb9018a8abb9e9c86e6c2a73 | test/test_config.py | test/test_config.py | import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, sta... | import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, sta... | Add a test for default config settings. | Add a test for default config settings.
| Python | apache-2.0 | novel/lc-tools,novel/lc-tools | ---
+++
@@ -27,5 +27,10 @@
config.LC_CONFIG = self.test_filename
config.get_config("default")
+ def test_defaults(self):
+ config.LC_CONFIG = self.test_filename
+ conf = config.get_config("default")
+ print conf.get("verify_ssl_certs")
+
def teardown(self):
os... |
f6b4b16c26ee97d48ba524027a96d17fba63dc80 | project/models.py | project/models.py | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | Update user model with confirmed and confirmed_at | Update user model with confirmed and confirmed_at
| Python | mit | dylanshine/streamschool,dylanshine/streamschool | ---
+++
@@ -12,12 +12,16 @@
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
+ confirmed = db.Column(db.Boolean, nullable=False, default=False)
+ confirmed_on = db.Column(db.DateTime... |
09333f89a7ce9dfda59401bc59d92a3def9ca80c | mycroft/formatters/formatter_plugin.py | mycroft/formatters/formatter_plugin.py | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... | Fix bug with list formatting | Fix bug with list formatting
Before it would completely fail to format any list of strings
| Python | apache-2.0 | MatthewScholefield/mycroft-simple,MatthewScholefield/mycroft-simple | ---
+++
@@ -29,7 +29,7 @@
if len(obj) == 1:
return self.format(obj[0], fmt)
return '{}, {} {}'.format(
- ', '.join(self.format(obj[:-1], fmt)), self.and_,
+ ', '.join(self.format(i, fmt) for i in obj[:-1]), self.and_,
self.format(obj[-1], fmt)
... |
3ea7a61be81c0f2094d8b3b0d3a81dec267ac663 | GitSvnServer/client.py | GitSvnServer/client.py |
import parse
import generate as gen
from repos import find_repos
from errors import *
def parse_client_greeting(msg_str):
msg = parse.msg(msg_str)
proto_ver = int(msg[0])
client_caps = msg[1]
url = parse.string(msg[2])
print "ver: %d" % proto_ver
print "caps: %s" % client_caps
print "url... |
import parse
import generate as gen
from repos import find_repos
from errors import *
server_capabilities = [
'edit-pipeline', # This is required.
'svndiff1', # We support svndiff1
'absent-entries', # We support absent-dir and absent-dir editor commands
#'commit-revprops', # We don't curr... | Sort out the server announce message | Sort out the server announce message
Tidy up the server announce message a bit. In particular, we might as
well announce the absent-entries capability - we support the commands
even if they currently aren't implemented.
| Python | bsd-3-clause | slonopotamus/git_svn_server | ---
+++
@@ -3,6 +3,15 @@
import generate as gen
from repos import find_repos
from errors import *
+
+server_capabilities = [
+ 'edit-pipeline', # This is required.
+ 'svndiff1', # We support svndiff1
+ 'absent-entries', # We support absent-dir and absent-dir editor commands
+ #'commit-revp... |
cbae1dafb07fda5afcd0f2573c81b6eeb08e6e20 | dependencies.py | dependencies.py | import os, pkgutil, site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo a... | import os
import pkgutil
import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please ... | Exit program if exception is raised | Exit program if exception is raised
| Python | mit | Kane610/axis | ---
+++
@@ -1,4 +1,6 @@
-import os, pkgutil, site
+import os
+import pkgutil
+import site
if pkgutil.find_loader("gi"):
try:
@@ -9,6 +11,7 @@
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
+ return False
print... |
20547b8cb6d530be7a41e1a49cb526dbbaab8330 | override_settings/tests.py | override_settings/tests.py | from django.conf import settings
from django.test import TestCase
from override_settings import (
override_settings, SETTING_DELETED, with_apps, without_apps)
@override_settings(FOO="abc")
class TestOverrideSettingsDecoratedClass(TestCase):
"""
Provide a decorated class.
"""
def test_override_setti... | Write a full test suite for override_settings | Write a full test suite for override_settings
| Python | bsd-3-clause | edavis/django-override-settings | ---
+++
@@ -0,0 +1,88 @@
+from django.conf import settings
+from django.test import TestCase
+from override_settings import (
+ override_settings, SETTING_DELETED, with_apps, without_apps)
+
+@override_settings(FOO="abc")
+class TestOverrideSettingsDecoratedClass(TestCase):
+ """
+ Provide a decorated class.... | |
463ff7bc6571a60c79795992cca9ae40e03dd681 | gmn/src/d1_gmn/app/context_processors.py | gmn/src/d1_gmn/app/context_processors.py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | Add dynamic links to GMN home page from 404 and 500 HTML templates | Add dynamic links to GMN home page from 404 and 500 HTML templates
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | ---
+++
@@ -34,4 +34,3 @@
return {
'BASE_URL': django.conf.settings.BASE_URL,
}
- |
428c62ed4b10ba5714e2a0b718cd3f52e0376bc1 | feedhq/feeds/tasks.py | feedhq/feeds/tasks.py | from django.conf import settings
from django.db import connection
from ..tasks import raven
@raven
def update_feed(feed_url, use_etags=True):
from .models import UniqueFeed
UniqueFeed.objects.update_feed(feed_url, use_etags)
close_connection()
@raven
def read_later(entry_pk):
from .models import En... | from django.conf import settings
from django.db import connection
from ..tasks import raven
@raven
def update_feed(feed_url, use_etags=True):
from .models import UniqueFeed
UniqueFeed.objects.update_feed(feed_url, use_etags)
close_connection()
@raven
def read_later(entry_pk):
from .models import En... | Update favicon on UniqueFeed update | Update favicon on UniqueFeed update
| Python | bsd-3-clause | rmoorman/feedhq,feedhq/feedhq,vincentbernat/feedhq,rmoorman/feedhq,rmoorman/feedhq,vincentbernat/feedhq,feedhq/feedhq,feedhq/feedhq,rmoorman/feedhq,feedhq/feedhq,feedhq/feedhq,vincentbernat/feedhq,vincentbernat/feedhq,rmoorman/feedhq,vincentbernat/feedhq | ---
+++
@@ -20,7 +20,7 @@
@raven
def update_unique_feed(feed_url):
- from .models import UniqueFeed, Feed
+ from .models import UniqueFeed, Feed, Favicon
feed, created = UniqueFeed.objects.get_or_create(
url=feed_url,
defaults={'subscribers': 1},
@@ -28,6 +28,7 @@
if not created:... |
9dc90727df23e655e5c921ca84cb98b7d5ae5eb2 | example_game.py | example_game.py | from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
| from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
| Remove now unnecessary quit() method from ExampleGame | Remove now unnecessary quit() method from ExampleGame
| Python | mit | AndyDeany/pygame-template | ---
+++
@@ -8,6 +8,3 @@
def draw(self):
pass
-
- def quit(self):
- pass |
ee884a9cbaaaf7693e8d980d26cca480b9d1291e | app/models/__init__.py | app/models/__init__.py | """
Initialisation file for models directory.
The application SQLite database model is setup in SQLObject.
The db model structure is:
* Place
- contains records of all Places
* Supername -> Continent -> Country -> Town
- These tables are linked to each other in a hiearchy such that a
Supername has... | """
Initialisation file for models directory.
"""
# Create an _`_all__` list here, using values set in other application files.
from .places import __all__ as placesModel
from .trends import __all__ as trendsModel
from .tweets import __all__ as tweetsModel
from .cronJobs import __all__ as cronJobsModel
__all__ = places... | Add tweets model to models init file, for db setup to see it. | Add tweets model to models init file, for db setup to see it.
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | ---
+++
@@ -1,37 +1,15 @@
"""
Initialisation file for models directory.
+"""
+# Create an _`_all__` list here, using values set in other application files.
+from .places import __all__ as placesModel
+from .trends import __all__ as trendsModel
+from .tweets import __all__ as tweetsModel
+from .cronJobs import __all... |
2352f18400d5b4b36052e04804bd04e32b000cc4 | streak-podium/render.py | streak-podium/render.py | import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
... | import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
... | Add links to profiles and clean up chart options | Add links to profiles and clean up chart options
| Python | mit | jollyra/hubot-commit-streak,supermitch/streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-streak-podium | ---
+++
@@ -10,8 +10,11 @@
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
- chart = pygal.HorizontalStackedBar(show_legend=False,
- print_values=True, print_zeroes=False,
+ chart ... |
e02dabde2ea898847ec61cc966e29a52e27f71cd | example_storage.py | example_storage.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | Fix a broken constant name, should be CLOUDFILES_UK. | Fix a broken constant name, should be CLOUDFILES_UK.
git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@1101075 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | techhat/libcloud,ninefold/libcloud,smaffulli/libcloud,wrigri/libcloud,lochiiconnectivity/libcloud,lochiiconnectivity/libcloud,Kami/libcloud,StackPointCloud/libcloud,schaubl/libcloud,mistio/libcloud,briancurtin/libcloud,briancurtin/libcloud,Cloud-Elasticity-Services/as-libcloud,SecurityCompass/libcloud,wrigri/libcloud,s... | ---
+++
@@ -18,7 +18,7 @@
from libcloud.storage.types import Provider
from libcloud.storage.providers import get_driver
-CloudFiles = get_driver(Provider.CLOUDFILES)
+CloudFiles = get_driver(Provider.CLOUDFILES_UK)
driver = CloudFiles('access key id', 'secret key')
|
08331a081713f880d5eca4fb7b18f4c61e360132 | tests/skipif_markers.py | tests/skipif_markers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | Revert skipif markers to use correct reasons (bug fixed in pytest) | Revert skipif markers to use correct reasons (bug fixed in pytest)
| Python | bsd-3-clause | hackebrot/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,dajose/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecut... | ---
+++
@@ -26,14 +26,10 @@
else:
no_network = True
-# For some reason pytest incorrectly uses the first reason text regardless of
-# which condition matches. Using a unified message for now
-# travis_reason = 'Works locally with tox but fails on Travis.'
-# no_network_reason = 'Needs a network connection to ... |
022bbf819b3c4a14ade4100102d251eceb84c637 | tests/test_bijection.py | tests/test_bijection.py | """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 i... | """Test bijection class."""
import pytest
from collections_extended.bijection import bijection
def test_bijection():
"""General tests for bijection."""
b = bijection()
assert len(b) == 0
b['a'] = 1
assert len(b) == 1
assert b['a'] == 1
assert b.inverse[1] == 'a'
assert 'a' in b
assert 1 not in b
assert 1 i... | Add test for bijection init from list of pairs | Add test for bijection init from list of pairs
| Python | apache-2.0 | mlenzen/collections-extended | ---
+++
@@ -28,3 +28,7 @@
assert 'b' in b
assert b['b'] == 1
assert 'a' not in b
+
+
+def test_init_from_pairs():
+ assert bijection({'a': 1, 'b': 2}) == bijection((('a', 1), ('b', 2))) |
7f9a31a03e68e1d9dc6f420c6aa157e657da4157 | apps/core/templatetags/files.py | apps/core/templatetags/files.py | from pathlib import Path
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def filename(path):
"""Removes traceback lines from a string (if any). It has no effect when
no 'Traceback' pattern has been found.
R... | from pathlib import Path
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def filename(path):
"""Removes parent path from a relative or absolute filename
Returns: the filename
"""
return Path(path).name
| Fix filename template tag docstring | Fix filename template tag docstring
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | ---
+++
@@ -9,9 +9,8 @@
@register.filter
@stringfilter
def filename(path):
- """Removes traceback lines from a string (if any). It has no effect when
- no 'Traceback' pattern has been found.
+ """Removes parent path from a relative or absolute filename
- Returns: raws before the 'Traceback' pattern
+... |
746df42ff459c52690a5cf8c786a6d91edee7151 | heroku_settings.py | heroku_settings.py | import os
DEBUG = True
ASSETS_DEBUG = True
# GRANO_HOST = 'http://localhost:5000'
# GRANO_APIKEY = '7a65f180d7b898822'
# GRANO_PROJECT = 'kompromatron_C'
GRANO_HOST = os.environ.get('GRANO_HOST', 'http://beta.grano.cc/')
GRANO_APIKEY = os.environ.get('GRANO_APIKEY')
GRANO_PROJECT = os.environ.get('GRANO_PROJECT', 'k... | import os
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ASSETS_DEBUG = os.environ.get('ASSET_DEBUG', 'False') == 'True'
# GRANO_HOST = 'http://localhost:5000'
# GRANO_APIKEY = '7a65f180d7b898822'
# GRANO_PROJECT = 'kompromatron_C'
GRANO_HOST = os.environ.get('GRANO_HOST', 'http://beta.grano.cc/')
GRANO_APIKEY =... | Make heroku debug settings environ dependent | Make heroku debug settings environ dependent | Python | mit | pudo/kompromatron,pudo/kompromatron | ---
+++
@@ -1,7 +1,7 @@
import os
-DEBUG = True
-ASSETS_DEBUG = True
+DEBUG = os.environ.get('DEBUG', 'False') == 'True'
+ASSETS_DEBUG = os.environ.get('ASSET_DEBUG', 'False') == 'True'
# GRANO_HOST = 'http://localhost:5000'
# GRANO_APIKEY = '7a65f180d7b898822' |
8a5d111b5c77ae9f7478dd7e73eca292c441d3fa | website_event_excerpt_img/__openerp__.py | website_event_excerpt_img/__openerp__.py | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"web... | # -*- coding: utf-8 -*-
# © 2016 Antiun Ingeniería S.L. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Excerpt + Image in Events",
"summary": "New layout for event summary, including an excerpt and image",
"version": "8.0.1.0.0",
"category": "Website",
"web... | Update module name as changed in last module version. | Update module name as changed in last module version.
| Python | agpl-3.0 | open-synergy/event,open-synergy/event | ---
+++
@@ -13,7 +13,7 @@
"installable": True,
"depends": [
"website_event",
- "html_imgs",
+ "html_image_url_extractor",
"html_text",
],
"data": [ |
52c359c1348b9c21f7c47917d024d7c161652b43 | webapp/thing_test.py | webapp/thing_test.py | #!/usr/bin/env python
from thing import PiThing
# Instantiate a PiThing
pi_thing = PiThing()
# Get the current switch state
switch = pi_thing.read_switch()
print('Switch: {0}'.format(switch))
| #!/usr/bin/env python
from thing import PiThing
# Instantiate a PiThing
pi_thing = PiThing()
# Get the current switch state
switch = pi_thing.read_switch()
print('Switch: {0}'.format(switch))
# Blink the LED forever.
print('Blinking LED (Ctrl-C to stop)...')
while True:
pi_thing.set_led(True)
time.sleep(0.... | Add blink LED. TODO: Test on raspberry pi hardware. | Add blink LED. TODO: Test on raspberry pi hardware.
| Python | mit | beepscore/pi_thing,beepscore/pi_thing,beepscore/pi_thing | ---
+++
@@ -9,3 +9,11 @@
# Get the current switch state
switch = pi_thing.read_switch()
print('Switch: {0}'.format(switch))
+
+# Blink the LED forever.
+print('Blinking LED (Ctrl-C to stop)...')
+while True:
+ pi_thing.set_led(True)
+ time.sleep(0.5)
+ pi_thing.set_led(False)
+ time.sleep(0.5) |
ba6c2ba95f4d0ab8a6c153a617aa5d1c789318a5 | numpy/distutils/command/install.py | numpy/distutils/command/install.py |
from distutils.command.install import *
from distutils.command.install import install as old_install
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
|
import os
from distutils.command.install import *
from distutils.command.install import install as old_install
from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
def ru... | Fix bdist_rpm for path names containing spaces. | Fix bdist_rpm for path names containing spaces.
| Python | bsd-3-clause | empeeu/numpy,sonnyhu/numpy,dimasad/numpy,MaPePeR/numpy,tynn/numpy,dch312/numpy,stefanv/numpy,felipebetancur/numpy,ssanderson/numpy,MichaelAquilina/numpy,musically-ut/numpy,behzadnouri/numpy,ContinuumIO/numpy,madphysicist/numpy,mwiebe/numpy,stuarteberg/numpy,mwiebe/numpy,ChristopherHogan/numpy,rgommers/numpy,madphysicis... | ---
+++
@@ -1,9 +1,34 @@
+import os
from distutils.command.install import *
from distutils.command.install import install as old_install
+from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_... |
64dbe1d931edd38b4d731db18408e337d39e42c3 | cab/admin.py | cab/admin.py | from django.contrib import admin
from cab.models import Language, Snippet, SnippetFlag
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
class SnippetAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'rating_score', 'pub_date')
list_filter = ('language',)
... | from django.contrib import admin
from cab.models import Language, Snippet, SnippetFlag
class LanguageAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ['name']}
class SnippetAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'rating_score', 'pub_date')
list_filter = ('language',)
... | Use raw_id_fields for users and snippets. | Use raw_id_fields for users and snippets.
| Python | bsd-3-clause | django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org | ---
+++
@@ -12,12 +12,14 @@
list_filter = ('language',)
date_hierarchy = 'pub_date'
search_fields = ('author__username', 'title', 'description', 'code',)
+ raw_id_fields = ('author',)
class SnippetFlagAdmin(admin.ModelAdmin):
list_display = ('snippet', 'flag')
list_filter = ('flag',)
... |
cb2cafc809481748ec64aa8ef9bfa3cc29660a6d | install_deps.py | install_deps.py | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... | Correct for None appearing in requirements list | Correct for None appearing in requirements list
| Python | bsd-3-clause | Neurita/darwin | ---
+++
@@ -24,7 +24,7 @@
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
- return install_deps
+ return [dep for dep in install_deps if dep != 'None']
if __name__ == '__main__':
@@ -36,9 +36,6 @@
try:
for dep_name in deps:
- if dep_... |
fa92a5ff237abc0c3de169bac7784e48caa152dd | clean_lxd.py | clean_lxd.py | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_out... | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
from dateutil import (
parser as date_parser,
tz,
)
def list_old_juju_containers(hours):
env = ... | Use dateutil to calculate age of container. | Use dateutil to calculate age of container. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -11,19 +11,22 @@
import subprocess
import sys
+from dateutil import (
+ parser as date_parser,
+ tz,
+ )
+
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
- now ... |
d360d4e5af09c5c194db783c4344aef10367b7f3 | kolla/cmd/build.py | kolla/cmd/build.py | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software... | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software... | Change the search path to look locally | Change the search path to look locally
In order to use tools/build.py, we need to search
locally for imports.
Closes-bug: #1592030
Change-Id: Idfa651c1268f93366de9f4e3fa80c33be42c71c3
| Python | apache-2.0 | mandre/kolla,intel-onp/kolla,mandre/kolla,GalenMa/kolla,openstack/kolla,stackforge/kolla,coolsvap/kolla,openstack/kolla,stackforge/kolla,dardelean/kolla-ansible,dardelean/kolla-ansible,dardelean/kolla-ansible,mrangana/kolla,rahulunair/kolla,nihilifer/kolla,intel-onp/kolla,rahulunair/kolla,nihilifer/kolla,mrangana/kolla... | ---
+++
@@ -11,6 +11,14 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+
+import os
+import sys
+
+PROJECT_ROOT = os.path.abspath(os.path.join(
+ os.path.dirname(os.path.realpath... |
903f958fbdfc0f7a2f0e1d863907488f9a88cad3 | prophyle/prophyle_validate_tree.py | prophyle/prophyle_validate_tree.py | #! /usr/bin/env python3
"""Test whether given Newick/NHX trees are valid for ProPhyle.
Author: Karel Brinda <kbrinda@hsph.harvard.edu>
Licence: MIT
Example:
$ prophyle_validate_tree.py ~/prophyle/bacteria.nw ~/prophyle/viruses.nw
"""
import os
import sys
import argparse
sys.path.append(os.path.dirname(__file__)... | #! /usr/bin/env python3
"""Test whether given Newick/NHX trees are valid for ProPhyle.
Author: Karel Brinda <kbrinda@hsph.harvard.edu>
Licence: MIT
Example:
$ prophyle_validate_tree.py ~/prophyle/bacteria.nw ~/prophyle/viruses.nw
"""
import os
import sys
import argparse
sys.path.append(os.path.dirname(__file__)... | Fix script for validating trees | Fix script for validating trees
Former-commit-id: e6409f5a586d34a3bcb03b2d55afc9b220aebe04 | Python | mit | karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle | ---
+++
@@ -37,7 +37,7 @@
for tree_fn in tree_fns:
print("Validating '{}'".format(tree_fn))
tree = pro.load_nhx_tree(tree_fn, validate=False)
- r = pro.validate_prophyle_nhx_tree(tree, verbose=True, throw_exceptions=False, output=sys.stdout)
+ r = pro.validate_prophyle_nhx_tree(tree, verbose=True, throw_exc... |
61fe996f79e34ac3f5be15213bfa2c16eccfa3ee | ptt_preproc_target.py | ptt_preproc_target.py | #!/usr/bin/env python
import json
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = 'targets'
def generate_target_from(json_path):
l.info('Generate target from {} ...'.format(json_pat... | #!/usr/bin/env python
import json
from pathlib import Path
from os import scandir
from os.path import (
join as path_join,
basename as to_basename,
splitext,
exists
)
import ptt_core
l = ptt_core.l
_TARGETS_DIR_PATH = Path('targets')
if not _TARGETS_DIR_PATH.exists():
_TARGETS_DIR_PATH.mkdir()... | Use pathlib in the target | Use pathlib in the target
| Python | mit | moskytw/mining-news | ---
+++
@@ -2,6 +2,7 @@
import json
+from pathlib import Path
from os import scandir
from os.path import (
join as path_join,
@@ -14,34 +15,35 @@
l = ptt_core.l
-_TARGETS_DIR_PATH = 'targets'
+_TARGETS_DIR_PATH = Path('targets')
+
+if not _TARGETS_DIR_PATH.exists():
+ _TARGETS_DIR_PATH.mkdir()
... |
5959bb60ca9e42d41386b2a1c672f7a1e666df0d | pybb/read_tracking.py | pybb/read_tracking.py | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(track... | Fix bug in read tracking system | Fix bug in read tracking system
| Python | bsd-3-clause | gpetukhov/pybb,gpetukhov/pybb,gpetukhov/pybb | ---
+++
@@ -12,9 +12,9 @@
tracking.topics = None
tracking.last_read = datetime.now()
tracking.save()
- #update topics if exist new post or does't exist in dict
+ #update topics if new post exists or cache entry is empty
if topic.last_post.pk > tracking.top... |
22ac4b9f8dd7d74a84585131fb982f3594a91603 | hr_family/models/hr_children.py | hr_family/models/hr_children.py | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation... | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation... | Use the same selection like employee | [IMP][hr_family] Use the same selection like employee
| Python | agpl-3.0 | xpansa/hr,Vauxoo/hr,Eficent/hr,thinkopensolutions/hr,microcom/hr,hbrunn/hr,acsone/hr,hbrunn/hr,Antiun/hr,feketemihai/hr,thinkopensolutions/hr,Antiun/hr,xpansa/hr,Endika/hr,feketemihai/hr,Endika/hr,open-synergy/hr,VitalPet/hr,microcom/hr,Vauxoo/hr,VitalPet/hr,open-synergy/hr,Eficent/hr,acsone/hr | ---
+++
@@ -21,8 +21,8 @@
from openerp import models, fields
-GENDER_SELECTION = [('m', 'M'),
- ('f', 'F')]
+GENDER_SELECTION = [('male', 'Male'),
+ ('female', 'Female')]
class HrChildren(models.Model): |
ead2f795480ae7e671c93550e55cf9e106b2f306 | hubblestack_nova/pkgng_audit.py | hubblestack_nova/pkgng_audit.py | # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
__tags__ = None
def __virtual__():
if 'FreeBSD' not in __grai... | # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def __virtual__():
if 'FreeBSD' not in __grains__['os']:
... | Update frebsd-pkg-audit to rely on yaml data and take data from hubble.py | Update frebsd-pkg-audit to rely on yaml data and take data from hubble.py
| Python | apache-2.0 | HubbleStack/Nova,avb76/Nova,SaltyCharles/Nova,cedwards/Nova | ---
+++
@@ -12,22 +12,28 @@
log = logging.getLogger(__name__)
-__tags__ = None
-
def __virtual__():
if 'FreeBSD' not in __grains__['os']:
return False, 'This audit module only runs on FreeBSD'
- global __tags__
- __tags__ = ['freebsd-pkg-audit']
return True
-def audit(tags, verbos... |
5d448435477ce94273051b8351275d8c18838b8b | icekit/utils/fluent_contents.py | icekit/utils/fluent_contents.py | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, page, ... | from django.contrib.contenttypes.models import ContentType
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
def create_content_instance(content_plugin_class, test_p... | Change argument name to stop probable name clash. | Change argument name to stop probable name clash.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -4,12 +4,12 @@
# USEFUL FUNCTIONS FOR FLUENT CONTENTS #############################################################
# Fluent Contents Helper Functions #################################################################
-def create_content_instance(content_plugin_class, page, placeholder_name='main', **kw... |
2c652df7f7ec93ecad0eb23094f12c6acd86256c | python/hello.py | python/hello.py | #!/usr/bin/env python2
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___:... | #!/usr/bin/env python2
print 'Hello, World!'
| Fix that damn obfuscated python | Fix that damn obfuscated python
| Python | mit | natemara/super-important-project,natemara/super-important-project | ---
+++
@@ -1,43 +1,2 @@
#!/usr/bin/env python2
-(lambda _, __, ___, ____, _____, ______, _______, ________:
- getattr(
- __import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
- ().__class__.__eq__.__class__.__name__[:__] +
- ().__iter__().__class__.__name__[_____:________]
- ... |
8e3b686b413af1340ba1641b65d237791704e117 | protocols/views.py | protocols/views.py | from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from .forms import ProtocolForm, TopicFormSet
def can_add_protocols(user):
return user.is_authenticated() and user.has_perm('protocols.add_protocol')
@user_passes_test(can_add_protoco... | from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from .forms import ProtocolForm, TopicFormSet
def can_add_protocols(user):
return user.is_authenticated() and user.has_perm('protocols.add_protocol')
@user_passes_test(can_add_protoco... | Add method listing all the protocols | Add method listing all the protocols
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -21,3 +21,7 @@
topic_form.save()
return render(request, 'protocols/add.html', locals())
+
+def list_all_protocols(request):
+ protocols = Protocol.objects.all()
+ return render(request, 'protocols/list.html', locals()) |
93c4039bff64b86e203f8ae3c3c576343cc146c0 | stock_request_picking_type/models/stock_request_order.py | stock_request_picking_type/models/stock_request_order.py | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | Set Picking Type in Create | [IMP] Set Picking Type in Create
[IMP] Flake8
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse | ---
+++
@@ -28,3 +28,13 @@
('warehouse_id', '=', self.warehouse_id.id)], limit=1)
if picking_type_id:
self._origin.write({'picking_type_id': picking_type_id.id})
+
+ @api.model
+ def create(self, vals):
+ if vals.get('warehouse_id', False):
+ ... |
dc54aad6813f5ef1828f4706d87eab9f91af1c5a | pronto/serializers/obo.py | pronto/serializers/obo.py | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... | Fix OBO serializer assuming `Ontology._terms` is properly ordered | Fix OBO serializer assuming `Ontology._terms` is properly ordered
| Python | mit | althonos/pronto | ---
+++
@@ -22,14 +22,16 @@
file.write(b"\n")
# dump terms
if self.ont._terms:
- for i, (id, data) in enumerate(self.ont._terms.items()):
+ for i, id in enumerate(sorted(self.ont._terms)):
+ data = self.ont._terms[id]
... |
47d329691e11ea332c17931ca40a822de788acfb | sanic_sentry.py | sanic_sentry.py | import logging
import sanic
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
self.init_app(app)
def init_... | import logging
import sanic
from sanic.log import logger
import raven
import raven_aiohttp
from raven.handlers.logging import SentryHandler
class SanicSentry:
def __init__(self, app=None):
self.app = None
self.handler = None
self.client = None
if app is not None:
self... | Fix to work on Sanic 0.7 | Fix to work on Sanic 0.7
Sanic 0.7 changed the logger name and is now using the 'root' logger (instead of 'sanic').
I think it is better to import it directly from Sanic than to use `logging.getLogger` to avoid this kind of problem in the future... | Python | mit | serathius/sanic-sentry | ---
+++
@@ -1,6 +1,7 @@
import logging
import sanic
+from sanic.log import logger
import raven
import raven_aiohttp
@@ -21,7 +22,6 @@
transport=raven_aiohttp.AioHttpTransport,
)
self.handler = SentryHandler(client=self.client, level=app.config.get('SENTRY_LEVEL', logging.ERROR))... |
aee26ebb12ddcc410ad1b0eccf8fd740c6b9b39a | demo.py | demo.py | if __name__ == '__main__':
from NeuroIO import NeuroIO
from PreProcess import PreProcess
from Cluster import Cluster
neuroread = NeuroIO(r"C:\Users\USERNAME\Downloads\Brainbow-demo.tif")
img_data = neuroread.img_data_return()[0]
img_path = neuroread.img_data_return()[1]
pre_processed_data =... | if __name__ == '__main__':
from NeuroIO import NeuroIO
from PreProcess import PreProcess
from Cluster import Cluster
neuroread = NeuroIO(r"C:\Users\USERNAME\Downloads\Brainbow-demo.tif")
img_data = neuroread.img_data_return()[0]
img_path = neuroread.img_data_return()[1]
pre_processed_data =... | Enable support for the parallel dbscan. | Enable support for the parallel dbscan.
| Python | apache-2.0 | aluo-x/GRIDFIRE | ---
+++
@@ -6,15 +6,15 @@
neuroread = NeuroIO(r"C:\Users\USERNAME\Downloads\Brainbow-demo.tif")
img_data = neuroread.img_data_return()[0]
img_path = neuroread.img_data_return()[1]
- pre_processed_data = PreProcess(im_data=img_data, filepath=img_path, snapshotpath=r"C:\UROP\\", multiprocess=True,
- ... |
8c2db8786a0dd08c7ca039f491260f9407eb946c | dodo.py | dodo.py | # coding: utf8
DOIT_CONFIG = {'default_tasks': []}
CITEULIKE_GROUP = 19073
BIBFILE = 'docs/pyfssa.bib'
def task_download_bib():
"""Download bibliography from CiteULike group"""
return {
'actions': [' '.join([
'wget', '-O', BIBFILE,
'"http://www.citeulike.org/bibtex/group/{}?... | # coding: utf8
import os
DOIT_CONFIG = {'default_tasks': []}
CITEULIKE_GROUP = 19073
BIBFILE = 'docs/pyfssa.bib'
def task_download_bib():
"""Download bibliography from CiteULike group"""
return {
'actions': [' '.join([
'wget', '-O', BIBFILE,
'"http://www.citeulike.org/bibte... | Add task to upload documentation to github pages | Add task to upload documentation to github pages
| Python | isc | andsor/pyfssa,andsor/pyfssa | ---
+++
@@ -1,4 +1,6 @@
# coding: utf8
+
+import os
DOIT_CONFIG = {'default_tasks': []}
@@ -17,3 +19,16 @@
# 'file_dep': [CITEULIKE_COOKIES],
'targets': [BIBFILE],
}
+
+
+def task_upload_doc():
+ """Upload built html documentation to GitHub pages"""
+
+ return {
+ 'actions': ... |
a52c1669a843e8afcf629de819e8144d6832bc7b | sensors_test.py | sensors_test.py | from TSL2561 import TSL2561
from MCP9808 import MCP9808
import time
def main():
tsl = TSL2561(debug=0)
mcp = MCP9808(debug=0)
#tsl.set_gain(16)
while True:
full = tsl.read_full()
ir = tsl.read_IR()
lux = tsl.read_lux()
print("%d,%d = %d lux" % (full, ir, lux))
te... | from TSL2561 import TSL2561
from MCP9808 import MCP9808
import time
import wiringpi2 as wiringpi
def main():
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(18,2) # enable PWM mode on pin 18
tsl = TSL2561(debug=0)
mcp = MCP9808(debug=0)
#tsl.set_gain(16)
while True:
full = tsl.read_full... | Add light PWM control to test code. | Add light PWM control to test code.
| Python | mit | liffiton/ATLeS,liffiton/ATLeS,liffiton/ATLeS,liffiton/ATLeS | ---
+++
@@ -1,8 +1,12 @@
from TSL2561 import TSL2561
from MCP9808 import MCP9808
import time
+import wiringpi2 as wiringpi
+
def main():
+ wiringpi.wiringPiSetupGpio()
+ wiringpi.pinMode(18,2) # enable PWM mode on pin 18
tsl = TSL2561(debug=0)
mcp = MCP9808(debug=0)
#tsl.set_gain(16)
@@ -1... |
49645ca7f579e5499f21e2192d16f4eed1271e82 | tests/integration/cli/sync_test.py | tests/integration/cli/sync_test.py | from mock import patch
from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles ac... | from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles activate busyboxa')
... | Clean up after sync integration tests | Clean up after sync integration tests
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty | ---
+++
@@ -1,5 +1,3 @@
-from mock import patch
-
from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
@@ -10,6 +8,14 @@
self.run_command('bundles activate busyboxa')
self.run_command('up')
+ def tearDown(self):
+ super(TestSyncC... |
2643562c03f057d91a325492e4561ce7676dc6b6 | thinglang/parser/tokens/classes.py | thinglang/parser/tokens/classes.py | from thinglang.lexer.symbols import LexicalGroupEnd
from thinglang.lexer.symbols.base import LexicalIdentifier
from thinglang.lexer.symbols.functions import LexicalDeclarationConstructor
from thinglang.parser.tokens import DefinitionPairToken, BaseToken
from thinglang.parser.tokens.functions import ArgumentList
class... | from thinglang.lexer.symbols import LexicalGroupEnd
from thinglang.lexer.symbols.base import LexicalIdentifier
from thinglang.lexer.symbols.functions import LexicalDeclarationConstructor
from thinglang.parser.tokens import DefinitionPairToken, BaseToken
from thinglang.parser.tokens.functions import ArgumentList
class... | Fix value/name ambiguity in ThingDefinition | Fix value/name ambiguity in ThingDefinition
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -8,10 +8,10 @@
class ThingDefinition(DefinitionPairToken):
def __contains__(self, item):
- return any(child.value == item for child in self.children)
+ return any(child.name == item for child in self.children)
def __getitem__(self, item):
- return [child for child in sel... |
d86b537a3820b23d66b5a8d52d15ae5d11c2b34b | spacy/lang/da/__init__.py | spacy/lang/da/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .norm_exceptions import NORM_EXCEPTIONS
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .morph_rules import MORPH_RULES
from ..tag_map import TAG_MAP
from ..tokenizer_exceptions ... | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .norm_exceptions import NORM_EXCEPTIONS
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .morph_rules import MORPH_RULES
from ..tag_map import TAG_MAP
from ..tokenizer_exceptions ... | Enable morph rules for Danish | Enable morph rules for Danish
| Python | mit | explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spa... | ---
+++
@@ -22,7 +22,7 @@
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM],
BASE_NORMS, NORM_EXCEPTIONS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
- # morph_rules = MORPH_RULES
+ morph_rules = MORPH_R... |
62ea03ce0de1a0ddc0879416a93ebc82ec30ecdd | examples/flask_example/example/settings.py | examples/flask_example/example/settings.py | from example import app
app.debug = False
SECRET_KEY = 'random-secret-key'
SESSION_COOKIE_NAME = 'psa_session'
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
DEBUG_TB_INTERCEPT_REDIRECTS = False
SESSION_PROTECTION = 'strong'
| from example import app
app.debug = True
SECRET_KEY = 'random-secret-key'
SESSION_COOKIE_NAME = 'psa_session'
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
DEBUG_TB_INTERCEPT_REDIRECTS = False
SESSION_PROTECTION = 'strong'
| Set app in debug mode by default | Set app in debug mode by default
| Python | bsd-3-clause | henocdz/python-social-auth,iruga090/python-social-auth,muhammad-ammar/python-social-auth,nirmalvp/python-social-auth,merutak/python-social-auth,barseghyanartur/python-social-auth,alrusdi/python-social-auth,mrwags/python-social-auth,msampathkumar/python-social-auth,cjltsod/python-social-auth,mrwags/python-social-auth,cm... | ---
+++
@@ -1,7 +1,7 @@
from example import app
-app.debug = False
+app.debug = True
SECRET_KEY = 'random-secret-key'
SESSION_COOKIE_NAME = 'psa_session' |
2a9406968552de04c5b3fdd5796dc3693af08a07 | src/engine/file_loader.py | src/engine/file_loader.py | import os
import json
'''
data_dir = os.path.join(
os.path.split(
os.path.split(os.path.dirname(__file__))[0])[0], 'data')
'''
data_dir = os.path.join(os.environ['PORTER'], 'data')
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
elements = []
def full_path(fil... | import os
import json
data_dir = os.path.join(os.environ['PORTER'], 'data')
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
elements = []
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.ends... | Remove commented file loading code | Remove commented file loading code
| Python | mit | Tactique/game_engine,Tactique/game_engine | ---
+++
@@ -1,11 +1,6 @@
import os
import json
-'''
-data_dir = os.path.join(
- os.path.split(
- os.path.split(os.path.dirname(__file__))[0])[0], 'data')
-'''
data_dir = os.path.join(os.environ['PORTER'], 'data')
|
0c593e993cb8fb4ea6b3031454ac359efa6aaf5c | states-pelican.py | states-pelican.py | import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# I don't know how to ma... | import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__... | Move subprocess stuff to an execution module for Pelican. | Move subprocess stuff to an execution module for Pelican.
| Python | mit | lvl1/salt-formulas | ---
+++
@@ -9,9 +9,7 @@
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
- # I don't know how to make this work. But it's cool.
- #current_state = __salt__['pelican.current_state'](name)
- current_state = "cool"
+ current_state = __salt__['pelican.current_state'](name)
i... |
4530325e460d38086201573d85a9ae95fc877a4c | webvtt/exceptions.py | webvtt/exceptions.py |
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
|
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
| Add new exception for malformed captions | Add new exception for malformed captions
| Python | mit | glut23/webvtt-py,sampattuzzi/webvtt-py | ---
+++
@@ -2,3 +2,7 @@
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
+
+
+class MalformedCaptionError(Exception):
+ """Error raised when a caption is not well formatted""" |
7d9c4a9f173b856e92e5586d1b961d876fb212a4 | test/dependencies_test.py | test/dependencies_test.py | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... | Make sure test works with new API | Make sure test works with new API
| Python | mit | pharmbio/sciluigi,pharmbio/sciluigi,samuell/sciluigi | ---
+++
@@ -16,7 +16,7 @@
class TestRunTask():
def setup(self):
- self.t = sl.new_task(TestTask)
+ self.t = sl.new_task(self, TestTask, 'testtask')
def teardown(self):
self.t = None |
321258a01b735d432fcc103e17c7eb3031c6153f | scheduler.py | scheduler.py | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalina... | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
s... | Switch to a test schedule based on the environment | Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.
| Python | apache-2.0 | randsleadershipslack/destalinator,TheConnMan/destalinator,royrapoport/destalinator,underarmour/destalinator,royrapoport/destalinator,TheConnMan/destalinator,randsleadershipslack/destalinator | ---
+++
@@ -6,11 +6,17 @@
import flagger
import os
+
+# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
+if os.getenv("TEST_SCHEDULE"):
+ schedule_kwargs = {"hour": "*", "minute": "*/10"}
+else:
+ schedule_kwargs = {"hour": 4}
+
logging.basicConfig()
sched = BlockingScheduler()
-@... |
da281daf8f83b745dd128b0270dd26d80c952b9e | tests/settings.py | tests/settings.py | """
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
)
for dir in os.listdir("tests/apps"):
if o... | """
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
'django.contrib.contenttypes',
'django.... | Add missing installed apps for tests | Add missing installed apps for tests
| Python | mit | alisaifee/djlimiter,alisaifee/djlimiter | ---
+++
@@ -14,6 +14,8 @@
INSTALLED_APPS = (
'django_nose',
+ 'django.contrib.contenttypes',
+ 'django.contrib.auth'
)
for dir in os.listdir("tests/apps"):
if os.path.isfile("tests/apps/%s/urls.py" % dir): |
a7e1b1961d14306f16c97e66982f4aef5b203e0a | tests/test_acf.py | tests/test_acf.py | import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf... | import io
import os
import pytest
from steamfiles import acf
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(a... | Fix relative path not working properly 50% of the time… | Fix relative path not working properly 50% of the time…
| Python | mit | leovp/steamfiles | ---
+++
@@ -1,9 +1,9 @@
import io
+import os
import pytest
from steamfiles import acf
-test_file_name = 'tests/test_data/appmanifest_202970.acf'
-
+test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@pytest.yield_fixture
def acf_data(): |
e1bdfbb226795f4dd15fefb109ece2aa9659f421 | tests/test_ssl.py | tests/test_ssl.py | from nose.tools import assert_true, assert_false, assert_equal, \
assert_list_equal, raises
import datajoint as dj
from . import CONN_INFO
from pymysql.err import OperationalError
class TestSSL:
@staticmethod
def test_secure_connection():
result = dj.conn(**CONN_INFO, reset=Tr... | from nose.tools import assert_true, assert_false, assert_equal, \
assert_list_equal, raises
import datajoint as dj
from . import CONN_INFO
from pymysql.err import OperationalError
class TestSSL:
# @staticmethod
# def test_secure_connection():
# result = dj.conn(**CONN_INFO, re... | Disable secure test until new test rig complete. | Disable secure test until new test rig complete.
| Python | lgpl-2.1 | eywalker/datajoint-python,datajoint/datajoint-python,dimitri-yatsenko/datajoint-python | ---
+++
@@ -7,11 +7,11 @@
class TestSSL:
- @staticmethod
- def test_secure_connection():
- result = dj.conn(**CONN_INFO, reset=True).query(
- "SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1]
- assert_true(len(result) > 0)
+ # @staticmethod
+ # def test_secure_connection():... |
6eff3cc2fba257e685dadbb19dda8aa667cb799c | tests/mongodb_settings.py | tests/mongodb_settings.py |
from test_project.settings import *
DATABASES['mongo'] = {
'ENGINE' : 'django_mongodb_engine',
'NAME' : 'mutant',
'OPTIONS': {
'OPERATIONS': {
'save' : {'safe' : True},
}
}
}
SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south'}
INSTALLED_APPS.extend(['django_mongodb_engine', 'dja... |
from test_project.settings import *
DATABASES['mongo'] = {
'ENGINE' : 'django_mongodb_engine',
'NAME' : 'mutant',
'OPTIONS': {
'OPERATIONS': {
'save' : {'safe' : True},
}
}
}
SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south_adapter'}
INSTALLED_APPS.extend(['django_mongodb_engin... | Make sure to load the new mongo south adapter | Make sure to load the new mongo south adapter
| Python | mit | charettes/django-mutant | ---
+++
@@ -11,7 +11,7 @@
}
}
-SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south'}
+SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south_adapter'}
INSTALLED_APPS.extend(['django_mongodb_engine', 'djangotoolbox'])
|
96469afbd9d01b0e4f43e93a0edfd3dc84bfa2f3 | Monstr/Core/Config.py | Monstr/Core/Config.py | import ConfigParser
Config = ConfigParser.ConfigParser()
import os
print os.getcwd()
try:
Config.read('/opt/monstr/current.cfg')
except Exception as e:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):
result = {}
if section in Con... | import ConfigParser
import os
CONFIG_PATH = '/opt/monstr/current.cfg'
Config = ConfigParser.ConfigParser()
print os.getcwd()
if os.path.isfile(CONFIG_PATH):
Config.read(CONFIG_PATH)
else:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):... | Check whether current config exists usinf os and if | FIX: Check whether current config exists usinf os and if
| Python | apache-2.0 | tier-one-monitoring/monstr,tier-one-monitoring/monstr | ---
+++
@@ -1,11 +1,14 @@
import ConfigParser
+import os
+
+CONFIG_PATH = '/opt/monstr/current.cfg'
+
+
Config = ConfigParser.ConfigParser()
-
-import os
print os.getcwd()
-try:
- Config.read('/opt/monstr/current.cfg')
-except Exception as e:
+if os.path.isfile(CONFIG_PATH):
+ Config.read(CONFIG_PATH)
+else:... |
77dbd2dc061e70a414dcd509a79bdb54491274aa | src/index.py | src/index.py | """
SmartAPI Web Server Entry Point
> python index.py
"""
import os.path
from tornado.ioloop import IOLoop, PeriodicCallback
from utils.api_monitor import update_uptime_status
from utils.versioning import backup_and_refresh
import config
from biothings.web.index_base import main
from bio... | """
SmartAPI Web Server Entry Point
> python index.py
"""
import datetime
import logging
import os.path
from tornado.ioloop import IOLoop
from utils.api_monitor import update_uptime_status
from utils.versioning import backup_and_refresh
import config
from biothings.web.index_base import... | Allow accurate daily task time scheduling | Allow accurate daily task time scheduling
| Python | mit | Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI | ---
+++
@@ -5,9 +5,11 @@
"""
+import datetime
+import logging
import os.path
-from tornado.ioloop import IOLoop, PeriodicCallback
+from tornado.ioloop import IOLoop
from utils.api_monitor import update_uptime_status
from utils.versioning import backup_and_refresh
@@ -17,13 +19,25 @@
WEB_SETTINGS = Biot... |
7f109dc3e5b1d7ecacc6810aaee456359c70ad40 | validation/base.py | validation/base.py | import functools
_undefined = object()
def validator(f):
@functools.wraps(f)
def wrapper(value=_undefined, **kwargs):
required = kwargs.pop('required', True)
def validate(value_):
if value_ is None:
if required:
raise TypeError()
... | import functools
_undefined = object()
def validator(f):
@functools.wraps(f)
def wrapper(value=_undefined, **kwargs):
required = kwargs.pop('required', True)
def validate(value):
if value is None:
if required:
raise TypeError()
... | Fix name of first argument to decorated validators | Fix name of first argument to decorated validators
| Python | apache-2.0 | JOIVY/validation | ---
+++
@@ -9,8 +9,8 @@
def wrapper(value=_undefined, **kwargs):
required = kwargs.pop('required', True)
- def validate(value_):
- if value_ is None:
+ def validate(value):
+ if value is None:
if required:
raise TypeError()
... |
9272fd30c70e946bfcc003a2936f57efdaa05bd7 | bindings/jupyroot/python/JupyROOT/__init__.py | bindings/jupyroot/python/JupyROOT/__init__.py | #-----------------------------------------------------------------------------
# Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
# Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN
#-----------------------------------------------------------------------------
############################################... | #-----------------------------------------------------------------------------
# Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
# Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN
#-----------------------------------------------------------------------------
############################################... | Update logic to check for IPython | [JupyROOT] Update logic to check for IPython
To sync it with what was already introduced in ROOT/__init__.py
| Python | lgpl-2.1 | olifre/root,olifre/root,root-mirror/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,olifre/root | ---
+++
@@ -13,6 +13,13 @@
from JupyROOT.helpers import cppcompleter, utils
-if '__IPYTHON__' in __builtins__ and __IPYTHON__:
+# Check if we are in the IPython shell
+try:
+ import builtins
+except ImportError:
+ import __builtin__ as builtins # Py2
+_is_ipython = hasattr(builtins, '__IPYTHON__')
+
+if _i... |
7ef287f2bb7a783146d5360eb9729aa4e273f7d9 | passgen.py | passgen.py | #!/usr/bin/env python3
import argparse
import random
import string
import sys
def main():
# Set defaults
default_length = 10
default_seed = None
default_population = string.ascii_letters + string.digits + '!%+=.,'
# Set up and parse arguments
p = argparse.ArgumentParser(
formatter... | #!/usr/bin/env python3
import argparse
import random
import string
import sys
def main():
# Set defaults
default_length = 10
default_seed = None
default_population = string.ascii_letters + string.digits + '!%+=.,'
# Set up and parse arguments
p = argparse.ArgumentParser(
formatter... | Fix length (was 1 too short). | Fix length (was 1 too short).
| Python | unlicense | sloede/passgen | ---
+++
@@ -28,7 +28,7 @@
# Generate password
pw = ''
- for i in range(1, args.length):
+ for i in range(0, args.length):
pw += random.choice(args.population)
# Print password |
cee60151acf606a4e22a92c51066b7fb720f35a3 | application/models.py | application/models.py | """
Database Emulator for the teammetrics project
Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats
"""
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.n... | """
Database Emulator for the teammetrics project
Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats
"""
import urllib2
import logging
def extractMetrics(team, metric):
"""
Parses the data available at the url into a data structure.
"""
url = "http://blends.debian.n... | Update the API to make it more semantic. | Update the API to make it more semantic.
| Python | mit | swvist/debmetrics,swvist/debmetrics | ---
+++
@@ -15,21 +15,19 @@
ll = len(lines)
names = lines[0].split('\t')
results = list()
- for i in range (1,ll):
- data = lines[i].split('\t')
- year = data[0]
- results.append(dict());
- results[len(results)-1]["year"]=year;
- results[len(results)-1]["userdata"]=list();
+ for i in range(1,ll):
+ data ... |
5c6f6b63450651b2860e960a4fb16c787537d3ed | kcm.py | kcm.py | #!/usr/bin/env python
"""kcm.
Usage:
kcm (-h | --help)
kcm --version
kcm (init | describe | reconcile) [--conf-dir=<dir>]
kcm isolate [--conf-dir=<dir>] --pool=<pool> <command> [-- <args> ...]
Options:
-h --help Show this screen.
--version Show version.
--conf-dir=<dir> KCM configurat... | #!/usr/bin/env python
"""kcm.
Usage:
kcm (-h | --help)
kcm --version
kcm (init | describe | reconcile) [--conf-dir=<dir>]
kcm isolate [--conf-dir=<dir>] --pool=<pool> <command> [-- <args> ...]
Options:
-h --help Show this screen.
--version Show version.
--conf-dir=<dir> KCM configurat... | Fix pool names in KCM help. | Fix pool names in KCM help.
| Python | apache-2.0 | Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes,Intel-Corp/CPU-Manager-for-Kubernetes | ---
+++
@@ -13,7 +13,7 @@
-h --help Show this screen.
--version Show version.
--conf-dir=<dir> KCM configuration directory [default: /etc/kcm].
- --pool=<pool> Pool name: either INFRA, CONTROLPLANE or DATAPLANE.
+ --pool=<pool> Pool name: either infra, controlplane or dataplane.
"... |
cd5f4c65777253d265a620194f553f5f4b76881d | l10n_ch_payment_slip/report/__init__.py | l10n_ch_payment_slip/report/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | Add common in import statement | Add common in import statement
| Python | agpl-3.0 | brain-tec/l10n-switzerland,BT-jmichaud/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland | ---
+++
@@ -29,3 +29,4 @@
#
##############################################################################
from . import payment_slip_from_invoice
+from . import reports_common |
5c7b33574550d37454b4362fa0896a4dad6e98d1 | aesthetic/output/gif.py | aesthetic/output/gif.py | from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = Im... | from PIL import Image
from PIL import ImageDraw
def render(animation, out, scale=8):
images = [render_frame(colors, scale=scale) for colors in animation]
save_gif(out, *images)
def render_frame(colors, scale=8):
led_count = 53
size = (led_count * scale, scale)
im = Image.new("RGB", size, "black")
d = Im... | Optimize GIF palette (too many colors right now), better GIF timing options. | Optimize GIF palette (too many colors right now), better GIF timing options.
| Python | apache-2.0 | gnoack/aesthetic | ---
+++
@@ -22,7 +22,7 @@
return im
def save_gif(out, image, *more_images):
+ delay_ms = 1000 * 0.035
image.save(out, save_all=True,
append_images=list(more_images),
- loop=1000,
- duration=50)
+ duration=delay_ms, optimize=True) |
612810cd1acbffe925a74e005e766b09349d2606 | src/nodemgr/database_nodemgr/common.py | src/nodemgr/database_nodemgr/common.py | #
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import subprocess
class CassandraManager(object):
def __init__(self, cassandra_repair_logdir):
self.cassandra_repair_logdir = cassandra_repair_logdir
def status(self):
subprocess.Popen(["contrail-cassandra-status",
... | #
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import subprocess
class CassandraManager(object):
def __init__(self, cassandra_repair_logdir):
self.cassandra_repair_logdir = cassandra_repair_logdir
def status(self):
subprocess.Popen(["contrail-cassandra-status",
... | Fix issue with config-nodemgr and cassandra-repair listening on same port | Fix issue with config-nodemgr and cassandra-repair listening on same port
contrail-config-nodemgr spawns contrail-cassandra-repair using
subprocess.Popen and thus contrail-cassandra-repair inherits all
the fds including the listening fd. Then when contrail-config-nodemgr
is restarted/killed, contrail-cassandra-repair ... | Python | apache-2.0 | eonpatapon/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-... | ---
+++
@@ -12,10 +12,10 @@
def status(self):
subprocess.Popen(["contrail-cassandra-status",
"--log-file", "/var/log/cassandra/status.log",
- "--debug"])
+ "--debug"], close_fds=True)
def repair(self):
logdir = ... |
cb0c7ba021a3896e7ad726178bc686775829de34 | appengine/components/components/machine_provider/utils.py | appengine/components/components/machine_provider/utils.py | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from components import net
from components import utils
MACHINE_PROVIDER... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Helper functions for working with the Machine Provider."""
import logging
from google.appengine.ext import ndb
from components import net
from comp... | Allow users of the Machine Provider to specify the dev instance for API calls | Allow users of the Machine Provider to specify the dev instance for API calls
BUG=489837
Review URL: https://codereview.chromium.org/1572793002
| Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py | ---
+++
@@ -6,17 +6,31 @@
import logging
+from google.appengine.ext import ndb
+
from components import net
from components import utils
+from components.datastore_utils import config
-MACHINE_PROVIDER_API_URL = 'https://machine-provider.appspot.com/_ah/api'
-
-CATALOG_BASE_URL = '%s/catalog/v1' % MACHINE_... |
4fe55df3bb668a2eafdb65a3a31ad27ffa5dc3c2 | pytable.py | pytable.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from operator import itemgetter
import monoidal_tables as mt
from monoidal_tables import renderers
if __name__ == '__main__':
table = (mt.integer('X', itemgetter('x')) +
mt.integer('Y', itemgetter('y')) +
mt.align_center(mt... | # -*- coding: utf-8 -*-
from __future__ import print_function
from operator import itemgetter
import monoidal_tables as mt
from monoidal_tables import renderers
if __name__ == '__main__':
table = (mt.integer('X', itemgetter('x')) +
mt.set_class(mt.integer('Y', itemgetter('y')), 'col-y') +
... | Update example to show HTML class | Update example to show HTML class
| Python | bsd-3-clause | lubomir/monoidal-tables | ---
+++
@@ -10,7 +10,7 @@
if __name__ == '__main__':
table = (mt.integer('X', itemgetter('x')) +
- mt.integer('Y', itemgetter('y')) +
+ mt.set_class(mt.integer('Y', itemgetter('y')), 'col-y') +
mt.align_center(mt.column('Name', itemgetter('name'))))
data = [
... |
85feafe002dfdce67cc4b29125f656e55867d088 | telegrambot/bot_views/generic/base.py | telegrambot/bot_views/generic/base.py | from telegrambot.bot_views.generic.responses import TextResponse, KeyboardResponse
from telegram import ParseMode
import sys
import traceback
import logging
logger = logging.getLogger(__name__)
class TemplateCommandView(object):
template_text = None
template_keyboard = None
def get_context(self,... | from telegrambot.bot_views.generic.responses import TextResponse, KeyboardResponse
from telegram import ParseMode
import sys
import traceback
import logging
logger = logging.getLogger(__name__)
PY3 = sys.version_info > (3,)
class TemplateCommandView(object):
template_text = None
template_keyboard = None
... | Fix encoding bug in TemplateCommandView | Fix encoding bug in TemplateCommandView
| Python | bsd-3-clause | jlmadurga/django-telegram-bot,jlmadurga/django-telegram-bot | ---
+++
@@ -5,7 +5,7 @@
import logging
logger = logging.getLogger(__name__)
-
+PY3 = sys.version_info > (3,)
class TemplateCommandView(object):
template_text = None
@@ -22,7 +22,9 @@
# logger.debug("Text:" + str(text.encode('utf-8')))
# logger.debug("Keyboard:" + str(keyboard))
... |
444e1951950e77f2b0e35d2921026bcadff6881b | backend/breach/forms.py | backend/breach/forms.py | from django.forms import ModelForm
from breach.models import Target
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | Add form validation for victim | Add form validation for victim
| Python | mit | dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esara... | ---
+++
@@ -1,5 +1,5 @@
from django.forms import ModelForm
-from breach.models import Target
+from breach.models import Target, Victim
class TargetForm(ModelForm):
@@ -15,3 +15,11 @@
'recordscardinality',
'method'
)
+
+
+class VictimForm(ModelForm):
+ class Meta:
+ m... |
fe2ce4e21530daffacbd654790a161019dd2de83 | backend/breach/forms.py | backend/breach/forms.py | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | from django.forms import ModelForm
from breach.models import Target, Victim
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | Add form for /attack with victim id | Add form for /attack with victim id
| Python | mit | dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dim... | ---
+++
@@ -23,3 +23,11 @@
fields = (
'sourceip',
)
+
+
+class AttackForm(ModelForm):
+ class Meta:
+ model = Victim
+ fields = (
+ 'id',
+ ) |
d4398d068d4fdf6364869cd01237f53438e2674c | blinkylib/blinkytape.py | blinkylib/blinkytape.py | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... | Fix the slow-mo gradient bug by flushing BlinkyTape response on updates | Fix the slow-mo gradient bug by flushing BlinkyTape response on updates
| Python | mit | jonspeicher/blinkyfun | ---
+++
@@ -25,3 +25,4 @@
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
+ self._serial.flushInput() |
5723dbbf2dbebf349c61a00ee4ea665b4009bd18 | spur/io.py | spur/io.py | import threading
class IoHandler(object):
def __init__(self, in_out_pairs, read_all):
self._handlers = [
OutputHandler(file_in, file_out)
for file_in, file_out
in in_out_pairs
]
self._read_all = read_all
def wait(self):
handler_resul... | import threading
class IoHandler(object):
def __init__(self, in_out_pairs, read_all):
self._handlers = [
OutputHandler(file_in, file_out)
for file_in, file_out
in in_out_pairs
]
self._read_all = read_all
def wait(self):
handler_resul... | Remove references to stdout in OutputHandler | Remove references to stdout in OutputHandler
| Python | bsd-2-clause | mwilliamson/spur.py | ---
+++
@@ -21,28 +21,28 @@
class OutputHandler(object):
- def __init__(self, stdout_in, stdout_out):
- self._stdout_in = stdout_in
- self._stdout_out = stdout_out
+ def __init__(self, file_in, file_out):
+ self._file_in = file_in
+ self._file_out = file_out
self._o... |
800ffecbed76f306806642546ed949153c8414c3 | astropy/vo/samp/tests/test_hub_proxy.py | astropy/vo/samp/tests/test_hub_proxy.py | from ..hub_proxy import SAMPHubProxy
from ..hub import SAMPHubServer
from ..client import SAMPClient
class TestHubProxy(object):
def setup_method(self, method):
self.hub = SAMPHubServer(web_profile=False)
self.hub.start()
self.proxy = SAMPHubProxy()
self.proxy.connect()
def... | import os
import tempfile
from ..hub_proxy import SAMPHubProxy
from ..hub import SAMPHubServer
from ..client import SAMPClient
class TestHubProxy(object):
def setup_method(self, method):
fileobj, self.lockfile = tempfile.mkstemp()
self.hub = SAMPHubServer(web_profile=False,
... | Use temporary SAMP lock file | Use temporary SAMP lock file
| Python | bsd-3-clause | saimn/astropy,DougBurke/astropy,joergdietrich/astropy,AustereCuriosity/astropy,lpsinger/astropy,lpsinger/astropy,tbabej/astropy,kelle/astropy,tbabej/astropy,mhvk/astropy,kelle/astropy,dhomeier/astropy,larrybradley/astropy,DougBurke/astropy,larrybradley/astropy,joergdietrich/astropy,dhomeier/astropy,stargaser/astropy,as... | ---
+++
@@ -1,3 +1,6 @@
+import os
+import tempfile
+
from ..hub_proxy import SAMPHubProxy
from ..hub import SAMPHubServer
from ..client import SAMPClient
@@ -7,16 +10,28 @@
def setup_method(self, method):
- self.hub = SAMPHubServer(web_profile=False)
+ fileobj, self.lockfile = tempfile.mkst... |
9a5aee262b5a89e5a22e9e1390e23898a5373627 | byceps/util/jobqueue.py | byceps/util/jobqueue.py | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from rq imp... | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from flask ... | Fix `get_queue` call in `enqueue` | Fix `get_queue` call in `enqueue`
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps | ---
+++
@@ -13,6 +13,7 @@
from contextlib import contextmanager
+from flask import current_app
from rq import Connection, Queue
from byceps.redis import redis
@@ -32,5 +33,5 @@
def enqueue(*args, **kwargs):
"""Add the function call to the queue as a job."""
with connection():
- queue = get_... |
41139b20b78550982ee8242c18e24ad81e2d13ae | api/caching/tasks.py | api/caching/tasks.py | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
from framework.tasks.utils import logged
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = ... | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO... | Remove unused import because Travis is picky | Remove unused import because Travis is picky
| Python | apache-2.0 | emetsger/osf.io,Nesiehr/osf.io,wearpants/osf.io,amyshi188/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,abought/osf.io,amyshi188/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,adlius/osf.io,sloria/osf.io,brandonPurvi... | ---
+++
@@ -6,7 +6,6 @@
from django.conf import settings
from framework.tasks import app as celery_app
-from framework.tasks.utils import logged
logger = get_task_logger(__name__)
|
4a125d2455e1c31043c66835c60cc0e55f9990e9 | core/network.py | core/network.py | import codecs
from string import Template
import os
import networkx as nx
from networkx.readwrite import json_graph
path = os.path.dirname(os.path.abspath(__file__))
def create_network(data):
G = nx.DiGraph()
for node in data:
G.add_node( encode_utf8( node['creator'] ) )
if '___comments'... | import codecs
from string import Template
import os
import networkx as nx
from networkx.readwrite import json_graph
path = os.path.dirname(os.path.abspath(__file__))
def create_network(data):
G = nx.DiGraph()
for node in data:
G.add_node( encode_utf8( node['creator'] ) )
if '_comments' i... | Fix variable naming for comments | Fix variable naming for comments
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | ---
+++
@@ -16,8 +16,8 @@
for node in data:
G.add_node( encode_utf8( node['creator'] ) )
- if '___comments' in node:
- for comment in node['___comments']:
+ if '_comments' in node:
+ for comment in node['_comments']:
G.add_edge( encode_utf8( comment... |
0bd7c3ff4bbfe6571dbb615c7bd625ab968bfd19 | app/communication.py | app/communication.py | from networktables import NetworkTables
TABLE_NAME = 'ImageProc'
DO_WORK_NAME = 'calculate'
HORIZONTAL_DATA_NAME = 'horizontal'
VERTICAL_DATA_NAME = 'vertical'
class TableManager:
def __init__(self):
self.startup()
self.vision_table = NetworkTables.getTable(TABLE_NAME)
self.do_work = sel... | Add table manger to handle and commit changes to the table | Add table manger to handle and commit changes to the table
| Python | mit | codeinvain/object_detection,codeinvain/object_detection | ---
+++
@@ -0,0 +1,49 @@
+from networktables import NetworkTables
+
+TABLE_NAME = 'ImageProc'
+DO_WORK_NAME = 'calculate'
+HORIZONTAL_DATA_NAME = 'horizontal'
+VERTICAL_DATA_NAME = 'vertical'
+
+class TableManager:
+ def __init__(self):
+ self.startup()
+
+ self.vision_table = NetworkTables.getTable... | |
8653f2c0e63fecd5617dfa063878c846ddafcf97 | tests/test_add_language/test_update_language_list.py | tests/test_add_language/test_update_language_list.py | # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_li... | # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_li... | Add additional checks to update_language_list test | Add additional checks to update_language_list test
Also make language variable names independent of their actual values.
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -16,15 +16,20 @@
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
- kln_language_id = 'kln'
- kln_language_name = 'Klingon'
- add_lang.update_language_list(kln_language_id, kln_language_name)
+ new_language_id = 'kln'... |
13b387af53edcce78f95adc2ad96e87bb6df75e6 | beetle_preview/__init__.py | beetle_preview/__init__.py | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config['port']
self.builder = builder
def serve(self):
os.chdir(self.directory)
... | from http import server
from socketserver import TCPServer
import os
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
self.port = own_config.get('port', 5000)
self.builder = builder
def serve(self):
os.chdir(self.director... | Set up a default port of 5000 so it won't fail if you forget to specify one in config.yaml | Set up a default port of 5000 so it won't fail if you forget to specify one in config.yaml
| Python | mit | cknv/beetle-preview | ---
+++
@@ -6,7 +6,7 @@
class Server:
def __init__(self, own_config, config, builder):
self.directory = config.folders['output']
- self.port = own_config['port']
+ self.port = own_config.get('port', 5000)
self.builder = builder
def serve(self): |
a32270be3ef07fa4a8289374d779ec44f834834c | examples/chr12_plot.py | examples/chr12_plot.py | import tadtool.tad as tad
import tadtool.plot as tp
# load regions data set
regions = tad.HicRegionFileReader().regions("chr12_20-35Mb_regions.bed")
# load matrix
matrix = tad.HicMatrixFileReader().matrix("chr12_20-35Mb.matrix.txt")
# prepare plot
tad_plot = tp.TADtoolPlot(matrix, regions, norm='lin', max_dist=10000... | import tadtool.tad as tad
import tadtool.plot as tp
# load regions data set
regions = tad.HicRegionFileReader().regions("chr12_20-35Mb_regions.bed")
# load matrix
matrix = tad.HicMatrixFileReader().matrix("chr12_20-35Mb.matrix.txt")
# prepare plot
tad_plot = tp.TADtoolPlot(matrix, regions, norm='lin', max_dist=10000... | Make sure example also runs if executed as scipt | Make sure example also runs if executed as scipt
| Python | mit | vaquerizaslab/tadtool | ---
+++
@@ -12,5 +12,6 @@
fig, axes = tad_plot.plot('chr12:31000000-34000000')
# show plot
-fig.show()
+import matplotlib.pyplot as plt
+plt.show()
|
97645cf2d1dec9b59f30a460de7f142d1f6bc01b | bin/purge_database_json.py | bin/purge_database_json.py | from pymongo import MongoClient
import json
import sys
from emission.core.get_database import get_db, get_section_db
from emission.tests import common
def purgeData(userName):
Sections=get_section_db()
common.purgeData(Sections)
def purgeAllData():
db = get_db()
common.dropAllCollections(db)
if __name__ == '... | from pymongo import MongoClient
import json
import sys
from emission.core.get_database import get_db, get_section_db
import emission.tests.common as etc
def purgeAllData():
db = get_db()
etc.dropAllCollections(db)
if __name__ == '__main__':
if len(sys.argv) != 1:
print "USAGE: %s" % sys.argv[0]
exit(1)
... | Fix obsolete code + import | Fix obsolete code + import
I can now run this without anything crashing
```
C02KT61MFFT0:e-mission-server shankari$ ./e-mission-py.bash bin/purge_database_json.py localhost
USAGE: bin/purge_database_json.py
C02KT61MFFT0:e-mission-server shankari$ ./e-mission-py.bash bin/purge_database_json.py
C02KT61MFFT0:e-mission-s... | Python | bsd-3-clause | e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server | ---
+++
@@ -2,22 +2,15 @@
import json
import sys
from emission.core.get_database import get_db, get_section_db
-from emission.tests import common
-
-def purgeData(userName):
- Sections=get_section_db()
- common.purgeData(Sections)
+import emission.tests.common as etc
def purgeAllData():
db = get_db()
- co... |
3f62fb788beea1ac32d514d549fdaeaaae0f3292 | mesonbuild/scripts/__init__.py | mesonbuild/scripts/__init__.py | #!/usr/bin/env python3
# Copyright 2016 The Meson development team
# 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 appl... | # Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | Remove unneeded shebang line that was triggering some linters. | Remove unneeded shebang line that was triggering some linters.
| Python | apache-2.0 | ernestask/meson,aaronp24/meson,rhd/meson,mesonbuild/meson,centricular/meson,mesonbuild/meson,wberrier/meson,rhd/meson,mesonbuild/meson,fmuellner/meson,trhd/meson,mesonbuild/meson,MathieuDuponchelle/meson,centricular/meson,centricular/meson,QuLogic/meson,jeandet/meson,trhd/meson,MathieuDuponchelle/meson,thiblahute/meson... | ---
+++
@@ -1,5 +1,3 @@
-#!/usr/bin/env python3
-
# Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License"); |
8266b46f8710e48cf93778a90cc0c82f4f9dcbe8 | l10n_br_nfe/models/__init__.py | l10n_br_nfe/models/__init__.py | # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
f... | # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
f... | Disable import of document_cancel and document_correction | [REF] Disable import of document_cancel and document_correction
| Python | agpl-3.0 | OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil | ---
+++
@@ -10,7 +10,7 @@
from . import res_city
from . import res_config_settings
from . import cfop
-from . import document_cancel
-from . import document_correction
+# from . import document_cancel
+# from . import document_correction
from . import document_invalidate_number
from . import spec_mixin |
7805dbadd44c262223ae02d358aa251b4df5d0b0 | astropy/table/__init__.py | astropy/table/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .table import Column, Table, TableColumns, Row, MaskedColumn
from .np_utils import TableMergeError
from .operations import join, hstack, vstack
# Import routines that connect readers/writers to astropy.table
from ..io.ascii import connect
from ..io.f... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .table import Column, Table, TableColumns, Row, MaskedColumn, GroupedTable
from .np_utils import TableMergeError
from .operations import join, hstack, vstack
# Import routines that connect readers/writers to astropy.table
from ..io.ascii import conne... | Add GroupedTable to the top-level table classes | Add GroupedTable to the top-level table classes
| Python | bsd-3-clause | bsipocz/astropy,StuartLittlefair/astropy,joergdietrich/astropy,saimn/astropy,stargaser/astropy,larrybradley/astropy,lpsinger/astropy,pllim/astropy,funbaker/astropy,mhvk/astropy,joergdietrich/astropy,AustereCuriosity/astropy,funbaker/astropy,pllim/astropy,larrybradley/astropy,mhvk/astropy,AustereCuriosity/astropy,pllim/... | ---
+++
@@ -1,5 +1,5 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
-from .table import Column, Table, TableColumns, Row, MaskedColumn
+from .table import Column, Table, TableColumns, Row, MaskedColumn, GroupedTable
from .np_utils import TableMergeError
from .operations import join, hstack, vst... |
357af01554cca6197d07a4a408c02921e70a14eb | cozify/multisensor.py | cozify/multisensor.py | import time
from influxdb import InfluxDBClient
from influxdb import SeriesHelper
from . import config
# expects Cozify devices type json data
def getMultisensorData(data):
out = []
for device in data:
state=data[device]['state']
devtype = state['type']
if devtype == 'STATE_MULTI_SEN... | import time
from . import config
# expects Cozify devices type json data
def getMultisensorData(data):
out = []
for device in data:
state=data[device]['state']
devtype = state['type']
if devtype == 'STATE_MULTI_SENSOR':
name=data[device]['name']
if 'lastSeen' i... | Remove outdated imports, oops sorry. | Remove outdated imports, oops sorry.
| Python | mit | Artanicus/python-cozify,Artanicus/python-cozify | ---
+++
@@ -1,7 +1,4 @@
import time
-
-from influxdb import InfluxDBClient
-from influxdb import SeriesHelper
from . import config
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.