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 |
|---|---|---|---|---|---|---|---|---|---|---|
679ea714796fcf6f11c0f14301f95a37914fd653 | setup.py | setup.py | from setuptools import setup, find_packages
from hdx.utilities.path import script_dir_plus_file
requirements = ['ckanapi',
'colorlog',
'ndg-httpsclient',
'pyasn1',
'pyOpenSSL',
'pyaml',
'requests',
'scraper... | from setuptools import setup, find_packages
from hdx.utilities.path import script_dir_plus_file
def get_version():
version_file = open(script_dir_plus_file('version.txt', get_version))
return version_file.read().strip()
requirements = ['ckanapi',
'colorlog',
'ndg-httpsclient'... | Make download work using url filename Add user agent string | Make download work using url filename
Add user agent string
| Python | mit | OCHA-DAP/hdx-python-api | ---
+++
@@ -1,6 +1,11 @@
from setuptools import setup, find_packages
from hdx.utilities.path import script_dir_plus_file
+
+
+def get_version():
+ version_file = open(script_dir_plus_file('version.txt', get_version))
+ return version_file.read().strip()
requirements = ['ckanapi',
'colorl... |
a9c8d3331451deaaa6b156d73df951021705fd71 | setup.py | setup.py | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.6",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | Use a placeholder string instead of a README. | Use a placeholder string instead of a README.
Until I work out why README.rst isn't being included, use this.
| Python | bsd-2-clause | sujaymansingh/dudebot | ---
+++
@@ -21,6 +21,6 @@
url="https://github.com/sujaymansingh/dudebot",
license="LICENSE.txt",
description="A really simple framework for chatroom bots",
- long_description=open("README.rst").read(),
+ long_description="View the github page (https://github.com/sujaymansingh/... |
8651c367d05798323e33066c520cf8e988937a78 | setup.py | setup.py | #!/usr/bin/env python
import sys, os
sys.path.insert(0, os.path.join(os.getcwd(),'lib'))
from distutils.core import setup
import simpletal
setup(name="SimpleTAL",
version= simpletal.__version__,
description="SimpleTAL is a stand alone Python implementation of the TAL, TALES and METAL specifications used in Zope ... | #!/usr/bin/env python
import sys, os
sys.path.insert(0, os.path.join(os.getcwd(),'lib'))
from distutils.core import setup
import simpletal
setup(name="SimpleTAL",
version= simpletal.__version__,
description="SimpleTAL is a stand alone Python implementation of the TAL, TALES and METAL specifications used in Zope ... | Add download_url so the package can be located from PyPI. | Add download_url so the package can be located from PyPI.
| Python | bsd-3-clause | g2p/SimpleTAL | ---
+++
@@ -12,6 +12,7 @@
author="Colin Stewart",
author_email="colin@owlfish.com",
url="http://www.owlfish.com/software/simpleTAL/index.html",
+ download_url="http://www.owlfish.com/software/simpleTAL/download.html",
packages=[
'simpletal',
], |
33f28ad9ba7c6eeec1f85be43863ea4c7b04128f | setup.py | setup.py | from distutils.core import setup, Extension
setup (
name='PPeg',
version='0.9',
description="A Python port of Lua's LPeg pattern matching library",
url='https://bitbucket.org/pmoore/ppeg',
author='Paul Moore',
license='MIT',
classifiers=[
'Development Status :: 3 - A... | from distutils.core import setup, Extension
setup (
name='PPeg',
version='0.9',
description="A Python port of Lua's LPeg pattern matching library",
url='https://bitbucket.org/pmoore/ppeg',
author='Paul Moore',
license='MIT',
classifiers=[
'Development Status :: 3 - A... | Add lpeg.c to _ppeg.c dependencies | Add lpeg.c to _ppeg.c dependencies
| Python | mit | moreati/ppeg,moreati/ppeg | ---
+++
@@ -20,7 +20,7 @@
keywords='parsing peg grammar regex',
- ext_modules = [Extension('_ppeg', ['_ppeg.c']),
+ ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']),
Extension('_cpeg', ['_cpeg.c'])],
py_modules=[
'PythonImpl', |
e6e25b3d872d4812df8be0655eb582a301dfb51c | setup.py | setup.py | #!/usr/bin/env python
"""
Created by: Lee Bergstrand (2018)
Description: Setup for installing pygenprop.
"""
from setuptools import setup
setup(name='pygenprop',
version='0.5',
description='A python library for programmatic usage of EBI InterPro Genome Properties.',
url='https://github.com/Microme... | #!/usr/bin/env python
"""
Created by: Lee Bergstrand (2018)
Description: Setup for installing pygenprop.
"""
from setuptools import setup
setup(name='pygenprop',
version='0.5',
description='A python library for programmatic usage of EBI InterPro Genome Properties.',
url='https://github.com/Microme... | Add sqlalchemy as a dependancy. | Add sqlalchemy as a dependancy.
| Python | apache-2.0 | LeeBergstrand/pygenprop | ---
+++
@@ -19,5 +19,6 @@
install_requires=[
'Cython>=0.29',
'pandas>=0.23.4',
+ 'sqlalchemy>=1.2.18'
],
zip_safe=False) |
6c1f071876334b12f0c2f753efd42b0cd7bea135 | setup.py | setup.py | # coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | # coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | Include readme description in pypi. | Include readme description in pypi.
PiperOrigin-RevId: 426375123
| Python | apache-2.0 | google/balloon-learning-environment | ---
+++
@@ -14,10 +14,16 @@
# limitations under the License.
"""Setup file for installing the BLE."""
+import pathlib
import setuptools
+
+current_directory = pathlib.Path(__file__).parent
+description = (current_directory / 'README.md').read_text()
setuptools.setup(
name='balloon_learning_environment',
... |
93bcfe8d79e5835649239840ec3d4fd63a3a2567 | setup.py | setup.py | import os
import sys
from setuptools import setup
from setuptools.dist import Distribution
# Do this first, so setuptools installs cffi immediately before trying to do
# the below import
Distribution(dict(setup_requires='cffi'))
# Set this so the imagemagick flags will get sniffed out.
os.environ['SANPERA_BUILD'] =... | import os
import sys
from setuptools import setup
from setuptools.dist import Distribution
# Do this first, so setuptools installs cffi immediately before trying to do
# the below import
Distribution(dict(setup_requires='cffi'))
# Set this so the imagemagick flags will get sniffed out.
os.environ['SANPERA_BUILD'] =... | Make a PEP-386-compatible version number. | Make a PEP-386-compatible version number.
| Python | isc | eevee/sanpera,eevee/sanpera | ---
+++
@@ -21,7 +21,7 @@
setup(
name='sanpera',
- version='0.2pre',
+ version='0.2.dev1',
description='Image manipulation library, powered by ImageMagick',
author='Eevee',
author_email='eevee.sanpera@veekun.com', |
aca0e79216cc1e87bf70dd4cae042de8155f9893 | setup.py | setup.py | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU... | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU... | Upgrade ldap3 1.0.2 => 1.0.3 | Upgrade ldap3 1.0.2 => 1.0.3
| Python | mit | wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,PSU-OIT-ARC/django-arcutils | ---
+++
@@ -32,7 +32,7 @@
],
'ldap': [
'certifi>=2015.11.20.1',
- 'ldap3>=1.0.2',
+ 'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9', |
2e56f7674191aca7a03ede8586f2e18abb617a0b | polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py | polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py | import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
... | import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
... | Truncate address table before import, only import from one file | Truncate address table before import, only import from one file
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations | ---
+++
@@ -33,16 +33,20 @@
apps.get_app_config('pollingstations')
])
- glob_str = os.path.join(
+ cursor = connection.cursor()
+ print("clearing existing data..")
+ cursor.execute("TRUNCATE TABLE addressbase_address;")
+
+ cleaned_file_path = os.path.abspath... |
eeb9f4c01bba1df8b3946a319c5d904711ee4a18 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.23,>=2.4.2 to >=2.4.2,<2.24 | Update requests requirement from <2.23,>=2.4.2 to >=2.4.2,<2.24
Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://git... | Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -9,7 +9,7 @@
packages=find_packages(),
include_package_data=True,
install_requires=[
- 'requests>=2.4.2,<2.23',
+ 'requests>=2.4.2,<2.24',
'future>=0.16,<0.19',
'python-magic>=0.4,<0.5',
'redo>=1.7', |
6d1ba5e05c68dfe03676cd5a572bdf9107c18cb5 | setup.py | setup.py | from os.path import abspath, dirname, join, normpath
from setuptools import find_packages, setup
setup(
# Basic package information:
name = 'django-twilio',
version = '0.2',
packages = find_packages(),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package de... | from os.path import abspath, dirname, join, normpath
from setuptools import find_packages, setup
setup(
# Basic package information:
name = 'django-twilio',
version = '0.2',
packages = find_packages(),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package de... | Allow use latest version on twilio-python library. | Allow use latest version on twilio-python library.
| Python | unlicense | rdegges/django-twilio,aditweb/django-twilio | ---
+++
@@ -15,7 +15,7 @@
include_package_data = True,
# Package dependencies:
- install_requires = ['twilio==3.3.6', 'Django>=1.3.1'],
+ install_requires = ['twilio>=3.3.6', 'Django>=1.3.1'],
# Metadata for PyPI:
author = 'Randall Degges', |
3ebcbafdaff070b2157b5fb065da9a950ba58d1c | django_rq/settings.py | django_rq/settings.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .queues import get_unique_connection_configs
SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False)
QUEUES = getattr(settings, 'RQ_QUEUES', None)
if QUEUES is None:
raise ImproperlyConfigured("You have to defi... | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .queues import get_unique_connection_configs
SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False)
QUEUES = getattr(settings, 'RQ_QUEUES', None)
if QUEUES is None:
raise ImproperlyConfigured("You have to defi... | Sort the queues by name, so that they are deterministic across instances of `django_rq`. | Sort the queues by name, so that they are deterministic across instances of `django_rq`.
| Python | mit | sbussetti/django-rq,lechup/django-rq,mjec/django-rq,lechup/django-rq,mjec/django-rq,1024inc/django-rq,ryanisnan/django-rq,ui/django-rq,sbussetti/django-rq,viaregio/django-rq,ui/django-rq,viaregio/django-rq,ryanisnan/django-rq,1024inc/django-rq | ---
+++
@@ -13,7 +13,7 @@
# All queues in list format so we can get them by index, includes failed queues
QUEUES_LIST = []
-for key, value in QUEUES.items():
+for key, value in sorted(QUEUES.items()):
QUEUES_LIST.append({'name': key, 'connection_config': value})
for config in get_unique_connection_configs()... |
642f3109cb9fb6179d51de7a7d5781044ff6be3b | satori.core/satori/core/__init__.py | satori.core/satori/core/__init__.py | # vim:ts=4:sts=4:sw=4:expandtab
"""The core of the system. Manages the database and operational logic. Functionality is
exposed over Thrift.
"""
import os
def manage():
from django.core.management import execute_manager
import satori.core.settings
# HACK
import django.core.management
old_fmm = ... | # vim:ts=4:sts=4:sw=4:expandtab
"""The core of the system. Manages the database and operational logic. Functionality is
exposed over Thrift.
"""
import sys
import os
def manage():
from django.core.management import execute_manager
settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sator... | Allow specification of custom settings module using DJANGO_SETTINGS_MODULE environment variable. | Allow specification of custom settings module using DJANGO_SETTINGS_MODULE environment variable.
| Python | mit | zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori | ---
+++
@@ -3,12 +3,16 @@
exposed over Thrift.
"""
+import sys
import os
def manage():
from django.core.management import execute_manager
- import satori.core.settings
+
+ settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'satori.core.settings')
+ __import__(settings_modul... |
6054f2a103639dc1da51ddd4d63777a9d728a9ba | hr/admin.py | hr/admin.py | from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('user', 'character', 'corporation', 'status', '... | from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('user', 'character', 'corporation', 'status', '... | Add searchfield Blacklists, and use count() for recommendation count | Add searchfield Blacklists, and use count() for recommendation count
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -9,7 +9,7 @@
list_filter = ('status',)
def recommendations(self, obj):
- return len(obj.recommendation_set.all())
+ return obj.recommendation_set.all().count()
recommendations.short_description = '# of Recommendations'
@@ -33,6 +33,7 @@
class BlacklistAdmin(admin.ModelAd... |
79f1f198820f74a62501fc572b2f1162eafede2e | tests.py | tests.py | #!/usr/bin/env python
"""Test UW Menu Flask application."""
import unittest
from uwmenu import app, attach_filters
class UWMenuTestCase(unittest.TestCase):
def setUp(self):
attach_filters()
app.config['TESTING'] = True
self.app = app.test_client()
def tearDown(self):
pass
... | #!/usr/bin/env python
"""Test UW Menu Flask application."""
import json
import unittest
from uwmenu import app, attach_filters
class UWMenuTestCase(unittest.TestCase):
def setUp(self):
attach_filters()
app.config['TESTING'] = True
self.app = app.test_client()
def tearDown(self):
... | Add test for API endpoint | Add test for API endpoint
| Python | mit | alykhank/FoodMenu,alykhank/FoodMenu,alykhank/FoodMenu | ---
+++
@@ -2,6 +2,7 @@
"""Test UW Menu Flask application."""
+import json
import unittest
from uwmenu import app, attach_filters
@@ -27,6 +28,11 @@
rv = self.app.get('/')
assert 'This is an open source application available on GitHub' in rv.data
+ def test_api_endpoint(self):
+ ... |
e7f923488ebf589aa78f7dc37792ffba3fffd2a3 | pyinfra_kubernetes/defaults.py | pyinfra_kubernetes/defaults.py | DEFAULTS = {
# Install
'kubernetes_version': None, # must be provided
'kubernetes_download_base_url': 'https://dl.k8s.io',
'kubernetes_install_dir': '/usr/local/kubernetes',
'kubernetes_bin_dir': '/usr/local/bin',
'kubernetes_conf_dir': '/etc/kubernetes',
# Config
'kubernetes_service_c... | DEFAULTS = {
# Install
'kubernetes_version': None, # must be provided
'kubernetes_download_base_url': 'https://dl.k8s.io',
'kubernetes_install_dir': '/usr/local/kubernetes',
'kubernetes_bin_dir': '/usr/local/bin',
'kubernetes_conf_dir': '/etc/kubernetes',
# Config
'kubernetes_service_c... | Update comment about default data. | Update comment about default data.
| Python | mit | EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes | ---
+++
@@ -8,5 +8,7 @@
# Config
'kubernetes_service_cidr': None, # must be provided
+
+ # API server URL for master components (controller-manager, scheduler)
'kubernetes_master_url': 'http://127.0.0.1',
} |
3f7ccf17528b91b0b1145ad81c3f5aad68085aa5 | varify/variants/translators.py | varify/variants/translators.py | from avocado.query.translators import Translator, registry
from modeltree.tree import trees
class AllowNullsTranslator(Translator):
"""For data sources that only apply to SNPs, this translator ensures only
SNPs are filtered down and not other types of variants.
"""
def translate(self, field, roperator... | from avocado.query.translators import Translator, registry
from modeltree.tree import trees
class AllowNullsTranslator(Translator):
"""For data sources that only apply to SNPs, this translator ensures only
SNPs are filtered down and not other types of variants.
"""
def translate(self, field, roperator... | Exclude nulls in translator when operator is range, gt, gte | Exclude nulls in translator when operator is range, gt, gte
Previously, nulls were included in all cases making it appear that null
was but 0 and infinity. Now, null is effectively treated as 0.
Signed-off-by: Don Naegely <e690a32c1e2176a2bfface09e204830e1b5491e3@gmail.com>
| Python | bsd-2-clause | chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify | ---
+++
@@ -9,11 +9,19 @@
def translate(self, field, roperator, rvalue, tree, **kwargs):
output = super(AllowNullsTranslator, self).translate(
field, roperator, rvalue, tree, **kwargs)
- # Create a null condition for this field
- null_condition = trees[tree].query_condition(
-... |
cd4534ee267bd06944dcce1fe40ee662351eb114 | test/python-swig-test.py | test/python-swig-test.py | #!/usr/bin/env python3
import deepstream
version = deepstream.version_to_string()
if deepstream.version_to_string() != "0.1.0":
raise Exception("Version mismatch; expected 0.0.1, got {}".format(version))
| #!/usr/bin/env python3
import deepstream
version = deepstream.version_to_string()
if deepstream.version_to_string() != "0.1.0":
raise ValueError("Version mismatch; expected 0.0.1, got {}".format(version))
| Use ValueError for Swig Python test | Use ValueError for Swig Python test
| Python | apache-2.0 | deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp | ---
+++
@@ -5,7 +5,7 @@
version = deepstream.version_to_string()
if deepstream.version_to_string() != "0.1.0":
- raise Exception("Version mismatch; expected 0.0.1, got {}".format(version))
+ raise ValueError("Version mismatch; expected 0.0.1, got {}".format(version))
|
02548b44a3b5de203e4a82693288ebae4037d90e | jug/__init__.py | jug/__init__.py | # -*- coding: utf-8 -*-
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software withou... | # -*- coding: utf-8 -*-
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software withou... | Add value() to jug namespace | Add value() to jug namespace
The jug namespace might need some attention.
| Python | mit | unode/jug,luispedro/jug,luispedro/jug,unode/jug | ---
+++
@@ -21,9 +21,9 @@
# THE SOFTWARE.
from __future__ import division
-from .task import TaskGenerator, Task
+from .task import TaskGenerator, Task, value
from .jug import init
from .backends import file_store, dict_store, redis_store
-__version__ = '0.5.0'
+__version__ = '0.5.9-git'
|
e57793b654ac29becb358832d83d4dea78dc1a50 | whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py | whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListProductTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-products')
... | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListProductTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-products')
... | Rebase off develop, add missing parenthesis | Rebase off develop, add missing parenthesis
| Python | apache-2.0 | iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api | ---
+++
@@ -33,5 +33,4 @@
product.modified.strftime("%I:%M %P, %d %b %Y"))
self.assertEqual(
sort(items[product.id-1]['preparations']),
- sort([prep.name for prep in product.preparations.all()])
-
+ sort([prep.name for prep in product.prepar... |
ee4faf2e1a81fe400d818a5a7337cf562c968d2e | quantecon/common_messages.py | quantecon/common_messages.py | """
Warnings Module
===============
Contains a collection of warning messages for consistent package wide notifications
"""
#-Numba-#
numba_import_fail_message = "Numba import failed. Falling back to non-optimized routine." | """
Warnings Module
===============
Contains a collection of warning messages for consistent package wide notifications
"""
#-Numba-#
numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
"This will reduce the overall performance of this package.\n... | Update warning message if numba import fails | Update warning message if numba import fails
| Python | bsd-3-clause | gxxjjj/QuantEcon.py,agutieda/QuantEcon.py,andybrnr/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,andybrnr/QuantEcon.py,gxxjjj/QuantEcon.py,QuantEcon/QuantEcon.py,dingliumath/quant-econ,mgahsan/QuantEcon.py,jviada/QuantEcon.py,dingliumath/quant-econ,agutieda/QuantEcon.py,jviada/QuantEcon.py,mgahsan/QuantEcon.p... | ---
+++
@@ -7,4 +7,7 @@
"""
#-Numba-#
-numba_import_fail_message = "Numba import failed. Falling back to non-optimized routine."
+numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
+ "This will reduce the overall performance of this package.\... |
7f0684583de39552e4117df8cd12c3e030c98f3e | securesystemslib/__init__.py | securesystemslib/__init__.py | import logging
# Configure a basic 'securesystemslib' top-level logger with a StreamHandler
# (print to console) and the WARNING log level (print messages of type
# warning, error or critical). This is similar to what 'logging.basicConfig'
# would do with the root logger. All 'securesystemslib.*' loggers default to
# ... | Configure basic securesystemslib top-level logger | Configure basic securesystemslib top-level logger
As pointed out by @FlorianVeaux in #210, securesystemslib does not
correctly initialize its loggers. As a consequence the logging
module logs a one-off "No handler could be found ..." warning when
used for the first time (only on Python 2).
The logging module then cal... | Python | mit | secure-systems-lab/securesystemslib,secure-systems-lab/securesystemslib | ---
+++
@@ -0,0 +1,11 @@
+import logging
+
+# Configure a basic 'securesystemslib' top-level logger with a StreamHandler
+# (print to console) and the WARNING log level (print messages of type
+# warning, error or critical). This is similar to what 'logging.basicConfig'
+# would do with the root logger. All 'securesy... | |
156d6f7dd56a5f2554a425fb5a001c99656e320b | semanticize/_semanticizer.py | semanticize/_semanticizer.py | import json
import subprocess
class Semanticizer:
''' Wrapper for semanticizest go implementation. '''
def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'):
''' Create an instance of Semanticizer.
Arguments:
model -- Language model created by semanticizest-dumpparse... | import json
import subprocess
class Semanticizer:
''' Wrapper for semanticizest go implementation. '''
def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'):
''' Create an instance of Semanticizer.
Arguments:
model -- Language model created by semanticizest-dumpparse... | Send json to semanticizer stdin | Send json to semanticizer stdin
| Python | apache-2.0 | semanticize/st,semanticize/st | ---
+++
@@ -29,7 +29,7 @@
- linkcount
- ngramcount
'''
- self.proc.stdin.write(sentence + '\n\n')
+ self.proc.stdin.write(json.dumps(sentence) + '\n\n')
stdoutdata = self.proc.stdout.readline()
return self._responseGenerator(stdoutdata)
|
b0237011251815e883b4fa60839dafd513907227 | forum/templatetags/forum_extras.py | forum/templatetags/forum_extras.py | from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
... | from django import template
from django.urls import reverse
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
... | Add formatting to post tree | Add formatting to post tree
| Python | mit | Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano | ---
+++
@@ -1,4 +1,5 @@
from django import template
+from django.urls import reverse
from django.utils.safestring import mark_safe
@@ -20,7 +21,15 @@
except IndexError:
pass
- html += ' ' * depth + '<li>' + post.subject
+ html += '<li><a href="{url}">{title}</a> by {user} ... |
cd91c7f1db5c2462127a76dd9957c36017ac06cd | tests/run_tests.py | tests/run_tests.py | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | Fix a platform detection bug | Fix a platform detection bug
| Python | bsd-3-clause | Zephor5/pika,jstnlef/pika,fkarb/pika-python3,vitaly-krugl/pika,pika/pika,Tarsbot/pika,skftn/pika,benjamin9999/pika,reddec/pika,vrtsystems/pika,zixiliuyue/pika,shinji-s/pika,hugoxia/pika,knowsis/pika,renshawbay/pika-python3 | ---
+++
@@ -40,7 +40,7 @@
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if file[:-3] in PLATFORMS:
- if platform == file[:3]:
+ if platform == file[:-3]:
run_test(file_path)
... |
375513808e3fa83ff23de942aeedbd0d9cc4d1c2 | tests/test_h5py.py | tests/test_h5py.py | import h5py
import bitshuffle.h5
import numpy
import tempfile
def test_is_h5py_correctly_installed():
"""
If this test fails you probably need to install h5py from source manually:
$ pip install --no-binary=h5py h5py
"""
f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w")
block_size = 0... | import h5py
import hdf5plugin
import numpy
import tempfile
def test_is_h5py_correctly_installed():
"""
If this test fails you probably need to install h5py from source manually:
$ pip install --no-binary=h5py h5py
"""
f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w")
block_size = 0
... | Change bitshuffle call to hdf5plugin | Change bitshuffle call to hdf5plugin
| Python | bsd-3-clause | UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy | ---
+++
@@ -1,5 +1,5 @@
import h5py
-import bitshuffle.h5
+import hdf5plugin
import numpy
import tempfile
@@ -15,9 +15,8 @@
dataset = f.create_dataset(
"data",
(100, 100, 100),
- compression=bitshuffle.h5.H5FILTER,
- compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4... |
39e00164541535db2de8c8143d8728e5624f98f9 | configuration/development.py | configuration/development.py | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')
SECRET_KEY = 'INSECURE'
MAIL_SERVER = 'localhost'
MAIL_PORT = '25'
MAIL_DEFAULT_SENDER = 'no-reply@localhost.localdomain'
del os
| import pathlib
_basedir = pathlib.Path(__file__).parents[1]
SQLALCHEMY_DATABASE_URI = (
'sqlite:///' + str(_basedir.joinpath(pathlib.PurePath('app.db')).resolve())
)
SECRET_KEY = 'INSECURE'
MAIL_SERVER = 'localhost'
MAIL_PORT = '25'
MAIL_DEFAULT_SENDER = 'no-reply@localhost.localdomain'
del pathlib
| Move the db back to the correct location | Move the db back to the correct location
| Python | agpl-3.0 | interactomix/iis,interactomix/iis | ---
+++
@@ -1,7 +1,10 @@
-import os
-_basedir = os.path.abspath(os.path.dirname(__file__))
+import pathlib
-SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')
+_basedir = pathlib.Path(__file__).parents[1]
+
+SQLALCHEMY_DATABASE_URI = (
+ 'sqlite:///' + str(_basedir.joinpath(pathlib.PurePat... |
2726404284fbae6388dbf40e01b6ad5ccf1c56a2 | knights/compiler.py | knights/compiler.py | import ast
from .context import ContextScope
from .parser import Parser
from .utils import Helpers
def kompile(src, raw=False, filename='<compiler>'):
'''
Creates a new class based on the supplied template, and returnsit.
class Template(object):
def __call__(self, context):
return ''... | import ast
from .context import ContextScope
from .parser import Parser
from .utils import Helpers
def kompile(src, raw=False, filename='<compiler>', **kwargs):
'''
Creates a new class based on the supplied template, and returnsit.
class Template(object):
def __call__(self, context):
... | Add option to print astor reconstructed source of template | Add option to print astor reconstructed source of template
| Python | mit | funkybob/knights-templater,funkybob/knights-templater | ---
+++
@@ -5,7 +5,7 @@
from .utils import Helpers
-def kompile(src, raw=False, filename='<compiler>'):
+def kompile(src, raw=False, filename='<compiler>', **kwargs):
'''
Creates a new class based on the supplied template, and returnsit.
@@ -45,6 +45,10 @@
ast.fix_missing_locations(inst)
+ ... |
70e1e6cde0c31d34cbd2a0118b3215618b84a5d9 | adhocracy4/projects/views.py | adhocracy4/projects/views.py | from django.shortcuts import redirect
from django.views import generic
from rules.contrib import views as rules_views
from . import mixins, models
class ProjectDetailView(rules_views.PermissionRequiredMixin,
mixins.PhaseDispatchMixin,
generic.DetailView):
model = ... | from django.shortcuts import redirect
from django.views import generic
from rules.contrib import views as rules_views
from . import mixins, models
class ProjectDetailView(rules_views.PermissionRequiredMixin,
mixins.PhaseDispatchMixin,
generic.DetailView):
model = ... | Remove last memberships related hooks from project | Remove last memberships related hooks from project
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 | ---
+++
@@ -16,28 +16,6 @@
def raise_exception(self):
return self.request.user.is_authenticated()
- def handle_no_permission(self):
- """
- Check if user clould join
- """
- user = self.request.user
- is_member = user.is_authenticated() and self.project.has_member... |
1f2a30f5c9ac68c53ed042ab6b5b9c365a1d0d16 | rate_limit.py | rate_limit.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright 2016 Eddie Antonio Santos <easantos@ualberta.ca>
#
# 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/licens... | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright 2016 Eddie Antonio Santos <easantos@ualberta.ca>
#
# 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/licens... | Allow for checking search rate limit. | Allow for checking search rate limit.
| Python | apache-2.0 | naturalness/sensibility,eddieantonio/ad-hoc-miner,naturalness/sensibility,naturalness/sensibility,eddieantonio/ad-hoc-miner,eddieantonio/ad-hoc-miner,naturalness/sensibility,eddieantonio/ad-hoc-miner | ---
+++
@@ -25,17 +25,20 @@
logger = logging.getLogger(__name__)
-def wait_for_rate_limit():
+def wait_for_rate_limit(resource='core'):
"""
Checks the rate limit and waits if the rate limit is beyond a certain
threshold.
"""
- limit_info = github.rate_limit()
- core = limit_info['resour... |
f20dd39fd3ae739bf6460f452a5d67bc42785adf | src/ansible/urls.py | src/ansible/urls.py | from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])),
url(r'^$', PlaybookListView... | from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
PlaybookFileView
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])),
url(r'... | Add playbook file detail view | Add playbook file detail view
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | ---
+++
@@ -2,6 +2,7 @@
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
+ PlaybookFileView
)
from . import views
@@ -9,5 +10,10 @@
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleF... |
4ecd19f7a1a36a424021e42c64fb273d7591ef1f | haas/plugin_manager.py | haas/plugin_manager.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
from .utils import find_module_by_name
... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
from .utils import get_mo... | Add logging and raise exceptions when loading plugin factories | Add logging and raise exceptions when loading plugin factories
| Python | bsd-3-clause | sjagoe/haas,itziakos/haas,sjagoe/haas,scalative/haas,itziakos/haas,scalative/haas | ---
+++
@@ -6,27 +6,44 @@
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
-from .utils import find_module_by_name
+import logging
+
+from .utils import get_module_by_name
+
+logger = logging.getLogger(__name__)
+
+
+class PluginError(E... |
83c682264582a345d4c5ada0a8fd2fd540595d1e | trex/management/commands/zeiterfassung.py | trex/management/commands/zeiterfassung.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.core.management.base import BaseCommand, CommandError
from trex.models.project import Project
from trex.utils import Zeiterfassung
class Command(BaseCommand):
... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from trex.models.project import Project
from trex.utils import Zeiterfassung
... | Allow to pass the encoding via a command option | Allow to pass the encoding via a command option
| Python | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -4,6 +4,8 @@
#
# See LICENSE comming with the source of 'trex' for details.
#
+
+from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
@@ -16,6 +18,11 @@
args = "<project> <name>"
help = "Load entries from a zeiterfassung.txt to a project"
+ ... |
da39921f94a90e330c796e0ad9ff861e9fc5a8af | examples/tutorial_pandas.py | examples/tutorial_pandas.py | import argparse
import pandas as pd
from influxdb import DataFrameClient
def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'example'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(... | import argparse
import pandas as pd
from influxdb import DataFrameClient
def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'example'
protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.Data... | Add correct protocol to the Pandas client | Add correct protocol to the Pandas client
@nicolajkirchhof Is this what you were talking about? | Python | mit | BenHewins/influxdb-python,BenHewins/influxdb-python,influxdb/influxdb-python,tzonghao/influxdb-python,tzonghao/influxdb-python,influxdata/influxdb-python,omki2005/influxdb-python,influxdb/influxdb-python,influxdata/influxdb-python,omki2005/influxdb-python | ---
+++
@@ -8,6 +8,7 @@
user = 'root'
password = 'root'
dbname = 'example'
+ protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
|
aaaa857642fa4ce2631fb47f3c929d3197037231 | falcom/generate_pageview.py | falcom/generate_pageview.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Pagetags:
default_confidence = 100
def generate_pageview (self):
return ""
def add_raw_tags (self, tag_data):
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Pagetags:
def __init__ (self):
self.default_confidence = 100
@property
def default_confidence (self):
ret... | Make default_confidence into a @property | :muscle: Make default_confidence into a @property
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -4,7 +4,16 @@
class Pagetags:
- default_confidence = 100
+ def __init__ (self):
+ self.default_confidence = 100
+
+ @property
+ def default_confidence (self):
+ return self.__default_confid
+
+ @default_confidence.setter
+ def default_confidence (self, value):
+ ... |
6f83e51dc505366187c911b90a017e0fe0531a17 | stock_planning/models/stock_move.py | stock_planning/models/stock_move.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):... | Fix condition cond.append(('date', '>=', from_date)) | [FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))
| Python | agpl-3.0 | Daniel-CA/odoomrp-wip-public,sergiocorato/odoomrp-wip,agaldona/odoomrp-wip-1,jobiols/odoomrp-wip,odoomrp/odoomrp-wip,odoomrp/odoomrp-wip,jobiols/odoomrp-wip,agaldona/odoomrp-wip-1,Daniel-CA/odoomrp-wip-public,sergiocorato/odoomrp-wip | ---
+++
@@ -16,7 +16,7 @@
('date', '<=', to_date),
('state', 'not in', ('done', 'cancel'))]
if from_date:
- cond.append(('date', '=>', from_date))
+ cond.append(('date', '>=', from_date))
if product:
cond.append(('product_id', '=',... |
86678fce3817388641db3d0f4002b3f8d409377d | pdcupdater/tests/handler_tests/test_kerberos_auth.py | pdcupdater/tests/handler_tests/test_kerberos_auth.py | import pytest
import requests_kerberos
from mock import patch, Mock
import pdcupdater.utils
from test.test_support import EnvironmentVarGuard
import os
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test... | import os
from mock import patch, Mock
import pdcupdater.utils
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'htt... | Remove invalid imports for TestKerberosAuthentication and fix its styling | Remove invalid imports for TestKerberosAuthentication and fix its styling
| Python | lgpl-2.1 | fedora-infra/pdc-updater | ---
+++
@@ -1,23 +1,22 @@
-import pytest
-import requests_kerberos
-from mock import patch, Mock
-import pdcupdater.utils
-from test.test_support import EnvironmentVarGuard
import os
+from mock import patch, Mock
+
+import pdcupdater.utils
+
+
class TestKerberosAuthentication(object):
-
- @patch('os.path.exists',... |
3d29cad334446613180e0279cb1197fab1f77764 | lib/python/setup.py | lib/python/setup.py | from sys import version
from distutils.core import setup
setup(name='mosquitto',
version='1.0.1',
description='MQTT version 3.1 client class',
author='Roger Light',
author_email='roger@atchoo.org',
url='http://mosquitto.org/',
download_url='http://mosquitto.org/files/',
license='BSD License',
py_modules=['mosq... | from sys import version
from distutils.core import setup
setup(name='mosquitto',
version='1.0.1',
description='MQTT version 3.1 client class',
author='Roger Light',
author_email='roger@atchoo.org',
url='http://mosquitto.org/',
download_url='http://mosquitto.org/files/',
license='BSD License',
py_modules=['mosq... | Add Python classifiers for PyPi. | Add Python classifiers for PyPi.
| Python | bsd-3-clause | zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto | ---
+++
@@ -9,5 +9,20 @@
url='http://mosquitto.org/',
download_url='http://mosquitto.org/files/',
license='BSD License',
- py_modules=['mosquitto']
+ py_modules=['mosquitto'],
+
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'Intended Audience :: Developers',
+ 'License :: OSI App... |
1a06f983a3edf3ee2f887c2e2094eb76820b5a73 | examples/arabic.py | examples/arabic.py | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshape... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
import os
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bid... | Fix the __file__ is not defined bug | Fix the __file__ is not defined bug
| Python | mit | amueller/word_cloud | ---
+++
@@ -12,16 +12,17 @@
pip install python-bidi arabic_reshape
"""
-from os import path
+import os
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
-d = path.dirname(__file__)
+# get data directory (using getcwd() is needed to support running ex... |
633ba35c87f62b70e0aae275519514632d33a777 | googleanalytics/__init__.py | googleanalytics/__init__.py | # encoding: utf-8
from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments
from .auth import authenticate, authorize, revoke
from .blueprint import Blueprint
| # encoding: utf-8
import pkg_resources
from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments
from .auth import authenticate, authorize, revoke
from .blueprint import Blueprint
__version__ = pkg_resources.get_distribution("googleanalytics").version | Add version number to package. | Add version number to package.
| Python | isc | debrouwere/google-analytics | ---
+++
@@ -1,5 +1,9 @@
# encoding: utf-8
+
+import pkg_resources
from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments
from .auth import authenticate, authorize, revoke
from .blueprint import Blueprint
+
+__version__ = pkg_resources.get_distribution("googleanaly... |
4e6c901140a667612fd311a2f18e1b7c18bafcd0 | tests/test_octadecane_benchmarks.py | tests/test_octadecane_benchmarks.py | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation())
def test_lid_driven_cavity_benchmark_with... | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain())
def test_h... | Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests | Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests
| Python | mit | geo-fluid-dynamics/phaseflow-fenics | ---
+++
@@ -1,12 +1,6 @@
""" This module runs the benchmark test suite. """
from .context import phaseflow
-
-def test_lid_driven_cavity_benchmark__ci__():
-
- phaseflow.helpers.run_simulation_with_temporary_output(
- phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation())
-
def... |
c3526f51afc23a4c672e86a850c4f49d094a2482 | libpb/port/__init__.py | libpb/port/__init__.py | """FreeBSD Ports."""
from __future__ import absolute_import
__all__ = ["get_port"]
class PortCache(object):
"""Caches created ports."""
def __init__(self):
"""Initialise port cache."""
self._ports = {}
self._waiters = {}
def __len__(self):
return len(self._ports)
d... | """FreeBSD Ports."""
from __future__ import absolute_import
__all__ = ["get_port", "get_ports", "ports"]
class PortCache(object):
"""Caches created ports."""
def __init__(self):
"""Initialise port cache."""
self._ports = {}
self._waiters = {}
def __len__(self):
return l... | Add ability to iterate over all currently loaded ports. | Add ability to iterate over all currently loaded ports.
This function provides a snapshot of ports and does not provide support to
query ports that are still loading.
| Python | bsd-2-clause | DragonSA/portbuilder,DragonSA/portbuilder | ---
+++
@@ -2,7 +2,7 @@
from __future__ import absolute_import
-__all__ = ["get_port"]
+__all__ = ["get_port", "get_ports", "ports"]
class PortCache(object):
@@ -37,6 +37,9 @@
attr(origin).connect(self._attr)
return signal
+ def __iter__(self):
+ return self._po... |
029d5c9f85dedbe8d1b4d41a8cb27d70652c9c1b | tools/clean_output_directory.py | tools/clean_output_directory.py | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import subprocess
import utils
def Main():
build_roo... | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import os
import shutil
import sys
import subprocess
import utils
def Main():
... | Add missing python import to utility script | Add missing python import to utility script
BUG=
R=lrn@google.com
Review URL: https://codereview.chromium.org//1226963005.
| Python | bsd-3-clause | dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart... | ---
+++
@@ -5,6 +5,7 @@
# BSD-style license that can be found in the LICENSE file.
#
+import os
import shutil
import sys
import subprocess |
335ce70414ffecbfc506ce2c22a5a7e4aeeca1a1 | sda/__init__.py | sda/__init__.py | # -*- coding: utf-8 -*-
"""sda
.. codeauthor:: John Lane <jlane@fanthreesixty.com>
"""
from sda import element
from sda import locators
from sda import mixins
from sda import page
from sda import site
from sda import structures
__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__ = "MIT"
__version... | # -*- coding: utf-8 -*-
"""sda
.. codeauthor:: John Lane <jlane@fanthreesixty.com>
"""
from sda import locators
from sda import mixins
from sda import structures
from sda.element import Element
from sda.page import Page
from sda.site import Site
__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__... | Streamline imports for Element, Page and Site | Streamline imports for Element, Page and Site
| Python | mit | jlane9/selenium_data_attributes,jlane9/selenium_data_attributes | ---
+++
@@ -5,16 +5,16 @@
"""
-from sda import element
from sda import locators
from sda import mixins
-from sda import page
-from sda import site
from sda import structures
+from sda.element import Element
+from sda.page import Page
+from sda.site import Site
__author__ = 'jlane'
__email__ = 'jlane@fanth... |
51b179a6d8d2bef2a0371c870dbc1b7b3ebc9a38 | grammpy/Grammars/Grammar.py | grammpy/Grammars/Grammar.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 16.08.2017 19:25
:Licence GNUv3
Part of grammpy
"""
from .CopyableGrammar import CopyableGrammar as _G
class Grammar(_G):
def __copy__(self):
return self.copy()
def copy(self, terminals=False, nonterminals=False, rules=False):
c = ... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 16.08.2017 19:25
:Licence GNUv3
Part of grammpy
"""
from .CopyableGrammar import CopyableGrammar as _G
class Grammar(_G):
def __copy__(self):
return self.copy()
def copy(self, terminals=False, nonterminals=False, rules=False):
c = ... | Remove method for copying rules only | Remove method for copying rules only
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -22,8 +22,5 @@
rules=list(c.new_rules),
start_symbol=c.start)
- def copy_rules(self):
- return self.copy(rules=True)
-
def __deepcopy__(self, memodict={}):
return self.copy(terminals=True, nonterminals=True, rules=True) |
56fde910c417a8d1943e5ff110327fee49cb4a6d | fineants/models.py | fineants/models.py | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
class Transaction(models.Model):
title = models.CharField("Title", max_length=255, blank=False)
creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor")
... | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
class Transaction(models.Model):
title = models.CharField("Title", max_length=255, blank=False)
creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor")
... | Add description field to transaction | Add description field to transaction
| Python | mit | n2o/FineAnts,n2o/FineAnts | ---
+++
@@ -9,4 +9,5 @@
creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor")
debitors = models.ManyToManyField(User, verbose_name="Debitors", related_name="Debitors")
amount = models.FloatField("Amount", blank=False)
+ description = models.TextField("Description", bla... |
bb319f73d16066ffae81cd1f0a7d644b7621dec7 | shcol/config.py | shcol/config.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read durin... | Use UTF-8 as default encoding. | Use UTF-8 as default encoding.
| Python | bsd-2-clause | seblin/shcol | ---
+++
@@ -9,13 +9,11 @@
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
-
-from __future__ import unicode_literals
-
import logging
import os
import sys
+ENCODING = 'utf-8'
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.std... |
edfa2547b9ad2f6e8a2f1ab547c08d5d0c702dee | pybossa_z3950/__init__.py | pybossa_z3950/__init__.py | # -*- coding: utf8 -*-
"""Main package for pybossa-z3950."""
from flask import current_app as app
from flask.ext.plugins import Plugin
from flask.ext.z3950 import Z3950Manager
__plugin__ = "PyBossaZ3950"
__version__ = "0.0.1"
class PyBossaZ3950(Plugin):
"""A PyBossa plugin for Z39.50 integration."""
def se... | # -*- coding: utf8 -*-
"""Main package for pybossa-z3950."""
from flask import current_app as app
from flask.ext.plugins import Plugin
from flask.ext.z3950 import Z3950Manager
__plugin__ = "PyBossaZ3950"
__version__ = "0.0.1"
class PyBossaZ3950(Plugin):
"""A PyBossa plugin for Z39.50 integration."""
def se... | Raise error when plugin not configured | Raise error when plugin not configured
| Python | bsd-3-clause | alexandermendes/pybossa-z3950 | ---
+++
@@ -15,7 +15,7 @@
def setup(self):
"""Setup plugin."""
try:
- if app.config.get('Z3950_DATABASES'):
+ if app.config['Z3950_DATABASES']:
Z3950Manager.init_app(app)
self.setup_blueprint()
except Exception as inst: # pragma: no cover |
fb63b49302560d4ab139c3749347edf5878a18c9 | modules/pushover.py | modules/pushover.py | import http.client
import urllib
def send_message(settings, message):
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token": settings.PUSHOVER_APP_TOKEN,
"user": settings.P... | import http.client
import urllib
def send_message(settings, message, title="Argus"):
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token": settings.PUSHOVER_APP_TOKEN,
"us... | Support for title in the notification, defaulting to 'Argus' | Support for title in the notification, defaulting to 'Argus'
| Python | apache-2.0 | aquatix/argus,aquatix/argus | ---
+++
@@ -2,12 +2,13 @@
import urllib
-def send_message(settings, message):
+def send_message(settings, message, title="Argus"):
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token"... |
68673a0c3185b9575ec031c7b7590e5bc091ccb5 | h2o-bindings/bin/gen_all.py | h2o-bindings/bin/gen_all.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results/ folder, where H2OCloud stores its logs
if not... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results folder, where H2OCloud stores its logs, and ..... | Create test-results folder, to make Jenkins happy | Create test-results folder, to make Jenkins happy
| Python | apache-2.0 | h2oai/h2o-dev,mathemage/h2o-3,mathemage/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/... | ---
+++
@@ -12,9 +12,12 @@
sys.path.insert(0, "../../scripts")
import run
-# Create results/ folder, where H2OCloud stores its logs
+# Create results folder, where H2OCloud stores its logs, and ../build/test-results where Jenkins stores its stuff
if not os.path.exists("results"):
os.mkdir("results")
+ os... |
8ee418b9a51d418901951b4f7d4cc975b203c0ed | blanc_basic_assets/listeners.py | blanc_basic_assets/listeners.py | from django.db.models.signals import pre_save, post_delete
from django.core.files.storage import default_storage
def asset_file_change(sender, instance, **kwargs):
# Must be saved already
if instance.pk is not None:
try:
old_obj = sender.objects.get(pk=instance.pk)
# Delete th... | from django.db.models.signals import post_delete, pre_save
def asset_file_change(sender, instance, **kwargs):
# Must be saved already
if instance.pk is not None:
old_obj = sender.objects.get(pk=instance.pk)
# Delete the old file if the file names don't match
if old_obj.file.name != in... | Fix file deletion if we're using remote storage | Fix file deletion if we're using remote storage
| Python | bsd-3-clause | blancltd/blanc-basic-assets | ---
+++
@@ -1,26 +1,20 @@
-from django.db.models.signals import pre_save, post_delete
-from django.core.files.storage import default_storage
+from django.db.models.signals import post_delete, pre_save
def asset_file_change(sender, instance, **kwargs):
# Must be saved already
if instance.pk is not None:... |
b04afdc4a6808029443e8107c651a24ba5f9842a | gitman/__init__.py | gitman/__init__.py | """Package for GitMan."""
from pkg_resources import get_distribution
from .commands import delete as uninstall # pylint: disable=redefined-builtin
from .commands import display as list
from .commands import init, install, lock, update
__version__ = get_distribution("gitman").version
| """Package for GitMan."""
from pkg_resources import DistributionNotFound, get_distribution
from .commands import delete as uninstall # pylint: disable=redefined-builtin
from .commands import display as list
from .commands import init, install, lock, update
try:
__version__ = get_distribution("gitman").version
e... | Handle missing distribution on ReadTheDocs | Handle missing distribution on ReadTheDocs
| Python | mit | jacebrowning/gitman | ---
+++
@@ -1,9 +1,12 @@
"""Package for GitMan."""
-from pkg_resources import get_distribution
+from pkg_resources import DistributionNotFound, get_distribution
from .commands import delete as uninstall # pylint: disable=redefined-builtin
from .commands import display as list
from .commands import init, inst... |
42f2f4453552c2c01c0a066ba800b4c92d9d06f6 | src/txacme/challenges/_http.py | src/txacme/challenges/_http.py | """
``http-01`` challenge implementation.
"""
from twisted.web.http import OK
from twisted.web.resource import Resource
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni.
... | """
``http-01`` challenge implementation.
"""
from twisted.web.resource import Resource
from twisted.web.static import Data
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni... | Make HTTP01Responder's resource be at the token's path | Make HTTP01Responder's resource be at the token's path
* Not /.well-known/acme-challenge/<token>, just /<token>
* Use twisted.web.static.Data as the child resource
| Python | mit | mithrandi/txacme | ---
+++
@@ -1,8 +1,8 @@
"""
``http-01`` challenge implementation.
"""
-from twisted.web.http import OK
from twisted.web.resource import Resource
+from twisted.web.static import Data
from zope.interface import implementer
@@ -23,25 +23,17 @@
"""
Add the child resource.
"""
- ... |
4212b35221a69468b62f933e3dbe5ffeaa9d53dc | tests/test_domain_parser.py | tests/test_domain_parser.py | import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
def test_guardian(self):
... | # -*- coding: utf-8 -*-
import unittest
from domain_parser import domain_parser
class DomainParserTestCase(unittest.TestCase):
def test_google(self):
"""Is google.com properly parsed?"""
assert domain_parser.parse_domain(
'http://www.google.com') == ('com', 'google', 'www')
d... | Add test for internationalized domain names | Add test for internationalized domain names
Test that a domain name composed entirely of non-latin characters is
parsed properly. This should always pass with Python 3 but it will fail
with Python 2 because 'parse_domain' returns 'str(second_level_domain)',
which tries to encode second_level_domain in ASCII.
| Python | apache-2.0 | jeffknupp/domain-parser,jeffknupp/domain-parser | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import unittest
from domain_parser import domain_parser
@@ -23,3 +24,9 @@
"""Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?"""
assert domain_parser.parse_domain(
'https://www.google.com') ==... |
b7175449096717dcce9d3f90dd55e341a350b47b | flask_nav/elements.py | flask_nav/elements.py | from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):... | from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
active = False
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagI... | Make all navigation items have an active attribute. | Make all navigation items have an active attribute.
| Python | mit | mbr/flask-nav,mbr/flask-nav | ---
+++
@@ -5,6 +5,8 @@
class NavigationItem(object):
+ active = False
+
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self) |
efcdeb17ec1e3afdfbdbb50a201f90c422d7cd8e | tovp/contacts/lookups.py | tovp/contacts/lookups.py | from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from .models import Person
class PersonLookup(LookupChannel):
model = Person
def get_query(self, q, request):
return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontain... | from ajax_select import LookupChannel
from django.core.exceptions import PermissionDenied
from django.utils.html import escape
from django.db.models import Q
from .models import Person
class PersonLookup(LookupChannel):
model = Person
def get_query(self, q, request):
return Person.objects.filter(Q(f... | Allow to add contact to logged in users. | Allow to add contact to logged in users.
| Python | mit | phani00/tovp,mayapurmedia/tovp,phani00/tovp,mayapurmedia/tovp,mayapurmedia/tovp,phani00/tovp | ---
+++
@@ -1,4 +1,5 @@
from ajax_select import LookupChannel
+from django.core.exceptions import PermissionDenied
from django.utils.html import escape
from django.db.models import Q
from .models import Person
@@ -22,3 +23,8 @@
def format_item_display(self, obj):
""" (HTML) formatted item for displa... |
e5e621e511493a147f8ed3a7bae401874b5e5ef1 | __init__.py | __init__.py | #Shoopdawoop
from . import CuraEngineBackend
from UM.Preferences import Preferences
def getMetaData():
return { "name": "CuraBackend", "type": "Backend" }
def register(app):
Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine")
engine = CuraEngineBackend.CuraEngineBackend()
a... | #Shoopdawoop
from . import CuraEngineBackend
from UM.Preferences import Preferences
def getMetaData():
return { "name": "CuraEngine Backend", "type": "Backend" }
def register(app):
Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine")
engine = CuraEngineBackend.CuraEngineBackend(... | Update name and displayName for a bunch of plugins | Update name and displayName for a bunch of plugins
| Python | agpl-3.0 | markwal/Cura,hmflash/Cura,quillford/Cura,derekhe/Cura,bq/Ultimaker-Cura,DeskboxBrazil/Cura,derekhe/Cura,ad1217/Cura,lo0ol/Ultimaker-Cura,bq/Ultimaker-Cura,Curahelper/Cura,DeskboxBrazil/Cura,quillford/Cura,fieldOfView/Cura,ynotstartups/Wanhao,lo0ol/Ultimaker-Cura,ynotstartups/Wanhao,markwal/Cura,totalretribution/Cura,fi... | ---
+++
@@ -4,7 +4,7 @@
from UM.Preferences import Preferences
def getMetaData():
- return { "name": "CuraBackend", "type": "Backend" }
+ return { "name": "CuraEngine Backend", "type": "Backend" }
def register(app):
Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine") |
b9388a64b274277eff32fe53c856527716eee282 | docs/examples/servo_sweep.py | docs/examples/servo_sweep.py | from gpiozero import Servo
from gpiozero.tools import sin_values
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
| from gpiozero import Servo
from gpiozero.tools import sin_values
from signal import pause
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
pause()
| Fix servo sweep example in docs | Fix servo sweep example in docs | Python | bsd-3-clause | waveform80/gpio-zero | ---
+++
@@ -1,7 +1,10 @@
from gpiozero import Servo
from gpiozero.tools import sin_values
+from signal import pause
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
+
+pause() |
9698dc9da2ca2ac9ba632b14e5757f0f930efe9d | Mollie/API/Object/List.py | Mollie/API/Object/List.py | from .Base import Base
class List(Base):
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __iter__(self):
for item in self['data']:
yield self.object_type(item)
def getTotalCount(self):
if 'totalCount' not... | from .Base import Base
class List(Base):
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def getResourceName(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
for item in self['_embedded'][self.ge... | Make list objects return the embedded resource data again | Make list objects return the embedded resource data again
| Python | bsd-2-clause | mollie/mollie-api-python | ---
+++
@@ -6,8 +6,11 @@
Base.__init__(self, result)
self.object_type = object_type
+ def getResourceName(self):
+ return self.object_type.__name__.lower() + 's'
+
def __iter__(self):
- for item in self['data']:
+ for item in self['_embedded'][self.getResourceName()]:
... |
7a4d9c88895449b54d016226a383bde40502060c | supersaver/product/managers.py | supersaver/product/managers.py | from django.apps import apps
from django.db.models import manager
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
class ProductManager (manager.Manager):
# Custom manager to facilitate product query
# Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/
def sear... | from datetime import datetime
from django.apps import apps
from django.db.models import manager
from django.db.models import expressions
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
class ProductManager (manager.Manager):
"""
Custom manager to facilitate product query
... | Add 2 methods to search product by keywords. | Add 2 methods to search product by keywords.
| Python | bsd-2-clause | ftkghost/SuperSaver,ftkghost/SuperSaver | ---
+++
@@ -1,18 +1,46 @@
+from datetime import datetime
+
from django.apps import apps
from django.db.models import manager
+from django.db.models import expressions
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
class ProductManager (manager.Manager):
- # Custom manager ... |
1f38afdff13c7ccee797fe6063c75630dd642f0a | matador/commands/command.py | matador/commands/command.py | #!/usr/bin/env python
import logging
import argparse
from matador.session import Session
class Command(object):
def __init__(self, **kwargs):
if kwargs:
# If kwargs have been supplied, use these in same way argsparse
# would.
# Mainly used for testing.
clas... | #!/usr/bin/env python
import logging
import argparse
from matador.session import Session
class Command(object):
def __init__(self, **kwargs):
if kwargs:
# If kwargs have been supplied, use these in same way argsparse
# would.
# Mainly used for testing.
clas... | Change name of session init method | Change name of session init method
| Python | mit | Empiria/matador | ---
+++
@@ -26,7 +26,7 @@
self.args, unknown = parser.parse_known_args()
self._logger = logging.getLogger(__name__)
- Session.initialise_session()
+ Session.initialise()
self._execute()
def _add_arguments(self, parser): |
a7dce25964cd740b0d0db86b255ede60c913e73d | chdb.py | chdb.py | import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE IF EXISTS categories
''')
db.execute('''
DROP TABLE IF EXISTS articles
''')
... | import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE categories
''')
db.execute('''
DROP TABLE articles
''')
db.execute('''
... | Remove IF EXISTS from DROP TABLE when resetting the db. | Remove IF EXISTS from DROP TABLE when resetting the db.
| Python | mit | Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt | ---
+++
@@ -10,16 +10,16 @@
with db:
db.execute('''
- DROP TABLE IF EXISTS categories
+ DROP TABLE categories
''')
db.execute('''
- DROP TABLE IF EXISTS articles
+ DROP TABLE articles
''')
db.execute('''
- DROP ... |
280e7cf4f7e667ccba796294c58edd5a0f744b70 | geopandas/__init__.py | geopandas/__init__.py | try:
from geopandas.version import version as __version__
except ImportError:
__version__ = '0.1.0'
from geopandas.geoseries import GeoSeries
from geopandas.geodataframe import GeoDataFrame
from geopandas.io.file import read_file
from geopandas.io.sql import read_postgis
# make the interactive namespace easi... | try:
from geopandas.version import version as __version__
except ImportError:
__version__ = '0.2.0.dev-unknown'
from geopandas.geoseries import GeoSeries
from geopandas.geodataframe import GeoDataFrame
from geopandas.io.file import read_file
from geopandas.io.sql import read_postgis
# make the interactive na... | Set default version to 0.2.0.dev-unknown | BLD: Set default version to 0.2.0.dev-unknown
| Python | bsd-3-clause | IamJeffG/geopandas,geopandas/geopandas,perrygeo/geopandas,jorisvandenbossche/geopandas,ozak/geopandas,ozak/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,geopandas/geopandas,scw/geopandas,urschrei/geopandas,koldunovn/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,kwinkunks/geopandas,jdmcbr... | ---
+++
@@ -1,7 +1,7 @@
try:
from geopandas.version import version as __version__
except ImportError:
- __version__ = '0.1.0'
+ __version__ = '0.2.0.dev-unknown'
from geopandas.geoseries import GeoSeries
from geopandas.geodataframe import GeoDataFrame |
d173f5688d2ea466e52e58673d920723847f12a1 | gittip/utils/timer.py | gittip/utils/timer.py | import time
def start():
return {'start_time': time.time()}
def end(start_time):
print("count#requests=1")
response_time = time.time() - start_time
print("measure#response_time={}ms".format(response_time * 1000))
| import time
def start():
return {'start_time': time.time()}
def end(start_time, website):
if website.log_metrics:
print("count#requests=1")
response_time = time.time() - start_time
print("measure#response_time={}ms".format(response_time * 1000))
| Clean up merge of LOG_METRICS from master | Clean up merge of LOG_METRICS from master
| Python | mit | mccolgst/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/ww... | ---
+++
@@ -3,7 +3,8 @@
def start():
return {'start_time': time.time()}
-def end(start_time):
- print("count#requests=1")
- response_time = time.time() - start_time
- print("measure#response_time={}ms".format(response_time * 1000))
+def end(start_time, website):
+ if website.log_metrics:
+ ... |
b75570a5897383c6fa9834c1f5f1b2aaf8d236cd | wakatime/projects/projectmap.py | wakatime/projects/projectmap.py | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from functools import par... | Fix ProjectMap always returning true if it has a config section | Fix ProjectMap always returning true if it has a config section
| Python | bsd-3-clause | gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,wakatime/wakatime,prashanthr/wakatime,wangjun/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,gandarez/wakatime,queenp/wakatime,wakatime/wakatime,Djabbz/wakatime,prash... | ---
+++
@@ -12,6 +12,7 @@
import logging
import os
+from functools import partial
from ..packages import simplejson as json
@@ -23,22 +24,32 @@
class ProjectMap(BaseProject):
def process(self):
- if self.settings:
- return True
+ if not self.settings:
+ return Fals... |
73ee4af73309c4d20cf7b28ac82a5e1037a5d65a | poetry_core/packages/project_package.py | poetry_core/packages/project_package.py | from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
... | from poetry_core.semver import VersionRange
from poetry_core.semver import parse_constraint
from poetry_core.version.markers import parse_marker
from .package import Package
from .utils.utils import create_nested_marker
class ProjectPackage(Package):
def __init__(self, name, version, pretty_version=None):
... | Add the to_dependency method to ProjectPackage | Add the to_dependency method to ProjectPackage
| Python | mit | python-poetry/poetry-core,python-poetry/poetry-core,python-poetry/poetry-core | ---
+++
@@ -22,6 +22,13 @@
def is_root(self):
return True
+ def to_dependency(self):
+ dependency = super(ProjectPackage, self).to_dependency()
+
+ dependency.is_root = True
+
+ return dependency
+
@property
def python_versions(self):
return self._python_vers... |
3043a2400e46648f01921aad265816d2bcf18211 | test/test_conjunctive_graph.py | test/test_conjunctive_graph.py | from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(... | from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(... | Fix py3-incompatible test code that causes PY3 test failure. | Fix py3-incompatible test code that causes PY3 test failure.
| Python | bsd-3-clause | avorio/rdflib,yingerj/rdflib,avorio/rdflib,RDFLib/rdflib,ssssam/rdflib,marma/rdflib,marma/rdflib,avorio/rdflib,armandobs14/rdflib,RDFLib/rdflib,dbs/rdflib,armandobs14/rdflib,yingerj/rdflib,yingerj/rdflib,ssssam/rdflib,RDFLib/rdflib,dbs/rdflib,yingerj/rdflib,marma/rdflib,dbs/rdflib,armandobs14/rdflib,RDFLib/rdflib,avori... | ---
+++
@@ -22,7 +22,7 @@
yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle")
- source = StringInputSource(DATA)
+ source = StringInputSource(DATA.encode('utf8'))
source.setPublicId(PUBLIC_ID)
yield check, dict(source=source, format='turtle')
|
9be02e353335db2c5923be0959595aeb35e9311c | testing/test_direct_wrapper.py | testing/test_direct_wrapper.py | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
def test_open_file(tes... | import os
from cffitsio._cfitsio import ffi, lib
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = ffi.new('fitsfile **')
status = ffi.new('int *')
lib.fits_create_file(f, filename, status)
assert status[0] == 0
assert os.path.isfile(filename)
def test_open_file(tes... | Add test for file closing | Add test for file closing
| Python | mit | mindriot101/fitsio-cffi | ---
+++
@@ -17,3 +17,12 @@
status = ffi.new('int *')
lib.fits_open_file(f, test_file, 0, status)
assert status[0] == 0
+
+
+def test_close_file(test_file):
+ f = ffi.new('fitsfile **')
+ status = ffi.new('int *')
+ lib.fits_open_file(f, test_file, 0, status)
+ assert status[0] == 0
+ lib... |
f29360f7351e5c72769122ea215c45df7c069f20 | tests/all-errors-documented.py | tests/all-errors-documented.py | #!/usr/bin/python
# Check if all the errors have been added to
# docs/reference/telepathy-glib-sections.txt
import os
import sys
import xml.dom.minidom
from libglibcodegen import NS_TP
def check_all_errors_documented(abs_top_srcdir):
error_path = os.path.join(abs_top_srcdir, 'spec', 'errors.xml')
sections_p... | #!/usr/bin/python
# Check if all the errors have been added to
# docs/reference/telepathy-glib-sections.txt
import os
import sys
import xml.dom.minidom
from libglibcodegen import NS_TP
def check_all_errors_documented(abs_top_srcdir):
error_path = os.path.join(abs_top_srcdir, 'spec', 'errors.xml')
sections_p... | Add missing parenthesis to fix syntax of test | Add missing parenthesis to fix syntax of test
| Python | lgpl-2.1 | Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib | ---
+++
@@ -21,7 +21,7 @@
for error in errors.getElementsByTagNameNS(NS_TP, 'error'):
nick = error.getAttribute('name').replace(' ', '')
name = ('TP_ERROR_STR_' +
- error.getAttribute('name').replace('.', '_').replace(' ', '_').upper()
+ error.getAttribute('name').... |
a77b62ccadf578b8e352e4fdae8e4efe5060f938 | workshopvenues/venues/models.py | workshopvenues/venues/models.py | from django.db import models
class Venues(models.Model):
name = models.CharField(max_length=30)
website = models.CharField(max_length=50)
address = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10)
| from django.db import models
class Venues(models.Model):
name = models.CharField(max_length=30)
website = models.CharField(max_length=50)
address = models.CharField(max_length=200)
town = models.CharField(max_length=30)
postcode = models.CharField(max_length=10)
def __unicode__(self):
... | Add descriptive name to Venues model | Add descriptive name to Venues model
| Python | bsd-3-clause | andreagrandi/workshopvenues | ---
+++
@@ -1,8 +1,11 @@
from django.db import models
class Venues(models.Model):
- name = models.CharField(max_length=30)
- website = models.CharField(max_length=50)
- address = models.CharField(max_length=200)
- town = models.CharField(max_length=30)
- postcode = models.CharField(max_length=10)
+ name = mode... |
bdecfc7f31b13718957e598947eb52b2e7988fd6 | numba/postpasses.py | numba/postpasses.py | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | Add pointer from math library to external numba.math.* functions | Add pointer from math library to external numba.math.* functions
| Python | bsd-2-clause | pombredanne/numba,GaZ3ll3/numba,ssarangi/numba,numba/numba,ssarangi/numba,ssarangi/numba,stefanseefeld/numba,cpcloud/numba,pitrou/numba,cpcloud/numba,pitrou/numba,pitrou/numba,stuartarchibald/numba,jriehl/numba,gdementen/numba,stefanseefeld/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3... | ---
+++
@@ -23,6 +23,5 @@
@register_default('math')
def postpass_link_math(env, ee, lmod, lfunc):
"numba.math.* -> mathcode.*"
- env.llvm_context.execution_engine
math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library)
return lfunc |
25d36ba71aed866de468363ea6004eabbd8f22da | publish/tools/crontool.py | publish/tools/crontool.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This tool iterates through all of the scrapers in the datasets module
and creates a cron-task for each one.
'''
import os
import pkgutil
import random
import sys
from publish.lib.manifest import get_scraper_names
def get_launch_binary():
this_location = sys.argv[... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This tool iterates through all of the scrapers in the datasets module
and creates a cron-task for each one.
'''
import os
import pkgutil
import random
import sys
from publish.lib.manifest import get_scraper_names
def get_launch_binary():
this_location = sys.argv[... | Make sure we use the absolute path in generating cron lines | Make sure we use the absolute path in generating cron lines
| Python | mit | nhsengland/publish-o-matic | ---
+++
@@ -14,11 +14,13 @@
def get_launch_binary():
this_location = sys.argv[0]
- return os.path.join(os.path.dirname(this_location), "run_scraper")
+ path = os.path.join(os.path.dirname(this_location), "run_scraper")
+ return os.path.abspath(path)
def get_dmswitch_binary():
this_location = ... |
ad17e166cac2863692af96bccf0317d97e102e24 | tests/integration/test_juju.py | tests/integration/test_juju.py | import pytest
from juju.controller import Controller
from juju.juju import Juju
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_get_controllers(event_loop):
async with base.CleanController() as controller:
j = Juju()
controllers = j.get_controllers()
assert isi... | import pytest
from juju.controller import Controller
from juju.juju import Juju
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_get_controllers(event_loop):
async with base.CleanController() as controller:
j = Juju()
controllers = j.get_controllers()
assert isi... | Make sure to disconnect the extra connection before finishing the test | Make sure to disconnect the extra connection before finishing the test
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju | ---
+++
@@ -19,3 +19,4 @@
cc = await j.get_controller(controller.controller_name)
assert isinstance(cc, Controller)
assert controller.connection().endpoint == cc.connection().endpoint
+ await cc.disconnect() |
ab1fca145208dfcc0581fce8076b8f52fe237b94 | src/settings.py | src/settings.py | # -*- coding: utf-8 -*-
import os
HERE = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE... | # -*- coding: utf-8 -*-
import os
HERE = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE... | Set production databse to test database | Set production databse to test database
| Python | mit | codeforamerica/pdfhook,codeforamerica/pdfhook,codeforamerica/pdfhook,gauravmk/pdfhook,gauravmk/pdfhook,gauravmk/pdfhook | ---
+++
@@ -8,7 +8,7 @@
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
- SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
+ SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/')
SERVER_NAME = os.e... |
497116839db95bf734ed66e5cf87e986141ad50d | txircd/modules/rfc/cmd_info.py | txircd/modules/rfc/cmd_info.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd import version
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class InfoCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd import version
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class InfoCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name... | Add self to contributors list | Add self to contributors list
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd | ---
+++
@@ -26,6 +26,7 @@
user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>")
user.sendMessage(irc.RPL_INFO, ":Contributors:")
user.sendMessage(irc.RPL_INFO, ": Heufneutje")
+ user.sendMessage(irc.RPL_INFO, ": ekimekim")
user.... |
6292cd114d8d982162fa8076605cce569acd8fc5 | panphon/xsampa.py | panphon/xsampa.py | from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
d... | from __future__ import absolute_import, print_function, unicode_literals
import regex as re
import unicodecsv as csv
import os.path
import pkg_resources
class XSampa(object):
def __init__(self, delimiter=' '):
self.delimiter = delimiter
self.xs_regex, self.xs2ipa = self.read_xsampa_table()
d... | Convert map objects to lists | Convert map objects to lists
| Python | mit | dmort27/panphon,dmort27/panphon | ---
+++
@@ -17,7 +17,7 @@
with open(filename, 'rb') as f:
xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')}
xs = sorted(xs2ipa.keys(), key=len, reverse=True)
- xs_regex = re.compile('|'.join(map(re.escape, xs)))
+ xs_regex = re.compile('|'.join(list(map(re.esc... |
2809f97696791f34e659dc9fc3c9e29c802082d2 | django_evolution/tests/test_evolution_models.py | django_evolution/tests/test_evolution_models.py | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... | Fix unit tests for Version.objects.get_current(). | Fix unit tests for Version.objects.get_current().
The unit tests assumed that no Version objects were present, but this
wasn't always the case. This clears them before the test runs.
| Python | bsd-3-clause | beanbaginc/django-evolution | ---
+++
@@ -10,6 +10,9 @@
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_version() with two entries with same timestamps"""
+ # Remove anything that may already exist.
+ Version.objects.all().delete()
+
timestamp = datetime(year=2015, month=12, da... |
8ebaf59aa2f966bf0a807c1cbce5359ae0868863 | tests/encode_decode_tests.py | tests/encode_decode_tests.py | # -*- encoding: utf-8 -*-
from datetime import datetime
from decimal import Decimal
try:
import unittest2 as unittest
except ImportError:
import unittest
from pamqp import encode, decode
from pamqp import PYTHON3
if PYTHON3:
long = int
def to_bytes(value):
if isinstance(value, bytes):
return... | # -*- encoding: utf-8 -*-
from datetime import datetime
from decimal import Decimal
try:
import unittest2 as unittest
except ImportError:
import unittest
from pamqp import encode, decode
from pamqp import PYTHON3
if PYTHON3:
long = int
def to_bytes(value):
if isinstance(value, bytes):
return... | Update to reflect str key change | Update to reflect str key change
| Python | bsd-3-clause | gmr/pamqp | ---
+++
@@ -30,4 +30,4 @@
((b'A' * 128) + b'\xf0\x9f\x92\xa9').decode('utf-8'): 2}
encoded = encode.field_table(data)
decoded = decode.field_table(encoded)[1]
- self.assertIn(b'A' * 128, decoded)
+ self.assertIn('A' * 128, decoded) |
e3959d1dcf33dff0d69ba36abf2ff37f2dcf8d60 | spiff/membership/tests.py | spiff/membership/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.contrib.auth.models import User, Group
import models
class MemberTest(TestCase):
def tes... | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.contrib.auth.models import User, Group
import models
from spiff.payment.models import Payme... | Remove broken and old test | Remove broken and old test
| Python | agpl-3.0 | SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff | ---
+++
@@ -8,6 +8,7 @@
from django.test import TestCase
from django.contrib.auth.models import User, Group
import models
+from spiff.payment.models import Payment
class MemberTest(TestCase):
def testUserCreation(self):
@@ -22,15 +23,3 @@
self.assertIsNotNone(g.rank)
self.assertEqual(g.rank.group, ... |
2430e87f2c44c46863ed47c8b3a55c4010820260 | frontend/modloop/__init__.py | frontend/modloop/__init__.py | from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job
from . import submit
app = saliweb.frontend.make_application(__name__, "##CONFIG##")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
d... | from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
parameters=[Parameter("name", "Job name", optional=True),
FileParameter("pdb", "PDB file to be refined"),
Parame... | Add basic REST API support | Add basic REST API support
| Python | lgpl-2.1 | salilab/modloop,salilab/modloop | ---
+++
@@ -1,10 +1,14 @@
from flask import render_template, request, send_from_directory
import saliweb.frontend
-from saliweb.frontend import get_completed_job
+from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
-app = saliweb.frontend.make_application(__name__, "##... |
3e6aa4b740b6b22b7ea381db71f76c0c692afa53 | pydispatch/__init__.py | pydispatch/__init__.py | import sys
import warnings
import pkg_resources
try:
__version__ = pkg_resources.require('python-dispatch')[0].version
except: # pragma: no cover
__version__ = 'unknown'
if sys.version_info < (3, 6): # pragma: no cover
warnings.warn('You are using `python-dispatch` with a deprecated Python version. '
... | import sys
import warnings
import pkg_resources
try:
__version__ = pkg_resources.require('python-dispatch')[0].version
except: # pragma: no cover
__version__ = 'unknown'
if sys.version_info < (3, 6): # pragma: no cover
warnings.warn('You are using `python-dispatch` with a deprecated Python version. '
... | Add back missing import from merge commit c40da341b | Add back missing import from merge commit c40da341b
| Python | mit | nocarryr/python-dispatch | ---
+++
@@ -12,5 +12,5 @@
'After version 0.1.x, `python-dispatch` will only support Python 3.6 or greater.',
UserWarning)
-from pydispatch.dispatch import Dispatcher
+from pydispatch.dispatch import Dispatcher, Event
from pydispatch.properties import * |
27e7f47f2506be8607f29961dd629a8038c7e67f | ecmd-core/pyecmd/test_api.py | ecmd-core/pyecmd/test_api.py | from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId... | from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins... | Make fapi2 test conditional on fapi2 being built into ecmd | pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
| Python | apache-2.0 | open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD | ---
+++
@@ -1,6 +1,10 @@
from pyecmd import *
-with Ecmd(fapi2="ver1"):
+extensions = {}
+if hasattr(ecmd, "fapi2InitExtension"):
+ extensions["fapi2"] = "ver1"
+
+with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x101000... |
aca410866dfdd9ced23df14fb3e51fb02f910e85 | IPython/html/widgets/__init__.py | IPython/html/widgets/__init__.py | from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_... | from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_... | Make the widget error message shorter and more understandable. | Make the widget error message shorter and more understandable.
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidg... | ---
+++
@@ -26,4 +26,4 @@
# Warn on import
from warnings import warn
-warn("""The widget API is still considered experimental and may change in the future.""", FutureWarning, stacklevel=2)
+warn("IPython widgets are experimental and may change in the future.", FutureWarning, stacklevel=2) |
69d18539fb4f394ca45d1116a521084c83ea21b5 | icekit_events/migrations/0012_auto_20160706_1606.py | icekit_events/migrations/0012_auto_20160706_1606.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0011_event_show_in_calendar'),
]
operations = [
migrations.AlterModelTable(
name='event',
... | Make migration reverse no-op a valid SQL query | Make migration reverse no-op a valid SQL query
When using a PostgreSQL database with Django 1.7 empty reverse query
statements in DB migrations cause an error, so we replace the empty
no-op statement with a valid query that still does nothing so the
reverse migration will work in this case.
This problem doesn't seem ... | Python | mit | ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -24,6 +24,6 @@
# No-op: I haven't yet found a way to make this reversible in the
# way you would expect without unique constraint DB errors, whereas
# it works (according to unit tests at least) with a no-op.
- "",
+ "UPDATE django_content_type S... |
8c20bb711486a95cc861ffeb4bd61e67b3d8f99b | ledger-core-samples/nodejs/glob.py | ledger-core-samples/nodejs/glob.py | #!/usr/bin/env python
# a helper for gyp to do file globbing cross platform
# Usage: python glob.py root_dir pattern [pattern...]
import fnmatch
import os
import sys
root_dir = sys.argv[1]
patterns = sys.argv[2:]
for (dirpath, dirnames, files) in os.walk(root_dir):
for f in files:
match = False
f... | #!/usr/bin/env python
# a helper for gyp to do file globbing cross platform
# Usage: python glob.py root_dir pattern [pattern...]
import fnmatch
import os
import sys
root_dir = sys.argv[1]
patterns = sys.argv[2:]
for (dirpath, dirnames, files) in os.walk(root_dir):
for f in files:
match = False
f... | Fix Python invokation (2.7 -> 3.7) in ledger-samples. | Fix Python invokation (2.7 -> 3.7) in ledger-samples.
| Python | mit | LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core | ---
+++
@@ -15,4 +15,4 @@
for pattern in patterns:
match = match or fnmatch.fnmatch(f, pattern)
if match:
- print dirpath + '/' + f
+ print(dirpath + '/' + f) |
033c16034074d4fd6eab054a9c97888d23668316 | tests/test_empty_polygons.py | tests/test_empty_polygons.py | from shapely.geometry import MultiPolygon, Polygon
def test_empty_polygon():
"""No constructor arg makes an empty polygon geometry."""
assert Polygon().is_empty
def test_empty_multipolygon():
"""No constructor arg makes an empty multipolygon geometry."""
assert MultiPolygon().is_empty
def test_mul... | from shapely.geometry import MultiPolygon, Point, Polygon
def test_empty_polygon():
"""No constructor arg makes an empty polygon geometry."""
assert Polygon().is_empty
def test_empty_multipolygon():
"""No constructor arg makes an empty multipolygon geometry."""
assert MultiPolygon().is_empty
def t... | Add test of an empty and non empty polygon | Add test of an empty and non empty polygon
| Python | bsd-3-clause | jdmcbr/Shapely,jdmcbr/Shapely | ---
+++
@@ -1,4 +1,4 @@
-from shapely.geometry import MultiPolygon, Polygon
+from shapely.geometry import MultiPolygon, Point, Polygon
def test_empty_polygon():
@@ -15,3 +15,8 @@
"""An empty polygon passed to MultiPolygon() makes an empty
multipolygon geometry."""
assert MultiPolygon([Polygon()]).... |
c28b0f5ea02652f7899e34d9a8779e2ff47d8020 | tests/test_internal_links.py | tests/test_internal_links.py | # -*- encoding: utf-8
from http_crawler import crawl
def test_no_links_are_broken(baseurl):
"""
Check that all internal links point to working pages.
"""
responses = []
for rsp in crawl(baseurl, follow_external_links=False):
responses.append(rsp)
failed_responses = [rsp for rsp in re... | # -*- encoding: utf-8
from http_crawler import crawl
import pytest
_responses = []
@pytest.fixture
def responses(baseurl):
if not _responses:
for rsp in crawl(baseurl, follow_external_links=False):
_responses.append(rsp)
return _responses
def test_no_links_are_broken(responses):
""... | Move the responses to a cacheable fixture | Move the responses to a cacheable fixture
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net | ---
+++
@@ -1,16 +1,23 @@
# -*- encoding: utf-8
from http_crawler import crawl
+import pytest
+
+_responses = []
-def test_no_links_are_broken(baseurl):
+@pytest.fixture
+def responses(baseurl):
+ if not _responses:
+ for rsp in crawl(baseurl, follow_external_links=False):
+ _responses.ap... |
3bb2258e75658f8e9c01217fc9b0ae7f53df861a | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | Update Dockerfile to include extensions | Update Dockerfile to include extensions
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server | ---
+++
@@ -10,4 +10,4 @@
def __init__(self, game=None):
super(ExtGameController, self).__init__(game=game)
-# self.add_mode(self.additional_modes)
+ self.add_mode(self.additional_modes) |
178006e4a299ca67e758184be50ae94333f09821 | test_settings.py | test_settings.py | from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
| from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_K... | Add url setting to test settings | Add url setting to test settings
| Python | bsd-2-clause | praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django | ---
+++
@@ -8,6 +8,7 @@
}
ONAPIE_ACCESS_TOKEN = 'foo'
+ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY' |
0d81ecbe4126585d8af089e76fc3bb98b5dc2098 | eforge/__init__.py | eforge/__init__.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | Add beta version tagging for 0.5 beta 1 | Add beta version tagging for 0.5 beta 1
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge | ---
+++
@@ -25,7 +25,7 @@
},
}
-VERSION = (0, 5, 0)
+VERSION = (0, 5, 0, 'beta 1')
def get_version():
- return '%d.%d.%d' % VERSION
+ return '%d.%d.%d %s' % VERSION |
3ff7704d9c9998f023fb2d93e279b0f1e4410ad8 | arim/models.py | arim/models.py | from django.db import models
class Autoreg(models.Model):
class Meta:
db_table = 'autoreg'
mac = models.CharField(max_length=17, db_index=True)
ip = models.IntegerField(primary_key=True)
date = models.IntegerField()
| from django.db import models
class Lease(models.Model):
class Meta:
db_table = 'autoreg'
mac = models.CharField(max_length=17, db_index=True)
ip = models.IntegerField(primary_key=True)
date = models.IntegerField()
| Change model name (but not table name) | Change model name (but not table name)
| Python | bsd-3-clause | drkitty/arim,OSU-Net/arim,drkitty/arim,OSU-Net/arim,OSU-Net/arim,drkitty/arim | ---
+++
@@ -1,7 +1,7 @@
from django.db import models
-class Autoreg(models.Model):
+class Lease(models.Model):
class Meta:
db_table = 'autoreg'
|
690dbc1ce63a6dc107a34d5b0315d316ef334e49 | vdi/context_preprocessors.py | vdi/context_preprocessors.py | from django.conf import settings
def context_preprocessor(request):
d = {
'vdi_media_dir': settings.VDI_MEDIA_PREFIX,
}
if request.user.is_authenticated():
d['institution'] = request.user.username.split('++')[0]
return d
| from django.conf import settings
def context_preprocessor(request):
d = {
'vdi_media_dir': settings.VDI_MEDIA_PREFIX,
}
if request.user.is_authenticated():
institution = request.user.username.split('++')
if len(institution) == 1:
institution = 'local'
else:
... | Edit to populate the local themeing. | Edit to populate the local themeing.
| Python | apache-2.0 | bmbouter/Opus,ehelms/Opus,ehelms/Opus,bmbouter/Opus,ehelms/Opus,bmbouter/Opus | ---
+++
@@ -5,5 +5,10 @@
'vdi_media_dir': settings.VDI_MEDIA_PREFIX,
}
if request.user.is_authenticated():
- d['institution'] = request.user.username.split('++')[0]
+ institution = request.user.username.split('++')
+ if len(institution) == 1:
+ institution = 'local'
... |
3ed33d83b1ade56b41166b50713b1087d6559b70 | hello-world/hello_world_test.py | hello-world/hello_world_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import hello_world
class BobTests(unittest.TestCase):
def test_hello_without_name(self):
self.assertEqual(
'Hello, World!',
hello_world.hello()
)
def test_hello_with_name(self):
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import hello_world
class HelloWorldTests(unittest.TestCase):
def test_hello_without_name(self):
self.assertEqual(
'Hello, World!',
hello_world.hello()
)
def test_hello_with_sample_name(s... | Fix Hello World test class name & update test | Fix Hello World test class name & update test
Fix test class name to reflect exercise name.
Update tests to reflect Hello World metadata in x-common.
| Python | mit | pheanex/xpython,de2Zotjes/xpython,jmluy/xpython,rootulp/xpython,rootulp/xpython,oalbe/xpython,exercism/xpython,mweb/python,outkaj/xpython,exercism/xpython,mweb/python,jmluy/xpython,behrtam/xpython,N-Parsons/exercism-python,pheanex/xpython,smalley/python,orozcoadrian/xpython,N-Parsons/exercism-python,orozcoadrian/xpytho... | ---
+++
@@ -6,7 +6,7 @@
import hello_world
-class BobTests(unittest.TestCase):
+class HelloWorldTests(unittest.TestCase):
def test_hello_without_name(self):
self.assertEqual(
@@ -14,10 +14,16 @@
hello_world.hello()
)
- def test_hello_with_name(self):
+ def test_hello... |
c2726978a1272b13af2ffdfb10b4238985768317 | tests/test_db.py | tests/test_db.py | import pytest
from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val
def pytestmark(func):
pytest.mark.django_db(func)
pytest.mark.usefixtures('test_table')(func)
@pytest.fixture(scope='module')
def test_table():
do_sql('''
begin;
create table test (
id int ... | import pytest
from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val
def pytestmark(func):
pytest.mark.django_db(func)
pytest.mark.usefixtures('test_table')(func)
@pytest.fixture(scope='module')
def test_table():
# NOTE: We wrap that into transaction because in other case django will g... | Add NOTE regarding transaction to db tests setup | Add NOTE regarding transaction to db tests setup
| Python | bsd-3-clause | leliel12/handy,leliel12/handy | ---
+++
@@ -10,14 +10,18 @@
@pytest.fixture(scope='module')
def test_table():
+ # NOTE: We wrap that into transaction because in other case django will gobble it up
+ # into single transaction with first test and then rollback everything happily on
+ # that tests end.
do_sql('''
... |
221a94c38ac0ad0c6d08f02b587c259423b96311 | wagtailaltgenerator/utils.py | wagtailaltgenerator/utils.py | import os
import requests
from django.utils.translation import get_language
from wagtailaltgenerator.translation_providers import get_current_provider
from wagtailaltgenerator.providers import DescriptionResult
def get_image_data(image_url):
'''
Load external image and return byte data
'''
image_dat... | import os
import requests
from django.utils.translation import get_language
from wagtailaltgenerator.translation_providers import get_current_provider
from wagtailaltgenerator.providers import DescriptionResult
def get_image_data(image_url):
'''
Load external image and return byte data
'''
image_dat... | Fix issue where lang was not parsed properly | Fix issue where lang was not parsed properly
| Python | mit | marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator | ---
+++
@@ -30,17 +30,19 @@
def translate_description_result(result):
provider = get_current_provider()()
- to_lang = get_language()
+
+ lang_and_country_code = get_language()
+ lang_code = lang_and_country_code.split("-")[0]
strings = []
if result.description:
strings = [result.... |
b2c527e912260253be459c9ad3dd6139be21a75d | faucet/valve_manager_base.py | faucet/valve_manager_base.py | """Valve Manager base class"""
# pylint: disable=R0201
# pylint: disable=W0613
class ValveManagerBase: # pylint: disable=too-few-public-methods
"""Base class for ValveManager objects.
Expected to control the installation of flows into datapath tables.
Ideally each datapath table should be controlled by 1... | """Valve Manager base class"""
# pylint: disable=R0201
# pylint: disable=W0613
class ValveManagerBase: # pylint: disable=too-few-public-methods
"""Base class for ValveManager objects.
Expected to control the installation of flows into datapath tables.
Ideally each datapath table should be controlled by 1... | Update manager API for update. | Update manager API for update.
| Python | apache-2.0 | REANNZ/faucet,faucetsdn/faucet,mwutzke/faucet,anarkiwi/faucet,shivarammysore/faucet,trungdtbk/faucet,REANNZ/faucet,gizmoguy/faucet,anarkiwi/faucet,mwutzke/faucet,trungdtbk/faucet,shivarammysore/faucet,faucetsdn/faucet,gizmoguy/faucet | ---
+++
@@ -17,11 +17,15 @@
_FILTER_PRIORITY = 0x5000
def initialise_tables(self):
- '''initialise tables controlled by this manager'''
+ """initialise tables controlled by this manager."""
return []
def add_vlan(self, vlan):
- """install flows in response to a new vla... |
26f48bc7a5e39f50b035f20a517664dade87b981 | binder/json.py | binder/json.py | import json
import datetime
from uuid import UUID
from django.http import HttpResponse
from .exceptions import BinderRequestError
class BinderJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
# FIXME: was .isoformat(), but that omits the microseconds if they
# a... | import json
import datetime
from uuid import UUID
from django.http import HttpResponse
from .exceptions import BinderRequestError
try:
from dateutil.relativedelta import relativedelta
from relativedeltafield import format_relativedelta
except ImportError:
class relativedelta:
pass
class BinderJSONEncoder(json.... | Add support for relativedelta timespecs | Add support for relativedelta timespecs
This uses the django-relativedeltafield formatter. We could copy the
formatter into here but that's not great either. This can be improved
once we have a pluggable JSON serializer.
| Python | mit | CodeYellowBV/django-binder | ---
+++
@@ -6,7 +6,12 @@
from .exceptions import BinderRequestError
-
+try:
+ from dateutil.relativedelta import relativedelta
+ from relativedeltafield import format_relativedelta
+except ImportError:
+ class relativedelta:
+ pass
class BinderJSONEncoder(json.JSONEncoder):
def default(self, obj):
@@ -23,6... |
82ba42bf269e7897129976c07d28b4bc0f23df69 | shopify/mixins.py | shopify/mixins.py | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return shopify.resources.Metafield.... | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self, _options=None, **kwargs):
if _option... | Enable keyword arguments when requesting metafields | Enable keyword arguments when requesting metafields
| Python | mit | Shopify/shopify_python_api | ---
+++
@@ -11,8 +11,10 @@
class Metafields(object):
- def metafields(self):
- return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id)
+ def metafields(self, _options=None, **kwargs):
+ if _options is None:
+ _options = kwargs
+ return sh... |
3395943d4c202709c2f1f110e19a2aa0dc741e63 | UM/Qt/Bindings/DirectoryListModel.py | UM/Qt/Bindings/DirectoryListModel.py | from UM.Qt.ListModel import ListModel
from UM.Application import Application
from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl
import os
import os.path
class DirectoryListModel(ListModel):
NameRole = Qt.UserRole + 1
UrlRole = Qt.UserRole + 2
def __init__(self):
super().__init__()
... | from UM.Qt.ListModel import ListModel
from UM.Application import Application
from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl
import os
import os.path
import platform
class DirectoryListModel(ListModel):
NameRole = Qt.UserRole + 1
UrlRole = Qt.UserRole + 2
def __init__(self):
super().... | Fix directory listing on windows. | Fix directory listing on windows.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -5,6 +5,7 @@
import os
import os.path
+import platform
class DirectoryListModel(ListModel):
NameRole = Qt.UserRole + 1
@@ -26,7 +27,10 @@
def setDirectory(self, path):
if path != self._directory:
if path.startswith('file://'):
- path = path[7:]
+ ... |
5429534fc79237fb175aa8f7888565dd14092d9d | yetibridge/bridge/console.py | yetibridge/bridge/console.py | import threading
from . import BaseBridge
from .. import BaseEvent
class ConsoleBridge(BaseBridge):
def __init__(self, config):
BaseBridge.__init__(self, config)
self._thread = threading.Thread(target=self.run, daemon=True)
self.users = {}
def on_register(self):
self._thread.s... | import threading
from . import BaseBridge
from .. import BaseEvent
class ConsoleBridge(BaseBridge):
def __init__(self, config):
BaseBridge.__init__(self, config)
self._thread = threading.Thread(target=self.run, daemon=True)
self.users = {}
def on_register(self):
self._thread.s... | Add name method to ConsoleBridge | Add name method to ConsoleBridge
Add method to name an id, be it a user, bridge, or the manager itself.
| Python | mit | Hornwitser/YetiBridge | ---
+++
@@ -17,12 +17,27 @@
command = input()
self.send_event('bridge_command', command, 'console')
+ def name(self, item_id):
+ try:
+ return self.users[item_id]
+ except KeyError:
+ pass
+
+ try:
+ return self._manager._bridge_name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.