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 |
|---|---|---|---|---|---|---|---|---|---|---|
38c17bbafb1b193d49003cad5fb4e627625150c1 | pyfibot/modules/module_geoip.py | pyfibot/modules/module_geoip.py | from __future__ import unicode_literals, print_function, division
import pygeoip
import os.path
import sys
import socket
DATAFILE = os.path.join(sys.path[0], "GeoIP.dat")
# STANDARD = reload from disk
# MEMORY_CACHE = load to memory
# MMAP_CACHE = memory using mmap
gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE)
... | from __future__ import unicode_literals, print_function, division
import pygeoip
import os.path
import sys
import socket
# http://dev.maxmind.com/geoip/legacy/geolite/
DATAFILE = os.path.join(sys.path[0], "GeoIP.dat")
# STANDARD = reload from disk
# MEMORY_CACHE = load to memory
# MMAP_CACHE = memory using mmap
gi4 =... | Add comment telling where to get updated geoip database | Add comment telling where to get updated geoip database
| Python | bsd-3-clause | lepinkainen/pyfibot,huqa/pyfibot,rnyberg/pyfibot,huqa/pyfibot,lepinkainen/pyfibot,aapa/pyfibot,aapa/pyfibot,EArmour/pyfibot,rnyberg/pyfibot,EArmour/pyfibot | ---
+++
@@ -4,7 +4,9 @@
import sys
import socket
+# http://dev.maxmind.com/geoip/legacy/geolite/
DATAFILE = os.path.join(sys.path[0], "GeoIP.dat")
+
# STANDARD = reload from disk
# MEMORY_CACHE = load to memory
# MMAP_CACHE = memory using mmap |
3ccdd5e6c52b9c46f9245df647b7b9703424eb74 | pyramda/iterable/reject_test.py | pyramda/iterable/reject_test.py | from . import reject
def test_reject_filters_out_unwanted_items_in_iterable():
assert reject(lambda x: x % 2 == 1, [1, 2, 3, 4]) == [2, 4]
def test_curry_reject_filters_out_unwanted_items_in_iterable():
assert reject(lambda x: x % 2 == 1)([1, 2, 3, 4]) == [2, 4]
| from . import reject
def test_reject_filters_out_unwanted_items_in_iterable():
assert reject(lambda x: x % 2 == 1, [1, 2, 3, 4]) == [2, 4]
def test_curry_reject_filters_out_unwanted_items_in_iterable():
assert reject(lambda x: x % 2 == 1)([1, 2, 3, 4]) == [2, 4]
def test_reject_does_not_remove_duplicates(... | Add test to ensure reject does not remove duplicates | Add test to ensure reject does not remove duplicates
| Python | mit | jackfirth/pyramda | ---
+++
@@ -7,3 +7,11 @@
def test_curry_reject_filters_out_unwanted_items_in_iterable():
assert reject(lambda x: x % 2 == 1)([1, 2, 3, 4]) == [2, 4]
+
+
+def test_reject_does_not_remove_duplicates():
+ assert reject(lambda x: x % 2 == 1, [1, 2, 3, 4, 4]) == [2, 4, 4]
+
+
+def test_curry_reject_does_not_rem... |
af784cf9cf4c4f953ca1a6981155247d8009b2f5 | pullpush/pullpush.py | pullpush/pullpush.py | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
"""
:param repo_dir: Directory in which to pull into
"""
self.repo_dir = repo_dir
self.repo = None
def pull(self, origin):
"""
Pulls from a remote repository and store... | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
"""
:param repo_dir: Directory in which to pull into
"""
self.repo_dir = repo_dir
self.repo = None
def pull(self, origin):
"""
Pulls from a remote repository and store... | Add --all to push option | Add --all to push option
| Python | mit | martialblog/git-pullpush | ---
+++
@@ -47,4 +47,4 @@
#TODO Catch possible exceptions: Repo not initialized
self.set_remote_url(target)
- self.repo.git.push()
+ self.repo.git.push('--all') |
f2359a57d3b52925f88f0bd19ace1286c56d828b | TEKDB/explore/tests/test_views.py | TEKDB/explore/tests/test_views.py | from base64 import b64encode
from django.conf import settings
from django.db import connection
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
#########################################################################
# Run with:
# coverage run manag... | Add test for search input field query | Add test for search input field query
| Python | mit | Ecotrust/TEKDB,Ecotrust/TEKDB,Ecotrust/TEKDB,Ecotrust/TEKDB | ---
+++
@@ -0,0 +1,36 @@
+from base64 import b64encode
+
+from django.conf import settings
+from django.db import connection
+from django.test import TestCase
+from django.test.client import RequestFactory
+from django.urls import reverse
+
+#########################################################################
+#... | |
8c2a138057301821c2370e3d26b3921db2ed79a4 | bluebottle/organizations/serializers.py | bluebottle/organizations/serializers.py | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | Make the name of an organization required | Make the name of an organization required
| Python | bsd-3-clause | jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -14,7 +14,7 @@
class ManageOrganizationSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(required=False, allow_null=True)
- name = serializers.CharField(required=True, allow_blank=True)
+ name = serializers.CharField(required=True)
website = URLField(required=False, a... |
b7559972bc28532108027784a05e8ffc43cb398a | tests/test_models.py | tests/test_models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_djangocms-responsive-wrapper
------------
Tests for `djangocms-responsive-wrapper` models module.
"""
import os
import shutil
import unittest
from responsive_wrapper import models
class TestResponsive_wrapper(unittest.TestCase):
def setUp(self):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_djangocms-responsive-wrapper
------------
Tests for `djangocms-responsive-wrapper` models module.
"""
from django.conf import settings
from django.test import TestCase
from responsive_wrapper import models
class TestResponsive_wrapper(TestCase):
def setU... | Replace unittest.TestCase with Django’s own TestCase. | Replace unittest.TestCase with Django’s own TestCase.
| Python | bsd-3-clause | mishbahr/djangocms-responsive-wrapper,mishbahr/djangocms-responsive-wrapper,mishbahr/djangocms-responsive-wrapper | ---
+++
@@ -8,14 +8,13 @@
Tests for `djangocms-responsive-wrapper` models module.
"""
-import os
-import shutil
-import unittest
+from django.conf import settings
+from django.test import TestCase
from responsive_wrapper import models
-class TestResponsive_wrapper(unittest.TestCase):
+class TestResponsive_... |
ee2cc3cd965a1a8607181c87896430a41c2a4db1 | setup.py | setup.py | from setuptools import setup, find_packages
VERSION = 0.1
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="tldt",
version=VERSION,
url="http://github.com/rciorba/tldt",
long_description=open('README.md', 'r').read(),
package_dir={"": "src"},
packages=f... | from setuptools import setup, find_packages
VERSION = 0.1
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="tldt",
version=VERSION,
url="http://github.com/rciorba/tldt",
long_description=open('README.md', 'r').read(),
package_dir={"": "src"},
packages=f... | Create CLI entry point automatically | Create CLI entry point automatically
| Python | unlicense | rciorba/tldt,rciorba/tldt | ---
+++
@@ -16,4 +16,7 @@
"Development Status :: 1 :: Planning",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules'"],
+ entry_points={
+ "console_scripts": ["tldt = tldt.cli:main"]
+ },
install_requires=requirements) |
a5cf50da81460ab68063689f3e2cadb5db18a3d8 | common/candle_keras/__init__.py | common/candle_keras/__init__.py | from __future__ import absolute_import
#__version__ = '0.0.0'
#import from data_utils
from data_utils import load_csv_data
from data_utils import load_Xy_one_hot_data2
from data_utils import load_Xy_data_noheader
#import from file_utils
from file_utils import get_file
#import from default_utils
from default_utils i... | from __future__ import absolute_import
#__version__ = '0.0.0'
#import from data_utils
from data_utils import load_csv_data
from data_utils import load_Xy_one_hot_data2
from data_utils import load_Xy_data_noheader
#import from file_utils
from file_utils import get_file
#import from default_utils
from default_utils i... | Split multiple arguments for consistency | Split multiple arguments for consistency
| Python | mit | ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks | ---
+++
@@ -31,5 +31,7 @@
from generic_utils import Progbar
from generic_utils import LoggingCallback
-from solr_keras import CandleRemoteMonitor, compute_trainable_params, TerminateOnTimeOut
+from solr_keras import CandleRemoteMonitor
+from solr_keras import compute_trainable_params
+from solr_keras import Termi... |
e4a799d96ad80a8f7960824e7b9ec1192e81deeb | turbasen/__init__.py | turbasen/__init__.py | # encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
# Import the models we want directly available through the root module
from .models import \
Omrade, \
Sted
# Make configure directly available through the root module
from .settings import configure
# Make h... | # encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
# Import the models we want directly available through the root module
from .models import \
Gruppe, \
Omrade, \
Sted
# Make configure directly available through the root module
from .settings import confi... | Add Gruppe to Turbasen import __inti | Add Gruppe to Turbasen import __inti
| Python | mit | Turbasen/turbasen.py | ---
+++
@@ -3,6 +3,7 @@
# Import the models we want directly available through the root module
from .models import \
+ Gruppe, \
Omrade, \
Sted
|
5b3aa82b73d0794d5c3935968c79adbffd47e33f | product_images.py | product_images.py | from openerp.osv import osv, fields
class product_image(osv.Model):
_name = 'product.image'
_columns = {
'name': fields.char('Name'),
'description': fields.text('Description'),
'image': fields.binary('Image'),
'image_small': fields.binary('Small Image'),
'product_tmpl_i... | from openerp.osv import osv, fields
class product_image(osv.Model):
_name = 'product.image'
_columns = {
'name': fields.char('Name'),
'description': fields.text('Description'),
'image_alt': fields.text('Image Label'),
'image': fields.binary('Image'),
'image_small': fiel... | Add image_alt for adding Alt attribute to img tags | Add image_alt for adding Alt attribute to img tags
Added image_alt for adding alt attribute to img tags for SEO | Python | mit | yelizariev/website_multi_image,yelizariev/website_multi_image,luistorresm/website_multi_image,vauxoo-dev/website_multi_image,OdooCommunityWidgets/website_multi_image,lukebranch/website_multi_image,lukebranch/website_multi_image,Vauxoo/website_multi_image,Vauxoo/website_multi_image,luistorresm/website_multi_image,vauxoo... | ---
+++
@@ -6,6 +6,7 @@
_columns = {
'name': fields.char('Name'),
'description': fields.text('Description'),
+ 'image_alt': fields.text('Image Label'),
'image': fields.binary('Image'),
'image_small': fields.binary('Small Image'),
'product_tmpl_id': fields.many2... |
57d1053293424a23f3a74691d743e043f379b1e8 | ludo/ludo_test.py | ludo/ludo_test.py | from move_manager import MoveManager
from board import Board, Field
import unittest
class TestMoves(unittest.TestCase):
def test_valid_moves(self):
pass
if __name__ == '__main__':
unittest.main() | from move_manager import MoveManager, Move
from board import Board, Field
from common_definitions import BoardFieldType, BOARD_FIELD_COUNT,\
PAWN_COUNT, Players, MAX_DICE_NUMBER_OF_POINTS
import unittest
class TestMoves(unittest.TestCase):
def test_valid_moves_in_finish(self):
... | Add test case for no valid move in finish bug | Add test case for no valid move in finish bug
| Python | mit | risteon/ludo_python | ---
+++
@@ -1,12 +1,23 @@
-from move_manager import MoveManager
+from move_manager import MoveManager, Move
from board import Board, Field
+from common_definitions import BoardFieldType, BOARD_FIELD_COUNT,\
+ PAWN_COUNT, Players, MAX_DICE_NUMBER_OF_POINTS
import unittest
+
class T... |
7027163774a6c8213da82e796d4df6ba1c23a194 | molly/__init__.py | molly/__init__.py | """
Molly Project
http://mollyproject.org
A framework for creating Mobile Web applications for HE/FE institutions.
"""
__version__ = '1.2.1'
| """
Molly Project
http://mollyproject.org
A framework for creating Mobile Web applications for HE/FE institutions.
"""
__version__ = '1.3dev'
| Update routing branch to be 1.3 development branch | Update routing branch to be 1.3 development branch
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject | ---
+++
@@ -4,4 +4,4 @@
A framework for creating Mobile Web applications for HE/FE institutions.
"""
-__version__ = '1.2.1'
+__version__ = '1.3dev' |
9931e71dc3af859388c9c19ed29a1705f7af0b4a | mos/light_data.py | mos/light_data.py | import bpy
import json
from .common import *
def light_data_path(blender_object):
path = library_path(blender_object) + "light_data/" + blender_object.name + ".light_data"
return path.strip('/')
def write(report, directory):
blender_lamps = bpy.data.lights
for blender_lamp in blender_lamps:
... | import bpy
import json
from .common import *
def light_data_path(blender_object):
path = library_path(blender_object) + "light_data/" + blender_object.name + ".light_data"
return path.strip('/')
def write(report, directory):
blender_lamps = bpy.data.lights
for blender_lamp in blender_lamps:
... | Use nodes check for light export. | Use nodes check for light export.
| Python | mit | morganbengtsson/io_mos | ---
+++
@@ -12,12 +12,16 @@
blender_lamps = bpy.data.lights
for blender_lamp in blender_lamps:
- node = blender_lamp.node_tree.nodes.get("Emission")
- color_input = node.inputs.get("Color")
- color = color_input.default_value[:3]
+ if blender_lamp.use_nodes:
+ node =... |
6515d159ab3d09f4ac6157b0f825157c4ed1f5c9 | botbot/checks.py | botbot/checks.py | """Functions for checking files"""
import os
import stat
from .checker import is_link
def file_exists(path):
try:
with open(path, mode='r') as test:
pass
except FileNotFoundError:
if is_link(path):
return 'PROB_BROKEN_LINK'
except OSError:
return 'PROB_UNKNO... | """Functions for checking files"""
import os
import stat
from .checker import is_link
def is_fastq(path):
"""Check whether a given file is a fastq file."""
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(path):
"""Che... | Clean up some loose ends | Clean up some loose ends
| Python | mit | jackstanek/BotBot,jackstanek/BotBot | ---
+++
@@ -3,16 +3,6 @@
import stat
from .checker import is_link
-
-def file_exists(path):
- try:
- with open(path, mode='r') as test:
- pass
- except FileNotFoundError:
- if is_link(path):
- return 'PROB_BROKEN_LINK'
- except OSError:
- return 'PROB_UNKNOWN_ER... |
e981ebc6c4e69ee24ae225193c5024a25232169f | command/setup.py | command/setup.py | from command.default import ManagerDefaultController
from cement.core.controller import expose
from util.config import Configuration
import os
import sys
class SetupController(ManagerDefaultController):
class Meta:
label = 'setup'
description = 'Allows to set directories for SteamCMD and Quake Liv... | from command.default import ManagerDefaultController
from cement.core.controller import expose
from util.config import Configuration
import os
import sys
class SetupController(ManagerDefaultController):
class Meta:
label = 'setup'
description = 'Allows to set directories for SteamCMD and Quake Liv... | Fix a typo in STEAMDIR | Fix a typo in STEAMDIR
| Python | mit | rzeka/QLDS-Manager | ---
+++
@@ -26,6 +26,6 @@
config.set('directories', 'ql', os.path.expanduser(self.app.pargs.QLDIR))
if self.app.pargs.STEAMDIR is not None:
- config.set('directories', 'steamcmd', os.path.expanduser(self.app.pargs.STEAMCMD))
+ config.set('directories', 'steamcmd', os.path... |
0dffa6879415ebd1750c264d49e84a4d1d9a1bb0 | sequere/models.py | sequere/models.py | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
class FollowQuerySet(QuerySet):
pass
class FollowManager(models.Manager):
def get_query_set(self):
return FollowQuerySet(self.model)
@python_2_unicode_compatible
c... | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
from .backends import get_backend
class FollowQuerySet(QuerySet):
pass
class FollowManager(models.Manager):
def get_query_set(self):
return FollowQuerySet(self.mode... | Use get_backend in proxy methods | Use get_backend in proxy methods
| Python | mit | thoas/django-sequere | ---
+++
@@ -1,6 +1,8 @@
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
+
+from .backends import get_backend
class FollowQuerySet(QuerySet):
@@ -30,20 +32,20 @@
def follow(from_instance, to_instance):
- pass
+ re... |
bb6ff7beae761a5373c20d90dda4c9374d9baefb | shorturl/forms.py | shorturl/forms.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2013 Kimmo Parviainen-Jalanko <k@77.fi>
#
# 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 without restriction, including without limitation
# the ... | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2013 Kimmo Parviainen-Jalanko <k@77.fi>
#
# 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 without restriction, including without limitation
# the ... | Use requests to follow redirects | Use requests to follow redirects
| Python | mit | kimvais/shorturl,kimvais/shorturl,kimvais/shorturl | ---
+++
@@ -20,8 +20,32 @@
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
+import logging
+from urlparse import urlparse, urlunparse
from django import forms
+from django.conf import settings
+import requests
+
+logging.basicConfig()
... |
8ad8fcfb7d89fa485a3c79161af5733da6bc1462 | gvi/budgets/models.py | gvi/budgets/models.py | from django.db import models
class Budget(models.Model):
number = models.CharField(max_length=100, unique=True)
initial_date = models.DateTimeField()
final_date = models.DateTimeField(blank=True)
hub = models.ForeignKey('hubs.Hubs')
def __str__(self):
return self.number
class BudgetElemen... | from django.db import models
class Budget(models.Model):
number = models.CharField(max_length=100, unique=True)
initial_date = models.DateTimeField()
final_date = models.DateTimeField(blank=True)
hub = models.ForeignKey('hubs.Hubs')
def __str__(self):
return self.number
class BudgetElemen... | Add type of variable budget | Add type of variable budget
| Python | mit | m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts | ---
+++
@@ -23,6 +23,17 @@
category = models.ForeignKey('transactions.Category')
subcategory = models.ForeignKey('transactions.Subcategory')
+ """
+ If the element is variable
+ """
+ FIRST_W = 'f'
+ OTHER_W = 'o'
+ V_TYPE_CHOICES = (
+ (FIRST_W, 'First Week'),
+ ... |
8bf3bb5c44e7383348463215188051ca8054dce7 | spacy/tests/util.py | spacy/tests/util.py | # coding: utf-8
from __future__ import unicode_literals
from ..tokens import Doc
from ..attrs import ORTH, POS, HEAD, DEP
def get_doc(vocab, words, tags=None, heads=None, deps=None):
"""Create Doc object from given vocab, words and annotations."""
tags = tags or [''] * len(words)
heads = heads or [0] * l... | # coding: utf-8
from __future__ import unicode_literals
from ..tokens import Doc
from ..attrs import ORTH, POS, HEAD, DEP
def get_doc(vocab, words=[], tags=None, heads=None, deps=None):
"""Create Doc object from given vocab, words and annotations."""
tags = tags or [''] * len(words)
heads = heads or [0] ... | Make words optional for get_doc | Make words optional for get_doc
| Python | mit | Gregory-Howard/spaCy,banglakit/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,banglakit/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,recognai/spaCy,banglakit/spaCy,recognai/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,ra... | ---
+++
@@ -5,7 +5,7 @@
from ..attrs import ORTH, POS, HEAD, DEP
-def get_doc(vocab, words, tags=None, heads=None, deps=None):
+def get_doc(vocab, words=[], tags=None, heads=None, deps=None):
"""Create Doc object from given vocab, words and annotations."""
tags = tags or [''] * len(words)
heads = ... |
fb5de87747e21bf7ad5755fe5b882b8e3d3a7c8b | gala/filters.py | gala/filters.py | import numpy as np
from scipy import ndimage as nd
def nd_sobel_magnitude(image, spacing=None):
"""Compute the magnitude of Sobel gradients along all axes.
Parameters
----------
image : array
The input image.
spacing : list of float, optional
The voxel spacing along each dimension... | import numpy as np
from scipy import ndimage as ndi
def nd_sobel_magnitude(image, spacing=None):
"""Compute the magnitude of Sobel gradients along all axes.
Parameters
----------
image : array
The input image.
spacing : list of float, optional
The voxel spacing along each dimensio... | Replace usage of ndimage from nd to ndi | Replace usage of ndimage from nd to ndi
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala | ---
+++
@@ -1,5 +1,5 @@
import numpy as np
-from scipy import ndimage as nd
+from scipy import ndimage as ndi
def nd_sobel_magnitude(image, spacing=None):
@@ -22,7 +22,7 @@
if spacing is None:
spacing = np.ones(image.ndim, np.float32)
for ax, sp in enumerate(spacing):
- axsobel = nd.so... |
870af34689fe08d53ba32271716c49df9af982ae | grader/setup.py | grader/setup.py | from setuptools import setup, find_packages
setup(name="grader",
# http://semver.org/spec/v2.0.0.html
version="0.0.1",
url='https://github.com/brhoades/grader',
description="A grading framework for evaluating programming assignments",
packages=find_packages('src'),
package_dir={'': ... | from setuptools import setup, find_packages
setup(name="grader",
# http://semver.org/spec/v2.0.0.html
version="0.0.1",
url='https://github.com/brhoades/grader',
description="A grading framework for evaluating programming assignments",
packages=find_packages('src'),
package_dir={'': ... | Move the location for grader.egg-info | Move the location for grader.egg-info
| Python | mit | redkyn/grader,redkyn/grader,grade-it/grader | ---
+++
@@ -6,7 +6,7 @@
url='https://github.com/brhoades/grader',
description="A grading framework for evaluating programming assignments",
packages=find_packages('src'),
- package_dir={'': 'src'},
+ package_dir={'': '.'},
install_requires=[
'setuptools',
'G... |
2107a8c161d8a9fe13977a0997defb35297821c2 | certbot/tests/helpers.py | certbot/tests/helpers.py | import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
run_tests_with = AsynchronousDeferredRunTest
def parse_query(uri):
"""
Pa... | import json
import testtools
from testtools.twistedsupport import AsynchronousDeferredRunTest
from uritools import urisplit
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
run_tests_with = AsynchronousDeferredRunTest.make_factory(timeout=0.01)
def parse... | Increase default test timeout value | Increase default test timeout value
| Python | mit | praekeltfoundation/certbot,praekeltfoundation/certbot | ---
+++
@@ -9,7 +9,7 @@
class TestCase(testtools.TestCase):
""" TestCase class for use with Twisted asynchornous tests. """
- run_tests_with = AsynchronousDeferredRunTest
+ run_tests_with = AsynchronousDeferredRunTest.make_factory(timeout=0.01)
def parse_query(uri): |
e8e00b0bc9c9552858f364526803eb9edcaf52c3 | 01/test_directions.py | 01/test_directions.py | from directions import load_directions, turn, follow_directions
def test_load_directions():
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
in f.readline().strip().split()]
assert load_directions("directions.txt") == direct... | from directions import load_directions, turn, follow_directions, expand_path
import unittest
class TestDirections(unittest.TestCase):
def test_load_directions(self):
with open("directions.txt") as f:
directions = [direction.strip(',')
for direction
... | Convert to unittest and add test for expand_path. | Convert to unittest and add test for expand_path.
| Python | mit | machinelearningdeveloper/aoc_2016 | ---
+++
@@ -1,37 +1,40 @@
-from directions import load_directions, turn, follow_directions
+from directions import load_directions, turn, follow_directions, expand_path
+import unittest
+
+class TestDirections(unittest.TestCase):
+ def test_load_directions(self):
+ with open("directions.txt") as f:
+ ... |
dc83fd7a77cab31b264d19984ac996bf64356fba | malcolm/core/meta.py | malcolm/core/meta.py | from collections import OrderedDict
from malcolm.core.serializable import Serializable
@Serializable.register("malcolm:core/Meta:1.0")
class Meta(Serializable):
"""Meta class for describing Blocks"""
def __init__(self, name, description):
super(Meta, self).__init__(name)
self.description = d... | from collections import OrderedDict
from malcolm.core.serializable import Serializable
@Serializable.register("malcolm:core/Meta:1.0")
class Meta(Serializable):
"""Meta class for describing Blocks"""
def __init__(self, name, description, *args):
super(Meta, self).__init__(name, *args)
self.d... | Fix Meta init and from_dict | Fix Meta init and from_dict
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm | ---
+++
@@ -7,8 +7,8 @@
class Meta(Serializable):
"""Meta class for describing Blocks"""
- def __init__(self, name, description):
- super(Meta, self).__init__(name)
+ def __init__(self, name, description, *args):
+ super(Meta, self).__init__(name, *args)
self.description = descrip... |
9f3947c3454f02a393d22ff7672598e627246ed4 | condor_data_collectors/redis_condor_info_consumer.py | condor_data_collectors/redis_condor_info_consumer.py | import htcondor
import redis
import time
import json
import classad
def setup_redis_connection():
r = redis.StrictRedis(host="htcs-master.heprc.uvic.ca", port=6379, db=0, password=~NEED THE PW HERE~)
return r
def import_condor_info():
try:
redis_con = setup_redis_connection()
condor_reso... | import htcondor
import redis
import time
import json
import classad
def setup_redis_connection():
r = redis.StrictRedis(host="htcs-master.heprc.uvic.ca", port=6379, db=0, password=~NEED THE PW HERE~)
return r
def import_condor_info():
try:
redis_con = setup_redis_connection()
condor_reso... | Update consumer to rebuild 'Start' expression tree for condor resources | Update consumer to rebuild 'Start' expression tree for condor resources
This code is untested.
| Python | apache-2.0 | hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler | ---
+++
@@ -23,6 +23,11 @@
# we must rebuild the tree from the string on this side.
req_etree = classad.ExprTree(str(job["Requirements"]))
job["Requirements"] = req_etree
+
+ for resource in condor_resources:
+ if "Start" in resource:
+ start_etr... |
bcc5a9a68f0b97b7e170cf34f9ffea00fb5441f4 | version.py | version.py | major = 0
minor=0
patch=25
branch="master"
timestamp=1376610207.69 | major = 0
minor=0
patch=26
branch="master"
timestamp=1376610243.26 | Tag commit for v0.0.26-master generated by gitmake.py | Tag commit for v0.0.26-master generated by gitmake.py
| Python | mit | ryansturmer/gitmake | ---
+++
@@ -1,5 +1,5 @@
major = 0
minor=0
-patch=25
+patch=26
branch="master"
-timestamp=1376610207.69
+timestamp=1376610243.26 |
ac83a231b393ab8212b76a2887991cd128d48345 | contact/test_settings.py | contact/test_settings.py | # Only used for running the tests
import os
CONTACT_EMAILS = ['charlie@example.com']
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
INSTALLED_APPS = ['contact', 'django.contrib.staticfiles']
ROOT_URLCONF = 'contact.test_urls'
SECRET_KEY = 'whatever'
STATIC_URL = '/static/'
TEMPLATE_DIRS = [os... | # Only used for running the tests
import os
CONTACT_EMAILS = ['charlie@example.com']
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
INSTALLED_APPS = ['contact', 'django.contrib.staticfiles']
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = 'contact.test_urls'
SECRET_KEY = 'whatever'
STATIC_URL = '/stat... | Make tests pass on Django 1.7 without warnings. | Make tests pass on Django 1.7 without warnings.
| Python | bsd-3-clause | aaugustin/myks-contact,aaugustin/myks-contact | ---
+++
@@ -8,10 +8,14 @@
INSTALLED_APPS = ['contact', 'django.contrib.staticfiles']
+MIDDLEWARE_CLASSES = []
+
ROOT_URLCONF = 'contact.test_urls'
SECRET_KEY = 'whatever'
STATIC_URL = '/static/'
+TEMPLATE_CONTEXT_PROCESSORS = ['django.core.context_processors.static']
+
TEMPLATE_DIRS = [os.path.join(os.... |
13866af8073a35c3731a208af662422788d53b19 | telegramcalendar.py | telegramcalendar.py | # This file copied from https://github.com/unmonoqueteclea/calendar-telegram
from telebot import types
import calendar
def create_calendar(year,month):
markup = types.InlineKeyboardMarkup()
#First row - Month and Year
row=[]
row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year... | # This file copied from https://github.com/unmonoqueteclea/calendar-telegram
from telebot import types
import calendar
def create_calendar(year,month):
markup = types.InlineKeyboardMarkup()
#First row - Month and Year
row=[]
row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year... | Remove day of the week row | Remove day of the week row
| Python | mit | myxo/remu,myxo/remu,myxo/remu | ---
+++
@@ -8,12 +8,6 @@
#First row - Month and Year
row=[]
row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data="ignore"))
- markup.row(*row)
- #Second row - Week Days
- week_days=["M","T","W","R","F","S","U"]
- row=[]
- for day in week_days:
- ... |
ce4dbf4d0ac3ed91c54302ec81e6838d7bf04da2 | tests/test_compound.py | tests/test_compound.py | import pytest
from katana.utils import Node, Pair, prepare
from katana.compound import sequence, group, repeat, option, maybe
from katana.term import term
Ta, Tb, Tc = [term(k) for k in 'abc']
Na, Nb, Nc = [Node(k, 'data') for k in 'abc']
def test_sequence():
s = sequence(Ta, Tb)
given = prepare([Na, Nb])
... | import pytest
from pyrsistent import v
from katana.utils import Node, Pair, prepare
from katana.compound import sequence, group, repeat, option, maybe
from katana.term import term
Ta, Tb, Tc = [term(k) for k in 'abc']
Na, Nb, Nc = [Node(k, 'data') for k in 'abc']
def test_sequence():
s = sequence(Ta, Tb)
g... | Test grouping with matched nodes | Test grouping with matched nodes
| Python | mit | eugene-eeo/katana | ---
+++
@@ -1,4 +1,5 @@
import pytest
+from pyrsistent import v
from katana.utils import Node, Pair, prepare
from katana.compound import sequence, group, repeat, option, maybe
from katana.term import term
@@ -20,6 +21,13 @@
g = group(Ta)
given = prepare([Na])
after = Pair([Node(g, [Na])], [])
+ ... |
6498d61ba18699a93689a52a43963e034b14ed84 | diecutter/utils/files.py | diecutter/utils/files.py | # -*- coding: utf-8 -*-
"""Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(... | # -*- coding: utf-8 -*-
"""Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(... | Fix tests on travis ci. | Fix tests on travis ci.
| Python | bsd-3-clause | diecutter/diecutter,diecutter/diecutter | ---
+++
@@ -32,7 +32,10 @@
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
"""Remove temporary directory recursively."""
- shutil.rmtree(self.path)
+ try:
+ shutil.rmtree(self.path)
+ except OSError:
+ pass
class chdir(object): |
155fca9e7e2c8cfee8d2600268ebae8d94b2e7fe | wagtail/search/apps.py | wagtail/search/apps.py | from django.apps import AppConfig
from django.core.checks import Tags, Warning, register
from django.db import connection
from django.utils.translation import gettext_lazy as _
from wagtail.search.signal_handlers import register_signal_handlers
from . import checks # NOQA
class WagtailSearchAppConfig(AppConfig):
... | from django.apps import AppConfig
from django.core.checks import Tags, Warning, register
from django.db import connection
from django.utils.translation import gettext_lazy as _
from wagtail.search.signal_handlers import register_signal_handlers
from . import checks # NOQA
class WagtailSearchAppConfig(AppConfig):
... | Add alternative warning if sqlite is >=3.19 but is missing fts5 support | Add alternative warning if sqlite is >=3.19 but is missing fts5 support
| Python | bsd-3-clause | wagtail/wagtail,thenewguy/wagtail,mixxorz/wagtail,rsalmaso/wagtail,zerolab/wagtail,wagtail/wagtail,mixxorz/wagtail,mixxorz/wagtail,zerolab/wagtail,thenewguy/wagtail,jnns/wagtail,jnns/wagtail,zerolab/wagtail,zerolab/wagtail,thenewguy/wagtail,wagtail/wagtail,jnns/wagtail,rsalmaso/wagtail,mixxorz/wagtail,rsalmaso/wagtail,... | ---
+++
@@ -29,6 +29,11 @@
def check_if_sqlite_version_is_supported(app_configs, **kwargs):
if connection.vendor == 'sqlite':
import sqlite3
+
+ from wagtail.search.backends.database.sqlite.utils import fts5_available
+
if sqlite3.sqlite_version_info < (3, 19, 0):
... |
1dd863336641b3e9172c9a08018386bb133960bf | whitenoise/__init__.py | whitenoise/__init__.py | from .base import WhiteNoise
__version__ = '2.0.6'
__all__ = ['WhiteNoise']
| from .base import WhiteNoise
__version__ = 'development'
__all__ = ['WhiteNoise']
| Change version until ready for release | Change version until ready for release
| Python | mit | evansd/whitenoise,evansd/whitenoise,evansd/whitenoise | ---
+++
@@ -1,5 +1,5 @@
from .base import WhiteNoise
-__version__ = '2.0.6'
+__version__ = 'development'
__all__ = ['WhiteNoise'] |
fdee121f435128ada3065e2edc08b4ae6edde2d3 | exgrep.py | exgrep.py | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-c COL Only search in the column specified by COL.
-o Only output the match... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-c COL Only search in the column specified by COL.
-r ROW Only search in the ro... | Add support for single row checking | Add support for single row checking
| Python | mit | Sakartu/excel-toolkit | ---
+++
@@ -8,6 +8,7 @@
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-c COL Only search in the column specified by COL.
+-r ROW Only search in the row specified by ROW
-o Only output the matched part
"""
import... |
0c25bef5514913239db942d96a00a499144282c0 | tests/test_config.py | tests/test_config.py | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | Check more data about riemann | Check more data about riemann
| Python | mit | CodersOfTheNight/oshino | ---
+++
@@ -29,7 +29,9 @@
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
- assert isinstance(incomplete_config.riemann, RiemannConfig)
+ obj = incomplete_config.riemann
+ assert isinstance(obj, RiemannConfig)
... |
06bc49a066958390d423294730debe75466eff1f | tests/test_models.py | tests/test_models.py | from pysagec import models
def test_auth_info():
values = [
('mrw:CodigoFranquicia', 'franchise_code', '123456'),
('mrw:CodigoAbonado', 'subscriber_code', 'subscriber_code'),
('mrw:CodigoDepartamento', 'departament_code', 'departament_code'),
('mrw:UserName', 'username', 'username'... | from pysagec import models
def test_field():
f = models.Field('tag')
assert f.__get__(None, None) is f
assert 'Field' in repr(f)
def test_model_as_dict():
class MyModel(models.Model):
root_tag = 'root'
prop1 = models.Field('tag1')
prop2 = models.Field('tag2')
model = MyM... | Make test models self contained specific defining Model classes | Make test models self contained specific defining Model classes
| Python | mit | migonzalvar/pysagec | ---
+++
@@ -1,20 +1,29 @@
from pysagec import models
-def test_auth_info():
- values = [
- ('mrw:CodigoFranquicia', 'franchise_code', '123456'),
- ('mrw:CodigoAbonado', 'subscriber_code', 'subscriber_code'),
- ('mrw:CodigoDepartamento', 'departament_code', 'departament_code'),
- ('... |
e5cf121651051ca904ccdb9409908ad43be32dc2 | tests/test_resize.py | tests/test_resize.py | import webview
from .util import run_test
from time import sleep
def test_resize():
window = webview.create_window('Set Window Size Test', 'https://www.example.org', width=800, height=600)
run_test(webview, window, resize)
def resize(window):
assert window.width == 800
assert window.height == 600
... | import webview
from .util import run_test
from time import sleep
def test_resize():
window = webview.create_window('Set Window Size Test', 'https://www.example.org', width=800, height=600)
run_test(webview, window, resize)
def resize(window):
assert window.width == 800
assert window.height == 600
... | Add delay to resize test | Add delay to resize test
| Python | bsd-3-clause | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview | ---
+++
@@ -14,5 +14,7 @@
window.resize(500, 500)
+ sleep(0.5)
+
assert window.width == 500
assert window.height == 500 |
62a8ae77a619b8ae915c9489847c5a52ef379779 | smif/http_api/app.py | smif/http_api/app.py | """Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer i... | """Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer i... | Make path to sample project shorter | Make path to sample project shorter
| Python | mit | tomalrussell/smif,willu47/smif,willu47/smif,nismod/smif,tomalrussell/smif,tomalrussell/smif,willu47/smif,nismod/smif,nismod/smif,willu47/smif,nismod/smif,tomalrussell/smif | ---
+++
@@ -16,7 +16,7 @@
"""Return a data_layer.DataInterface
"""
return DatafileInterface(
- os.path.join(os.path.dirname(__file__), '..', '..', 'smif', 'sample_project')
+ os.path.join(os.path.dirname(__file__), '..', 'sample_project')
)
|
2462595312ca7ddf38ffb6d4bcdf7515401fe7ee | tests/test_hooks.py | tests/test_hooks.py | import json
from jazzband.projects.tasks import update_project_by_hook
from jazzband.tasks import JazzbandSpinach
def post(client, hook, data, guid="abc"):
headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid}
return client.post(
"/hooks",
content_type="application/json",
data... | import json
from jazzband.projects.tasks import update_project_by_hook
from jazzband.tasks import JazzbandSpinach
def post(client, hook, data, guid="abc"):
headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid}
return client.post(
"/hooks",
content_type="application/json",
data... | Fix more of the test. | Fix more of the test.
| Python | mit | jazzband/website,jazzband/jazzband-site,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/website,jazzband/site | ---
+++
@@ -27,4 +27,4 @@
assert response.data
response_string = response.data.decode("utf-8")
assert response_string.startswith("Started updating the project using hook id repo-added-")
- mocked_schedule.assert_called_once_with(update_project_by_hook, response_string)
+ mocked_schedule.assert_ca... |
057cdbdb0cd3edb18201ca090f57908681512c76 | openupgradelib/__init__.py | openupgradelib/__init__.py | # -*- coding: utf-8 -*-
import sys
__author__ = 'Odoo Community Association (OCA)'
__email__ = 'support@odoo-community.org'
__doc__ = """A library with support functions to be called from Odoo \
migration scripts."""
__license__ = "AGPL-3"
if sys.version_info >= (3, 8):
from importlib.metadata import version, Pa... | # -*- coding: utf-8 -*-
import sys
__author__ = 'Odoo Community Association (OCA)'
__email__ = 'support@odoo-community.org'
__doc__ = """A library with support functions to be called from Odoo \
migration scripts."""
__license__ = "AGPL-3"
try:
if sys.version_info >= (3, 8):
from importlib.metadata impor... | Fix issue when running setup.py on python<3.8 | Fix issue when running setup.py on python<3.8
| Python | agpl-3.0 | OCA/openupgradelib | ---
+++
@@ -8,13 +8,17 @@
__license__ = "AGPL-3"
-if sys.version_info >= (3, 8):
- from importlib.metadata import version, PackageNotFoundError
+try:
+ if sys.version_info >= (3, 8):
+ from importlib.metadata import version, PackageNotFoundError
+ else:
+ from importlib_metadata import ver... |
f742f5ce52738da51a3adce35bad1e852691d7be | tests/__init__.py | tests/__init__.py | """
gargoyle.tests
~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from tests import * | """
gargoyle.tests
~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
class fixture(object):
"""
Works like the built in @property decorator, except that it caches the
return value for each instance. This allows you to lazy-load the fixture
on... | Add fixture decorator to make tests better | Add fixture decorator to make tests better
| Python | apache-2.0 | disqus/gutter,kalail/gutter,kalail/gutter,disqus/gutter,kalail/gutter | ---
+++
@@ -6,4 +6,28 @@
:license: Apache License 2.0, see LICENSE for more details.
"""
+
+class fixture(object):
+ """
+ Works like the built in @property decorator, except that it caches the
+ return value for each instance. This allows you to lazy-load the fixture
+ only if your test needs it, ra... |
dc43be8d6b34de47b5bcb900e7d055372c2e28cc | parseBowtieOutput.py | parseBowtieOutput.py | #!python
# Load libraries
import sys, getopt
import libPipeline
# Set constants
helpMsg ='''
SYNOPSIS
parseBowtieOutput
parseBowtieOutput [OPTIONS] [FILE]
#
DESCRIPTION
parseBowtieOutput.py
Parses Bowtie alignments into paired-end read summaries.
Prints results to stdout.
OPTIONS
-h/--he... | #!python
# Load libraries
import sys, getopt
import libPipeline
# Set constants
helpMsg ='''
SYNOPSIS
parseBowtieOutput
parseBowtieOutput [OPTIONS] [FILE]
#
DESCRIPTION
parseBowtieOutput.py
Parses Bowtie alignments into paired-end read summaries.
Required if not using SAM output.
However,... | Add note on advantages of SAM format. | Add note on advantages of SAM format.
| Python | apache-2.0 | awblocker/paired-end-pipeline,awblocker/paired-end-pipeline | ---
+++
@@ -14,6 +14,9 @@
parseBowtieOutput.py
Parses Bowtie alignments into paired-end read summaries.
+ Required if not using SAM output.
+ However, with SAM output, can parse directly using command-line tools
+ (parseSAMOutput.sh script) in 100x or so less time.
Prints results to stdout.
... |
811263573aa35361da8a8ddde03b333914e156c5 | web_utils.py | web_utils.py | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates aiohttp reque... | """Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import json_response
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates a... | Add default status=200 to async_json_out decorator | Add default status=200 to async_json_out decorator
| Python | mit | open-craft-guild/aio-feature-flags | ---
+++
@@ -6,13 +6,13 @@
from aiohttp.web import json_response
-def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
+def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
"""Turn dict output of an HTTP handler into JSON response.
... |
cd722b5125b7bbedce3d5e48823644d61a42ffe2 | pyfr/backends/cuda/blasext.py | pyfr/backends/cuda/blasext.py | # -*- coding: utf-8 -*-
import numpy as np
from pyfr.backends.cuda.provider import CudaKernelProvider
from pyfr.backends.cuda.queue import CudaComputeKernel
from pyfr.nputil import npdtype_to_ctype
class CudaBlasExtKernels(CudaKernelProvider):
def __init__(self, backend):
super(CudaBlasExtKernels, self).... | # -*- coding: utf-8 -*-
import numpy as np
from pyfr.backends.cuda.provider import CudaKernelProvider
from pyfr.backends.cuda.queue import CudaComputeKernel
from pyfr.nputil import npdtype_to_ctype
class CudaBlasExtKernels(CudaKernelProvider):
def __init__(self, backend):
super(CudaBlasExtKernels, self).... | Support large meshes on Fermi-class hardware. | Support large meshes on Fermi-class hardware.
| Python | bsd-3-clause | tjcorona/PyFR,Aerojspark/PyFR,tjcorona/PyFR,iyer-arvind/PyFR,BrianVermeire/PyFR,tjcorona/PyFR | ---
+++
@@ -22,7 +22,7 @@
cnt = y.leaddim*y.majdim
# Compute a suitable block and grid
- block = (512, 1, 1)
+ block = (1024, 1, 1)
grid = self._get_grid_for_block(block, cnt)
class AxnpbyKernel(CudaComputeKernel): |
e4106d2742ac6d4566d114f700b951b6ddb84862 | apps/__init__.py | apps/__init__.py | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))]
... | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib,logging
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py... | Add logging to error output | Add logging to error output
| Python | agpl-3.0 | indx/indx-core,indx/indx-core,indx/indx-core,indx/indx-core,indx/indx-core | ---
+++
@@ -1,7 +1,7 @@
## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
-import os,importlib
+import os,importlib,logging
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__)) |
6a74d267c83f887aae9539417b7a13a00afbcd14 | sms_auth_service/client.py | sms_auth_service/client.py | import json
import requests
SMS_AUTH_ENDPOINT = 'http://localhost:5000'
class SMSAuthClient(object):
def __init__(self, endpoint=SMS_AUTH_ENDPOINT):
self.endpoint = endpoint
def create_auth(self, auth_id, recipient):
payload = {'auth_id': auth_id,
'recipient': recipient... | import json
import requests
SMS_AUTH_ENDPOINT = 'http://localhost:5000'
class SMSAuthClient(object):
def __init__(self, endpoint=SMS_AUTH_ENDPOINT):
self.endpoint = endpoint
def create_auth(self, auth_id, recipient):
payload = {'auth_id': auth_id,
'recipient': recipient... | Add 'attempts_left' to the http exception. | Add 'attempts_left' to the http exception.
| Python | mit | flowroute/sms-verification,flowroute/sms-verification,flowroute/sms-verification | ---
+++
@@ -36,5 +36,9 @@
content = e.response.json()
e.message = content['message']
e.strerror = content['reason']
+ try:
+ e.attempts_left = content['attempts_left']
+ except:
+ pass
raise e
return respo... |
50dd73443a2bcb0e973162afab6849078e68ac51 | account_banking_payment_export/migrations/7.0.0.1.165/pre-migration.py | account_banking_payment_export/migrations/7.0.0.1.165/pre-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Akretion (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Akretion (http://www.akretion.com/)
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the... | Update SQL query with "and communication is null" | Update SQL query with "and communication is null"
| Python | agpl-3.0 | syci/bank-payment,ndtran/bank-payment,yvaucher/bank-payment,vrenaville/bank-payment,Antiun/bank-payment,rlizana/bank-payment,rschnapka/bank-payment,open-synergy/bank-payment,ndtran/bank-payment,sergio-incaser/bank-payment,hbrunn/bank-payment,rlizana/bank-payment,rschnapka/bank-payment,David-Amaro/bank-payment,yvaucher/... | ---
+++
@@ -28,4 +28,5 @@
"WHERE payment_line.order_id = payment_order.id "
"AND payment_order.state in ('draft', 'open') "
"AND payment_line.state = 'normal' "
+ "AND communication is null"
"AND communication2 is not null") |
94e6079c786444bf1177454582e3c0f4e4d2500c | discode_server/config/base_config.py | discode_server/config/base_config.py | import os
from urllib import parse
DEBUG = False
DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER')
bits = parse.urlparse(DATABASE_SA)
DATABASE = {
'user': bits.username,
'database': bits.path[1:],
'password': bits.password,
'host': bits.hostname,
'port': bits.port,
'm... | import os
from urllib import parse
DEBUG = False
DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL')
PG_BOUNCER = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER')
bits = parse.urlparse(PG_BOUNCER)
DATABASE = {
'user': bits.username,
'database': bits.path[1:],
'password': bits.passw... | Use a the regular connection for alembic | Use a the regular connection for alembic
| Python | bsd-2-clause | d0ugal/discode-server,d0ugal/discode-server,d0ugal/discode-server | ---
+++
@@ -4,9 +4,10 @@
DEBUG = False
-DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER')
+DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL')
-bits = parse.urlparse(DATABASE_SA)
+PG_BOUNCER = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER')
+bits = parse.urlparse(PG... |
696a166e039220a5431a554db3a0cb379f9a59de | djlint/analyzers/template_loaders.py | djlint/analyzers/template_loaders.py | import ast
from .base import BaseAnalyzer, Result
class TemplateLoadersVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
deprecated_items = {
'django.template.loaders.app_directories.load_template_source':
'django.template.loaders.app_directories.Loader',
'dj... | import ast
from .base import BaseAnalyzer, Result
class TemplateLoadersVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.template.loaders.app_directories.load_template_source':
'django.template.loaders.app_directories.Loader',
'djang... | Update template loaders analyzer to target Django 1.5 | Update template loaders analyzer to target Django 1.5
| Python | isc | alfredhq/djlint | ---
+++
@@ -8,7 +8,7 @@
def __init__(self):
self.found = []
- deprecated_items = {
+ removed_items = {
'django.template.loaders.app_directories.load_template_source':
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.load_template_sour... |
88d1274638e1f4d0341c5e55bdb729ae52c2b607 | accounts/models.py | accounts/models.py | from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend
@extend(User)
class Profile(object):
"""Add shortcuts to user"""
@property
def github(self):
"""Github api instance with access from user"""
token = self.social_auth.get().extra_data[... | from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend
@extend(User)
class Profile(object):
"""Add shortcuts to user"""
@property
def github(self):
"""Github api instance with access from user"""
return Github(self.github_token)
@pro... | Add ability to get github token from user model | Add ability to get github token from user model
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -10,5 +10,9 @@
@property
def github(self):
"""Github api instance with access from user"""
- token = self.social_auth.get().extra_data['access_token']
- return Github(token)
+ return Github(self.github_token)
+
+ @property
+ def github_token(self):
+ """... |
9fa3775c78b8c44b503ce1565e2e990644a61da6 | Lib/test/test_lib2to3.py | Lib/test/test_lib2to3.py | # Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
from test.test_support import run_unittest
def suite():
tests = unittest.TestSuite()
loader = unittest.TestLoader()
for m in (test_fixers,test_pytree,test_util):
... | # Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
from test.test_support import run_unittest, requires
# Don't run lib2to3 tests by default since they take too long
if __name__ != '__main__':
requires('lib2to3')
def suite(... | Disable lib2to3 by default, unless run explicitly. | Disable lib2to3 by default, unless run explicitly.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -2,7 +2,11 @@
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
-from test.test_support import run_unittest
+from test.test_support import run_unittest, requires
+
+# Don't run lib2to3 tests by default since they take too long
+if __name__ != '__main__':
... |
8efde6f0fee26a2e83a0191bd21f78061ff92e8c | fedora.py | fedora.py | from fedora.template.fedora import FedoraTemplate
from fedora.manager.manager import FedoraConnectionManager
if '__main__' == __name__:
fedoraTemplate = FedoraTemplate()
a = FedoraConnectionManager("http://localhost:8080/rest/hand/english/fcr:metadata", templates=[FedoraTemplate()]);
print a.__dict__
| from fedora.template.fedora import FedoraTemplate
from fedora.manager.manager import FedoraConnectionManager
if '__main__' == __name__:
fedoraTemplate = FedoraTemplate()
parser = FedoraConnectionManager("http://localhost:8080/rest/hand/english/fcr:metadata", templates=[FedoraTemplate()]);
data = parser.ret... | Update code for support new methodology | Update code for support new methodology
| Python | mit | sitdh/fedora-parser | ---
+++
@@ -3,6 +3,7 @@
if '__main__' == __name__:
fedoraTemplate = FedoraTemplate()
- a = FedoraConnectionManager("http://localhost:8080/rest/hand/english/fcr:metadata", templates=[FedoraTemplate()]);
+ parser = FedoraConnectionManager("http://localhost:8080/rest/hand/english/fcr:metadata", templates=[... |
84dee56df90d9181d1e79c3246ef389462f0ca17 | configure_console_session.py | configure_console_session.py | import sys
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/caar'
sys.path.append(PYTHONPATH)
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/backports'
sys.path.append(PYTHONPATH)
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/backports/configparser'
sys.path.append(PYTHONPATH)
from comfort import cleanthermostat a... | import sys
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/caar'
sys.path.append(PYTHONPATH)
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/backports'
sys.path.append(PYTHONPATH)
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/backports/configparser'
sys.path.append(PYTHONPATH)
from caar.cleanthermostat import dict... | Put imports as they are in init | Put imports as they are in init
| Python | bsd-3-clause | nickpowersys/CaaR | ---
+++
@@ -5,11 +5,32 @@
sys.path.append(PYTHONPATH)
PYTHONPATH = '/home/nick/PycharmProjs/tl_cycling/backports/configparser'
sys.path.append(PYTHONPATH)
-from comfort import cleanthermostat as ct
-from comfort import history as hi
-from comfort import histdaily as hd
-from comfort import histsummary as hs
+from ... |
30259313a817f2d5f147dc37ebf5ebd2c2edf943 | configurator/__init__.py | configurator/__init__.py | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | Disable redirecting git output in _get_version | Disable redirecting git output in _get_version
| Python | apache-2.0 | yasserglez/configurator,yasserglez/configurator | ---
+++
@@ -16,7 +16,7 @@
git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir,
"describe", "--tags", "--dirty")
with open(os.devnull, "w") as devnull:
- output = subprocess.check_output(git_args, stderr=devnull)
+ output = subprocess.check_outpu... |
8e7f793abc012e136fa5ec0f2c003704ab98f751 | src/nodeconductor_assembly_waldur/experts/filters.py | src/nodeconductor_assembly_waldur/experts/filters.py | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... | Allow to filter expert bids by a customer | Allow to filter expert bids by a customer [WAL-1169]
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -36,6 +36,8 @@
class ExpertBidFilter(django_filters.FilterSet):
request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid')
request_uuid = django_filters.UUIDFilter(name='request__uuid')
+ customer = core_filters.URLFilter(view_name='customer-detail', name='team_... |
f41adb3b11a572251949778ed3fa49cd0c3901c7 | AFQ/tests/test_csd.py | AFQ/tests/test_csd.py | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data()
with nbtmp.InTemporaryDirectory() ... | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryD... | Replace the test data set with this one. | Replace the test data set with this one.
| Python | bsd-2-clause | arokem/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ,yeatmanlab/pyAFQ | ---
+++
@@ -13,14 +13,14 @@
def test_fit_csd():
- fdata, fbval, fbvec = dpd.get_data()
+ fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(... |
164c70386191f0761923c1344447b8fac0e0795c | pelican/settings.py | pelican/settings.py | import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
... | import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
... | Add a default for JINJA_EXTENSIONS (default is no extensions) | Add a default for JINJA_EXTENSIONS (default is no extensions)
| Python | agpl-3.0 | treyhunner/pelican,joetboole/pelican,janaurka/git-debug-presentiation,goerz/pelican,JeremyMorgan/pelican,Polyconseil/pelican,deved69/pelican-1,JeremyMorgan/pelican,douglaskastle/pelican,farseerfc/pelican,51itclub/pelican,florianjacob/pelican,liyonghelpme/myBlog,levanhien8/pelican,lucasplus/pelican,btnpushnmunky/pelican... | ---
+++
@@ -22,6 +22,7 @@
'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls
'RELATIVE_URLS': True,
'DEFAULT_LANG': 'en',
+ 'JINJA_EXTENSIONS': [],
}
def read_settings(filename): |
1e6fcb420c0cd3c41afd8a91ec020b6e15cf1973 | client/views.py | client/views.py | from django.shortcuts import render
# Create your views here.
| from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Message
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def chatroom(request):
messages = Message.objects.order_by('date')
context = {'messages': messages}
... | Add login restrictions to chatroom | Add login restrictions to chatroom
| Python | apache-2.0 | jason-feng/chatroom,jason-feng/chatroom,jason-feng/chatroom,jason-feng/chatroom | ---
+++
@@ -1,3 +1,12 @@
from django.shortcuts import render
+from django.http import HttpResponse, Http404
+from .models import Message
+from django.contrib.auth.decorators import login_required
# Create your views here.
+
+@login_required
+def chatroom(request):
+ messages = Message.objects.order_by('date')
... |
429738972be911f6b05358c918f822270eb94da7 | botbot/checks.py | botbot/checks.py | """Functions for checking files"""
import os
import stat
import mimetypes
from .checker import is_link
from .config import CONFIG
def is_fastq(fi):
"""Check whether a given file is a fastq file."""
path = fi['path']
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return... | """Functions for checking files"""
import os
import stat
import mimetypes
from .checker import is_link
from .config import CONFIG
def is_fastq(fi):
"""Check whether a given file is a fastq file."""
path = fi['path']
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return... | Fix SAM checker to for better coverage | Fix SAM checker to for better coverage
| Python | mit | jackstanek/BotBot,jackstanek/BotBot | ---
+++
@@ -22,6 +22,9 @@
return 'PROB_SAM_AND_BAM_EXIST'
else:
return 'PROB_SAM_SHOULD_COMPRESS'
+ elif ext == '.bam':
+ if os.path.isfile('.'.join((name, 'sam'))):
+ return 'PROB_SAM_SHOULD_COMPRESS'
def is_large_plaintext(fi):
"""Detect if a file plai... |
af8d25d74dbbfcb25bcdfb454125d834644bc1bc | bin/app_setup.py | bin/app_setup.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import hook_system_variables as hook
import os_operations as op
import os
def setup():
home_dir = op.get_home()
app_tree = home_dir + op.separator() + hook.data_storage_path
if not os.path.exists(app_tree):
op.create_tree(app_tree)
else:
pri... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import hook_system_variables as hook
import os_operations as op
import os
def setup():
home_dir = op.get_home()
app_tree = home_dir + op.separator() + hook.data_storage_path
if not os.path.exists(app_tree):
op.create_tree(app_tree)
file_absolute_... | Append G(app) to os $PATH | Append G(app) to os $PATH
| Python | mit | adnane1deev/Hook | ---
+++
@@ -12,6 +12,13 @@
if not os.path.exists(app_tree):
op.create_tree(app_tree)
-
+ file_absolute_path = os.path.abspath(__file__)
+ base_dir = os.path.split(file_absolute_path)[0]
+ hook_absolute_path = base_dir.rsplit(op.separator(), 1)[0]
+ append_hook_to_sys_path(h... |
f12120dd9a7660277b52cd25f8cfa48b3783eece | rest_framework_friendly_errors/handlers.py | rest_framework_friendly_errors/handlers.py | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not... | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not... | Create new exception to catch APIException | Create new exception to catch APIException
| Python | mit | oasiswork/drf-friendly-errors,FutureMind/drf-friendly-errors | ---
+++
@@ -9,7 +9,8 @@
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
- response = exception_handler(APIException(exc), context)
+ exc = APIException(exc)
+ response = exception_handler(exc, context)
if response is not None:
... |
d8a7abd16e115e142299a4c1ed01b18b15a5b806 | tests/test_hashring.py | tests/test_hashring.py | from hashring import HashRing
def test_basic_ring():
hr = HashRing(range(3))
actual = hr.get_node('howdy')
expected = 1
assert expected == actual
| from hashring import HashRing
def test_basic_ring():
hr = HashRing(range(3))
actual = hr.get_node('howdy')
expected = 1
assert expected == actual
def test_server_ring():
memcache_servers = ['192.168.0.246:11212',
'192.168.0.247:11212',
'192.168.0.24... | Add additional test for strings | Add additional test for strings
| Python | bsd-2-clause | goller/hashring | ---
+++
@@ -5,3 +5,14 @@
actual = hr.get_node('howdy')
expected = 1
assert expected == actual
+
+
+def test_server_ring():
+ memcache_servers = ['192.168.0.246:11212',
+ '192.168.0.247:11212',
+ '192.168.0.249:11212']
+
+ ring = HashRing(memcache_serv... |
ab247f37b72bf833dfb32c93d01e6889642b109e | cfr/game_tree.py | cfr/game_tree.py | from cfr.constants import NUM_ACTIONS
class Node:
def __init__(self, parent):
super().__init__()
self.parent = parent
self.children = {}
def set_child(self, key, child):
self.children[key] = child
class TerminalNode(Node):
def __init__(self, parent, pot_commitment):
... | from cfr.constants import NUM_ACTIONS
class Node:
def __init__(self, parent):
super().__init__()
self.parent = parent
self.children = {}
def set_child(self, key, child):
self.children[key] = child
def __str__(self):
if not self.parent:
return ''
... | Add str method for debugging to node | Add str method for debugging to node
| Python | mit | JakubPetriska/poker-cfr,JakubPetriska/poker-cfr | ---
+++
@@ -9,6 +9,27 @@
def set_child(self, key, child):
self.children[key] = child
+
+ def __str__(self):
+ if not self.parent:
+ return ''
+ parent_str = str(self.parent)
+ parents_children = list(filter(lambda item: item[1] == self, self.parent.children.items()))... |
16c5c9e89a6cf565070ab58d55a7796ea3183ced | coltrane/managers.py | coltrane/managers.py | from comment_utils.managers import CommentedObjectManager
from django.db import models
class LiveEntryManager(CommentedObjectManager):
"""
Custom manager for the Entry model, providing shortcuts for
filtering by entry status.
"""
def featured(self):
"""
Returns a ``QuerySet`` ... | from comment_utils.managers import CommentedObjectManager
from django.db import models
class LiveEntryManager(CommentedObjectManager):
"""
Custom manager for the Entry model, providing shortcuts for
filtering by entry status.
"""
def featured(self):
"""
Returns a ``QuerySet`` ... | Add the support for the new module constants to the LiveEntryManager | Add the support for the new module constants to the LiveEntryManager
git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@71 5f8205a5-902a-0410-8b63-8f478ce83d95
| Python | bsd-3-clause | mafix/coltrane-blog,clones/django-coltrane | ---
+++
@@ -21,7 +21,7 @@
with a status of 'live'.
"""
- return super(LiveEntryManager, self).get_query_set().filter(status__exact=1)
+ return super(LiveEntryManager, self).get_query_set().filter(status__exact=self.model.LIVE_STATUS)
def latest_featured(self):
... |
1a511f23acc873c95ed60e8a918bff5c6ba68ebc | deployment/websocket_wsgi.py | deployment/websocket_wsgi.py | import os
import gevent.socket
import redis.connection
from manage import _set_source_root_parent, _set_source_root
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
_set_source_root_parent('submodules')
_set_source_root(os.path.join('corehq', 'ex-submodules'))
_set_source_root(os.path.join('custom', '_lega... | import os
import gevent.socket
import redis.connection
from manage import init_hq_python_path, run_patches
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
init_hq_python_path()
run_patches()
redis.connection.socket = gevent.socket
from ws4redis.uwsgi_runserver import uWSGIWebsocketServer
application = uW... | Fix websockets process after celery upgrade | Fix websockets process after celery upgrade
make it do the same patching that manage.py does
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,13 +1,12 @@
import os
import gevent.socket
import redis.connection
-from manage import _set_source_root_parent, _set_source_root
+from manage import init_hq_python_path, run_patches
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
-_set_source_root_parent('submodules')
-_set_source_ro... |
44e1b892716b74a3730da92365669f1353eb267e | cyder/cydhcp/validation.py | cyder/cydhcp/validation.py | from django.core.exceptions import ValidationError
import re
mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$')
def validate_mac(mac):
if not isinstance(mac, basestring) or not mac_pattern.match(mac):
raise ValidationError('Invalid MAC address')
| from django.core.exceptions import ValidationError
import re
mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$')
def validate_mac(mac):
if not isinstance(mac, basestring) or not mac_pattern.match(mac) \
or mac == '00:00:00:00:00:00':
raise ValidationError('Invalid MAC address')
| Make 00:00:00:00:00:00 an invalid MAC address | Make 00:00:00:00:00:00 an invalid MAC address
| Python | bsd-3-clause | OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,zeeman/cyder,murrown/cyder,zeeman/cyder,murrown/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,akeym/cyder,akeym/cyder,akeym/cyder,drkitty/cyder | ---
+++
@@ -5,5 +5,6 @@
mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$')
def validate_mac(mac):
- if not isinstance(mac, basestring) or not mac_pattern.match(mac):
+ if not isinstance(mac, basestring) or not mac_pattern.match(mac) \
+ or mac == '00:00:00:00:00:00':
raise Valid... |
3ac4264b9242e0261735e35401a4a750489a6f0e | test/__init__.py | test/__init__.py | # Copyright 2010 10gen, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | # Copyright 2010 10gen, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Clean up all test dbs after test run. | Clean up all test dbs after test run.
| Python | apache-2.0 | develf/mongo-python-driver,ultrabug/mongo-python-driver,aherlihy/mongo-python-driver,jbenet/mongo-python-driver,aherlihy/mongo-python-driver,ShaneHarvey/mongo-python-driver,jbenet/mongo-python-driver,felixonmars/mongo-python-driver,felixonmars/mongo-python-driver,pigate/mongo-python-driver,WingGao/mongo-python-driver,b... | ---
+++
@@ -26,3 +26,4 @@
c.drop_database("pymongo_test1")
c.drop_database("pymongo_test2")
c.drop_database("pymongo_test_mike")
+ c.drop_database("pymongo_test_bernie") |
d772a2333f0d9736a87180dcfb29000bccee8e19 | spreadflow_thumbor/proc.py | spreadflow_thumbor/proc.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from libthumbor import CryptoURL
class ThumborService(object):
def __init__(self, baseurl='http://localhost:8888/', secretkey='MY_SECURE_KEY'):
self.baseurl = baseurl.rstrip('/')
self._u... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from libthumbor import CryptoURL
class ThumborService(object):
def __init__(self, baseurl='http://localhost:8888/', secretkey='MY_SECURE_KEY'):
self.baseurl = baseurl.rstrip('/')
self._u... | Use identity operator when comparing with None | Use identity operator when comparing with None
| Python | mit | znerol/spreadflow-thumbor | ---
+++
@@ -23,7 +23,7 @@
self.options = options
self.optionskey = optionskey
- if not (self.options == None) ^ (self.optionskey == None):
+ if not (self.options is None) ^ (self.optionskey is None):
raise ValueError('Either options or optionskey is required')
def... |
5255a72c266f8ab092a02b6d87f7006f2149560e | vortaro/admin.py | vortaro/admin.py | from bonvortaro.vortaro.models import Root, Word, Definition #, Translation
from django.contrib import admin
class RootAdmin(admin.ModelAdmin):
list_display = ["root", "kind", "begining", "ending", "ofc"]
list_filter = ["begining", "ending", "kind", "ofc"]
admin.site.register(Root, RootAdmin)
class WordAdmin... | from bonvortaro.vortaro.models import Root, Word, Definition #, Translation
from django.contrib import admin
class RootAdmin(admin.ModelAdmin):
list_display = ["root", "kind", "begining", "ending", "ofc"]
list_filter = ["begining", "ending", "kind", "ofc"]
admin.site.register(Root, RootAdmin)
class WordAdmin... | Reorder filters to make the easier to use. | Reorder filters to make the easier to use.
| Python | agpl-3.0 | pupeno/bonvortaro | ---
+++
@@ -9,7 +9,7 @@
class WordAdmin(admin.ModelAdmin):
list_display = ["language", "word", "kind", "begining", "root", "ending", "ofc", "mrk", "revo_link"]
- list_filter = ["ending", "kind", "ofc", "begining", "language"]
+ list_filter = ["kind", "ofc", "language", "ending", "begining"]
d... |
4f8c653f877067703acf7146bc3732152b3f8f62 | dax/constants.py | dax/constants.py | import os
from os.path import expanduser
USER_HOME = expanduser("~")
#MASIMATLAB dir:
if 'MASIMATLAB_PATH' not in os.environ:
MASIMATLAB_PATH = os.path.join(USER_HOME,'masimatlab')
else:
MASIMATLAB_PATH = os.environ['MASIMATLAB']
#Result dir
if 'UPLOAD_SPIDER_DIR' not in os.environ:
RESULTS_DIR=os.path.join(US... | import os
from os.path import expanduser
USER_HOME = expanduser("~")
#MASIMATLAB dir:
if 'MASIMATLAB_PATH' not in os.environ:
MASIMATLAB_PATH = os.path.join(USER_HOME,'masimatlab')
else:
MASIMATLAB_PATH = os.environ['MASIMATLAB_PATH']
#Result dir
if 'UPLOAD_SPIDER_DIR' not in os.environ:
RESULTS_DIR=os.p... | Fix bug and correct indentation | Fix bug and correct indentation | Python | mit | MattVUIIS/dax,MattVUIIS/dax,MattVUIIS/dax,MattVUIIS/dax,VUIIS/dax,VUIIS/dax | ---
+++
@@ -5,14 +5,14 @@
#MASIMATLAB dir:
if 'MASIMATLAB_PATH' not in os.environ:
- MASIMATLAB_PATH = os.path.join(USER_HOME,'masimatlab')
+ MASIMATLAB_PATH = os.path.join(USER_HOME,'masimatlab')
else:
- MASIMATLAB_PATH = os.environ['MASIMATLAB']
+ MASIMATLAB_PATH = os.environ['MASIMATLAB_PATH']
#Res... |
e289f1d604245e48954c09b39091a80beff39e34 | django_remote_forms/utils.py | django_remote_forms/utils.py | from django.utils.functional import Promise
from django.utils.translation import force_unicode
def resolve_promise(o):
if isinstance(o, dict):
for k, v in o.items():
o[k] = resolve_promise(v)
elif isinstance(o, (list, tuple)):
o = [resolve_promise(x) for x in o]
elif isinstance... | from django.utils.functional import Promise
from django.utils.encoding import force_unicode
def resolve_promise(o):
if isinstance(o, dict):
for k, v in o.items():
o[k] = resolve_promise(v)
elif isinstance(o, (list, tuple)):
o = [resolve_promise(x) for x in o]
elif isinstance(o, ... | Update import to correct path for Django 1.4->1.6 compatibility | Update import to correct path for Django 1.4->1.6 compatibility
| Python | mit | gadventures/django-remote-forms | ---
+++
@@ -1,6 +1,5 @@
from django.utils.functional import Promise
-from django.utils.translation import force_unicode
-
+from django.utils.encoding import force_unicode
def resolve_promise(o):
if isinstance(o, dict): |
fb5117e653b7a47f4af35d2c19ada9da15458ae3 | tmpl/Platform.py | tmpl/Platform.py | #--coding:utf-8--
#Platform
class BasePlatform(object):
"""
A template for codes which are dependent on platform, whatever shell type or system type.
Redefine members to modify the function.
"""
def __init__(self, shell = False):
if shell:
if os.name == 'posix':
... | #--coding:utf-8--
#Platform
class BasePlatform(object):
"""
A template for codes which are dependent on platform, whatever shell type or system type.
Redefine members to modify the function.
"""
def __init__(self, shell = False):
if shell:
if os.name == 'posix':
... | Fix the compile error of define classes which derivate from other classes in class. | Fix the compile error of define classes which derivate from other classes in class.
| Python | mit | nday-dev/Spider-Framework | ---
+++
@@ -32,34 +32,34 @@
"""
pass
- class Shell(self.Common):
+ class Shell(Common):
"""
Redefine members here for those which will be inherited to all shells.
"""
pass
- class System(self.Common):
+ class System(Common):
"""
R... |
ba48cd45c56646497bcda70d9a475a40ea44c874 | dbaas/workflow/steps/mysql/resize/change_config.py | dbaas/workflow/steps/mysql/resize/change_config.py | # -*- coding: utf-8 -*-
import logging
from . import run_vm_script
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
... | # -*- coding: utf-8 -*-
import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workfl... | Add is_ha variable to change config rollback | Add is_ha variable to change config rollback
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import logging
-from . import run_vm_script
-from ...util.base import BaseStep
+from workflow.steps.mysql.resize import run_vm_script
+from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
@@ -28,6 +28,7 @@
def undo(self, workflow_d... |
3c855de1b69dac3242d16574188905593330a9b7 | bh_sshcmd.py | bh_sshcmd.py | import paramiko # pip install paramiko
import os
def ssh_command(ip, user, command):
# you can run this script as
# SSH_PRIV_KEY=[your private key path] python bh_sshcmd.py
key = paramiko.RSAKey.from_private_key_file(os.getenv('SSH_PRIV_KEY'))
client = paramiko.SSHClient()
client.set_missing_hos... | import paramiko # pip install paramiko
import os
def ssh_command(ip, user, command):
# you can run this script as
# SSH_PRIV_KEY=[your private key path] python bh_sshcmd.py
key = paramiko.RSAKey.from_private_key_file(os.getenv('SSH_PRIV_KEY'))
client = paramiko.SSHClient()
client.set_missing_hos... | Add correct ip for my test | Add correct ip for my test
| Python | mit | inakidelamadrid/bhp_exercises | ---
+++
@@ -19,4 +19,4 @@
print(ssh_session.recv(1024))
return
-ssh_command('52.35.195.113', 'ubuntu', 'id')
+ssh_command('127.0.0.1', 'ubuntu', 'id') |
981ff326ffd104e4665e31d8a38a62a854aa7a4d | count_cameras.py | count_cameras.py | import cv2
# Get the number of cameras available
def count_cameras():
max_tested = 100
for i in range(max_tested):
temp_camera = cv2.VideoCapture(i)
if temp_camera.isOpened():
temp_camera.release()
continue
return i
print(count_cameras())
| import cv2
# Get the number of cameras available
def count_cameras():
max_tested = 100
for i in range(max_tested):
temp_camera = cv2.VideoCapture(i)
if temp_camera.isOpened():
temp_camera.release()
continue
return i
print(count_cameras())
| Create number of available cameras via OpenCV | Create number of available cameras via OpenCV | Python | mit | foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard | ---
+++
@@ -11,3 +11,4 @@
return i
print(count_cameras())
+ |
d56ffde056a7758539ce834943ceb0f656e795a8 | CI/syntaxCheck.py | CI/syntaxCheck.py | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/Appl... | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/Appl... | Fix missing test probably got removed in my clumsy merge | Fix missing test
probably got removed in my clumsy merge
| Python | bsd-3-clause | fran-jo/OpenIPSL,tinrabuzin/OpenIPSL,SmarTS-Lab/OpenIPSL,SmarTS-Lab/OpenIPSL,MaximeBaudette/OpenIPSL,OpenIPSL/OpenIPSL | ---
+++
@@ -11,6 +11,7 @@
"AKD":"/ApplicationExamples/AKD/package.mo",
"N44":"/ApplicationExamples/N44/package.mo",
"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
+"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests |
3a2d2934f61c496654281da7144f74713a9dea6f | devicehive/api.py | devicehive/api.py | from devicehive.transport import Request
from devicehive.transport import Response
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
... | class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
... | Add Request, Response and ApiObject and Token classes | Add Request, Response and ApiObject and Token classes
| Python | apache-2.0 | devicehive/devicehive-python | ---
+++
@@ -1,9 +1,25 @@
-from devicehive.transport import Request
-from devicehive.transport import Response
+class Request(object):
+ """Request class."""
+
+ def __init__(self, url, action, request, **params):
+ self.action = action
+ self.request = request
+ self.params = params
+ ... |
02ac33ae0f7a6279df3f049e291fed6556b1c481 | dhcp2nest/util.py | dhcp2nest/util.py | """
Utility functions for dhcp2nest
"""
from queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
def follow_file(fn, max_lines=100):
"""
Return a Queue that is fed lines (up to max_lines) from the given file (fn)
continuously
The implementation given here was inspired b... | """
Utility functions for dhcp2nest
"""
from queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
def follow_file(fn, max_lines=100):
"""
Return a Queue that is fed lines (up to max_lines) from the given file (fn)
continuously
The implementation given here was inspired b... | Make sure the tail subprocess does not actually list any prior records | Make sure the tail subprocess does not actually list any prior records
Signed-off-by: Jason Bernardino Alonso <f71c42a1353bbcdbe07e24c2a1c893f8ea1d05ee@hackorp.com>
| Python | mit | jbalonso/dhcp2nest | ---
+++
@@ -19,7 +19,7 @@
# Declare the helper routine
def _follow_file_thread(fn, fq):
# Use system tail with name-based following and retry
- p = Popen(["tail", "-F", fn], stdout=PIPE)
+ p = Popen(["tail", "-n0", "-F", fn], stdout=PIPE)
# Loop forever on pulling data from... |
a303756c2e2735f5eb14b525b98894e985b40baf | csunplugged/general/management/commands/updatedata.py | csunplugged/general/management/commands/updatedata.py | """Module for the custom Django updatedata command."""
from django.core import management
class Command(management.base.BaseCommand):
"""Required command class for the custom Django updatedata command."""
help = "Update all data from content folders for all applications"
def add_arguments(self, parser)... | """Module for the custom Django updatedata command."""
from django.core import management
class Command(management.base.BaseCommand):
"""Required command class for the custom Django updatedata command."""
help = "Update all data from content folders for all applications"
def add_arguments(self, parser)... | Remove invalid argument for load command | Remove invalid argument for load command
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -26,5 +26,5 @@
management.call_command("loadgeneralpages", lite_load=lite_load)
management.call_command("loadclassicpages", lite_load=lite_load)
management.call_command("loadactivities", lite_load=lite_load)
- management.call_command("load_at_a_distance_data", lite_load=li... |
ce47045bec5a3446063f192d04203b67dd4ab895 | scikits/audiolab/soundio/setup.py | scikits/audiolab/soundio/setup.py | #! /usr/bin/env python
# Last Change: Mon Dec 08 03:00 PM 2008 J
from os.path import join
import os
import warnings
from setuphelp import info_factory, NotFoundError
def configuration(parent_package='', top_path=None, package_name='soundio'):
from numpy.distutils.misc_util import Configuration
config = Confi... | #! /usr/bin/env python
# Last Change: Mon Dec 08 03:00 PM 2008 J
from os.path import join
import os
import warnings
from setuphelp import info_factory, NotFoundError
def configuration(parent_package='', top_path=None, package_name='soundio'):
from numpy.distutils.misc_util import Configuration
config = Confi... | Fix name of macosx backend. | Fix name of macosx backend.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab | ---
+++
@@ -25,7 +25,7 @@
classname='CoreAudioInfo')()
try:
core_audio_config = core_audio_info.get_info(2)
- config.add_extension("maxosx_backend", sources=["macosx/macosx_backend.c"],
+ config.add_extension("macosx_backend", sources=["macosx/macosx_backend.c... |
35c643aef0cb6b194e62cd5f2fcf7df98bf46870 | django_lightweight_queue/management/commands/queue_deduplicate.py | django_lightweight_queue/management/commands/queue_deduplicate.py | from django.core.management.base import BaseCommand, CommandError
from ...utils import get_backend
class Command(BaseCommand):
help = "Command to deduplicate tasks in a redis-backed queue"
def add_arguments(self, parser):
parser.add_argument(
'queue',
action='store',
... | from django.core.management.base import BaseCommand, CommandError
from ...utils import get_backend
class Command(BaseCommand):
help = "Command to deduplicate tasks in a redis-backed queue"
def add_arguments(self, parser):
parser.add_argument(
'queue',
action='store',
... | Improve output when no deduplication happened | Improve output when no deduplication happened
| Python | bsd-3-clause | thread/django-lightweight-queue,thread/django-lightweight-queue | ---
+++
@@ -26,9 +26,16 @@
original_size, new_size = backend.deduplicate(queue)
- self.stdout.write(
- "Deduplication reduced the queue from %d jobs to %d job(s)" % (
- original_size,
- new_size,
- ),
- )
+ if original_size == new_s... |
2cd634d22c74c742b0feb2aceef06c610a0fa378 | test/test_featurecounts.py | test/test_featurecounts.py | import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data... | import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data... | Fix featureCounts test following change in consensus nomenclature in FeatureCounts obj | Fix featureCounts test following change in consensus nomenclature in FeatureCounts obj
| Python | bsd-3-clause | sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana | ---
+++
@@ -14,10 +14,7 @@
assert fc.get_most_probable_strand_consensus(RNASEQ_DIR_2, tolerance=0.1) == "2"
try:
- fc.get_most_probable_strand_consensus(RNASEQ_DIR_undef, tolerance=0.1)
- assert False
- except IOError:
- assert True
+ assert fc.get_most_probable_strand_conse... |
a0556156651b6c8f5dd230ba99998efa890e1506 | test/unit/test_template.py | test/unit/test_template.py | # Copyright (c) 2013, Sascha Peilicke <saschpe@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHO... | # Copyright (c) 2013, Sascha Peilicke <saschpe@gmx.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHO... | Adjust template path after change | Adjust template path after change
| Python | apache-2.0 | saschpe/rapport | ---
+++
@@ -26,5 +26,5 @@
for type in ["plugin", "email", "web"]:
template_dirs = rapport.template._get_template_dirs(type)
self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs)
- self.assertIn(os.path.join("templates", type), ... |
b57bd821f0df367aaf0c993bce87c60875b813d2 | scikits/image/__init__.py | scikits/image/__init__.py | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import gzip
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--e... | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import gzip
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--e... | Fix Python 3 import error | Fix Python 3 import error | Python | bsd-3-clause | youprofit/scikit-image,michaelaye/scikit-image,robintw/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,Hiyorimi/scikit-image,chintak/scikit-image,chintak/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,almarklein/scikit-image,dpshelio/scikit-image... | ---
+++
@@ -47,4 +47,4 @@
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
return logging.getLogger(name)
-from util.dtype import *
+from .util.dtype import * |
de907a982f172a43e9997b5f41e53bb5ee89a5eb | Functions/Join.py | Functions/Join.py | '''
Created on Dec 20, 2011
@author: Tyranic-Moron
'''
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'join <channel> - makes the bot join the specified channel(s)'
def ... | '''
Created on Dec 20, 2011
@author: Tyranic-Moron
'''
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'join <channel> - makes the bot join the specified channel(s)'
def ... | Update list of channels when joining a new one | Update list of channels when joining a new one
| Python | mit | HubbeKing/Hubbot_Twisted | ---
+++
@@ -29,6 +29,7 @@
if not channel.startswith('#'):
channel = '#' + channel
responses.append(IRCResponse(ResponseType.Raw, 'JOIN %s' % channel, ''))
+ HubbeBot.channels.append(channel)
return responses
else:
... |
eb8f38301a4a61be121be1ff6b985f74871a0aa5 | frappe/core/doctype/deleted_document/deleted_document.py | frappe/core/doctype/deleted_document/deleted_document.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe import _
class DeletedDocument(Document):
pass
@frappe.whitelist()
d... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe import _
class DeletedDocument(Document):
pass
@frappe.whitelist()
d... | Fix indentation which causes error on restore | Fix indentation which causes error on restore
Fixes error message, that document with a specific number already exists, even if it doesn't. | Python | mit | saurabh6790/frappe,manassolanki/frappe,tundebabzy/frappe,adityahase/frappe,neilLasrado/frappe,manassolanki/frappe,tmimori/frappe,tundebabzy/frappe,RicardoJohann/frappe,mhbu50/frappe,frappe/frappe,tmimori/frappe,neilLasrado/frappe,tundebabzy/frappe,RicardoJohann/frappe,saurabh6790/frappe,yashodhank/frappe,neilLasrado/fr... | ---
+++
@@ -18,8 +18,8 @@
doc.insert()
except frappe.DocstatusTransitionError:
frappe.msgprint(_("Cancelled Document restored as Draft"))
- doc.docstatus = 0
- doc.insert()
+ doc.docstatus = 0
+ doc.insert()
doc.add_comment('Edit', _('restored {0} as {1}').format(deleted.dele... |
eb1c913a0800e2d5eabf34e7abce96c8f4096d79 | marble/tests/test_neighbourhoods.py | marble/tests/test_neighbourhoods.py | """ Tests for the extraction of neighbourhoods """
from nose.tools import *
import marble as mb
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
| """ Tests for the extraction of neighbourhoods """
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
from marble.neighbourhoods import _adjacency
#
# Synthetic data for tests
#
def grid():
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = ... | Test the adjacency matrix finder | Test the adjacency matrix finder
| Python | bsd-3-clause | scities/marble,walkerke/marble | ---
+++
@@ -1,7 +1,43 @@
""" Tests for the extraction of neighbourhoods """
from nose.tools import *
+import itertools
+from shapely.geometry import Polygon
import marble as mb
+from marble.neighbourhoods import _adjacency
+
+
+#
+# Synthetic data for tests
+#
+def grid():
+ au = [i*3+j for i,j in itertools.... |
bc021f416530375066c67c117995bd44c2bac7d5 | timezone_field/__init__.py | timezone_field/__init__.py | from .fields import TimeZoneField # noqa
from .forms import TimeZoneFormField # noqa
__version__ = '1.0'
| __version__ = '1.0'
__all__ = ['TimeZoneField', 'TimeZoneFormField']
from timezone_field.fields import TimeZoneField
from timezone_field.forms import TimeZoneFormField
| Add and __all__ designator to top-level | Add and __all__ designator to top-level
| Python | bsd-2-clause | mfogel/django-timezone-field | ---
+++
@@ -1,4 +1,5 @@
-from .fields import TimeZoneField # noqa
-from .forms import TimeZoneFormField # noqa
+__version__ = '1.0'
+__all__ = ['TimeZoneField', 'TimeZoneFormField']
-__version__ = '1.0'
+from timezone_field.fields import TimeZoneField
+from timezone_field.forms import TimeZoneFormField |
c998588fcc990f077a4f6d34f7d078c54aca1b3b | modules/google-earth-engine/docker/sepal-ee/sepal/drive/__init__.py | modules/google-earth-engine/docker/sepal-ee/sepal/drive/__init__.py | from threading import local
from apiclient import discovery
_local = local()
def get_service(credentials):
service = getattr(_local, 'service', None)
if not service:
service = discovery.build(serviceName='drive', version='v3', cache_discovery=False, credentials=credentials)
_local.service = ... | import logging
from threading import local
from apiclient import discovery
_local = local()
logging.getLogger('googleapiclient').setLevel(logging.WARNING)
def get_service(credentials):
service = getattr(_local, 'service', None)
if not service:
service = discovery.build(serviceName='drive', version='... | Set googleapiclient logging level to WARNING. | Set googleapiclient logging level to WARNING.
| Python | mit | openforis/sepal,openforis/sepal,openforis/sepal,openforis/sepal,openforis/sepal,openforis/sepal | ---
+++
@@ -1,8 +1,10 @@
+import logging
from threading import local
from apiclient import discovery
_local = local()
+logging.getLogger('googleapiclient').setLevel(logging.WARNING)
def get_service(credentials): |
582edd6bd36e8b40a37a8aaaa013704b5cd73ad6 | dotbot/config.py | dotbot/config.py | import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(co... | import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(co... | Fix compatibility with Python 3 | Fix compatibility with Python 3
This patch removes a stray print statement that was causing problems
with Python 3.
| Python | mit | bchretien/dotbot,imattman/dotbot,imattman/dotbot,anishathalye/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot,imattman/dotbot | ---
+++
@@ -11,7 +11,6 @@
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
- print ext
if ext == '.json':
data = json.load(fin)
else: |
281629165a1b5cf00fb154ad262f3a592df2bba7 | driller/config.py | driller/config.py | ### Redis Options
REDIS_HOST="localhost"
REDIS_PORT=6379
REDIS_DB=1
### Celery Options
BROKER_URL="amqp://guest@localhost//"
CELERY_ROUTES = {'fuzzer.tasks.fuzz': {'queue': 'fuzzer'}, 'driller.tasks.drill': {'queue': 'driller'}}
### Environment Options
# directory contain driller-qemu versions, relative to the dire... | ### Redis Options
REDIS_HOST="localhost"
REDIS_PORT=6379
REDIS_DB=1
### Celery Options
BROKER_URL="amqp://guest@localhost//"
CELERY_ROUTES = {'fuzzer.tasks.fuzz': {'queue': 'fuzzer'}, 'driller.tasks.drill': {'queue': 'driller'}}
### Environment Options
# directory contain driller-qemu versions, relative to the dire... | Increase default DRILL_TIMEOUT to 60 minutes | Increase default DRILL_TIMEOUT to 60 minutes
| Python | bsd-2-clause | shellphish/driller | ---
+++
@@ -18,7 +18,7 @@
### Driller options
# how long to drill before giving up in seconds
-DRILL_TIMEOUT=60 * 15 # 15 minutes
+DRILL_TIMEOUT=60 * 60 # 60 minutes
MEM_LIMIT=8 * 1024 * 1024 * 1024
|
01c9de35395495e35113e5f9bbee8ebc88e1c0f1 | evaluation/packages/project.py | evaluation/packages/project.py | """@package Project
This module defines an interface to read and use InputGen projects
See C++ InputGen project for more details on Projects
"""
import xml.etree.ElementTree as ET
import displacementKernels as kernels
class PyProject:
"""Main class of the module
"""
def __init__(self, path):
"""... | """@package Project
This module defines an interface to read and use InputGen projects
See C++ InputGen project for more details on Projects
"""
import xml.etree.ElementTree as ET
import displacementKernels as kernels
class PyProject(object):
"""Main class of the module
"""
def __init__(self, path):
... | Change loading function to take a path instead of a python file | Change loading function to take a path instead of a python file
| Python | apache-2.0 | NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt | ---
+++
@@ -7,15 +7,15 @@
import xml.etree.ElementTree as ET
import displacementKernels as kernels
-class PyProject:
+class PyProject(object):
"""Main class of the module
"""
def __init__(self, path):
"""Default constructor, taking as input a prj file."""
- print 'Loading project ... |
a040d06de7624371122960788aff241994ae08f8 | metadata/SnowDegreeDay/hooks/pre-stage.py | metadata/SnowDegreeDay/hooks/pre-stage.py | import os
import shutil
from wmt.config import site
from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = ['rti_file',
'pixel_file']
def execute(env):
"""Perform pre-stage tasks for run... | import os
import shutil
from wmt.config import site
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
... | Update hook for SnowDegreeDay component | Update hook for SnowDegreeDay component
| Python | mit | csdms/wmt-metadata | ---
+++
@@ -2,13 +2,11 @@
import shutil
from wmt.config import site
-from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
-from topoflow_utils.hook import assign_parameters
+from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
-file_list = ... |
0c83621f80ad8a1c014cc2ee79ea024f6d073749 | src/smif/__init__.py | src/smif/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""smif
"""
from __future__ import division, print_function, absolute_import
import pkg_resources
import warnings
__author__ = "Will Usher, Tom Russell"
__copyright__ = "Will Usher, Tom Russell"
__license__ = "mit"
try:
__version__ = pkg_resources.get_distribution(_... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""smif
"""
from __future__ import division, print_function, absolute_import
import pkg_resources
import warnings
__author__ = "Will Usher, Tom Russell"
__copyright__ = "Will Usher, Tom Russell"
__license__ = "mit"
try:
__version__ = pkg_resources.get_distribution(_... | Comment to explain numpy warnings filter | Comment to explain numpy warnings filter
| Python | mit | willu47/smif,nismod/smif,tomalrussell/smif,tomalrussell/smif,tomalrussell/smif,willu47/smif,willu47/smif,nismod/smif,nismod/smif,willu47/smif,nismod/smif,tomalrussell/smif | ---
+++
@@ -17,5 +17,7 @@
except:
__version__ = 'unknown'
+# Filter out warnings arising from some installed combinations of scipy/numpy
+# - problem and fix discussed in [numpy/numpy#432](https://github.com/numpy/numpy/pull/432)
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings... |
cc2b00f60029f50106af586d9a43895ef84133fa | __init__.py | __init__.py | #!/usr/bin/env python
# coding=utf-8
# flake8: noqa
# pylint: disable=missing-docstring
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from __future__ import absolu... | #!/usr/bin/env python
# coding=utf-8
# flake8: noqa
# pylint: disable=missing-docstring
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from __future__ import absolu... | Remove useless "unused-wildcard-import" pylint suppression. | Remove useless "unused-wildcard-import" pylint suppression.
| Python | mpl-2.0 | MozillaSecurity/lithium,MozillaSecurity/lithium,nth10sd/lithium,nth10sd/lithium | ---
+++
@@ -9,4 +9,4 @@
from __future__ import absolute_import
-from .lithium.lithium import * # pylint: disable=wildcard-import,unused-wildcard-import
+from .lithium.lithium import * # pylint: disable=wildcard-import |
3aac735425c532bdb565f31feab203a36205df4f | __main__.py | __main__.py | #!/usr/bin/env python3
import sys
import lexer as l
import parser as p
import evaluator as e
import context as c
import object as o
def main():
if len(sys.argv) == 1:
ctx = c.Context()
while True:
try:
string = input("⧫ ") + ";"
... | #!/usr/bin/env python3
import sys
import readline
import lexer as l
import parser as p
import evaluator as e
import context as c
import object as o
def main():
if len(sys.argv) == 1:
ctx = c.Context()
while True:
try:
string = input("⧫... | Use the readline module to allow arrow key movement in the REPL | Use the readline module to allow arrow key movement in the REPL
| Python | mit | Zac-Garby/pluto-lang | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import sys
+import readline
import lexer as l
import parser as p
@@ -9,12 +10,16 @@
import object as o
def main():
- if len(sys.argv) == 1:
+ if len(sys.argv) == 1:
ctx = c.Context()
while True:
... |
7223bf0bf3ecf3459e5e7c9f01af61a8236eaffd | espei/__init__.py | espei/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import os
import yaml
from cerberus import Validator
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
# extension for iseven
class ESPEIValidator(Validator):
def _validate_iseven(self, iseven, field, value):
... | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import os
import yaml
from cerberus import Validator
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
# extension for iseven
class ESPEIValidator(Validator):
def _validate_iseven(self, iseven, field, value):
... | Hide permissible NumPy warnings from users | ENH: Hide permissible NumPy warnings from users
| Python | mit | PhasesResearchLab/ESPEI | ---
+++
@@ -25,3 +25,9 @@
from espei.paramselect import generate_parameters
from espei.mcmc import mcmc_fit
from espei.espei_script import run_espei
+
+# swallow warnings during MCMC runs
+import warnings
+warnings.filterwarnings('ignore', message='Mean of empty slice')
+warnings.filterwarnings('ignore', message='... |
30c9359e33f6ec85ffad227dd8b68f3352f92c36 | Assignment_5_partial_differentials/P440_Assign5_Exp1.py | Assignment_5_partial_differentials/P440_Assign5_Exp1.py | '''
Kaya Baber
Physics 440 - Computational Physics
Assignment 5 - PDEs
Exploration 1 - Parabolic PDEs: Thermal Diffusion
'''
import numpy as np
from numpy import linalg as LA
import matplotlib.pyplot as plt
import math
| '''
Kaya Baber
Physics 440 - Computational Physics
Assignment 5 - PDEs
Exploration 1 - Parabolic PDEs: Thermal Diffusion
'''
import numpy as np
from numpy import linalg as LA
import matplotlib.pyplot as plt
import math
#make banded matrix
#initialize column vector
#matrix multiply
#modifiy boundaries
#repeat
... | Set up the procedure to code out | Set up the procedure to code out
| Python | mit | KayaBaber/Computational-Physics | ---
+++
@@ -9,3 +9,26 @@
from numpy import linalg as LA
import matplotlib.pyplot as plt
import math
+
+
+
+
+#make banded matrix
+#initialize column vector
+#matrix multiply
+#modifiy boundaries
+#repeat
+
+
+
+def make_banded(N,M):
+ bandTopBot = [2 + (4*M)/(N**2) ]*(N-1)
+ bandMid = [-2.0/ (stepSize**2)]... |
e39430a8d1870c744fcfb479a15c1a7eacca8a32 | psi/data/sinks/api.py | psi/data/sinks/api.py | import enaml
with enaml.imports():
from .bcolz_store import BColzStore
from .display_value import DisplayValue
from .event_log import EventLog
from .epoch_counter import EpochCounter, GroupedEpochCounter
from .text_store import TextStore
| import enaml
with enaml.imports():
from .bcolz_store import BColzStore
from .display_value import DisplayValue
from .event_log import EventLog
from .epoch_counter import EpochCounter, GroupedEpochCounter
from .text_store import TextStore
from .sdt_analysis import SDTAnalysis
| Fix missing import to API | Fix missing import to API
| Python | mit | bburan/psiexperiment | ---
+++
@@ -6,3 +6,4 @@
from .event_log import EventLog
from .epoch_counter import EpochCounter, GroupedEpochCounter
from .text_store import TextStore
+ from .sdt_analysis import SDTAnalysis |
0cfd63816706531646bf496798bf093f8ee081ff | psqlextra/__init__.py | psqlextra/__init__.py | default_app_config = "psqlextra.apps.PostgresExtraAppConfig"
| import django
if django.VERSION < (3, 2): # pragma: no cover
default_app_config = "psqlextra.apps.PostgresExtraAppConfig"
| Remove default_app_config for Django 3.2 and newer | Remove default_app_config for Django 3.2 and newer
RemovedInDjango41Warning: 'psqlextra' defines default_app_config = 'psqlextra.apps.PostgresExtraAppConfig'. Django now detects this configuration automatically. You can remove default_app_config.
| Python | mit | SectorLabs/django-postgres-extra | ---
+++
@@ -1 +1,4 @@
-default_app_config = "psqlextra.apps.PostgresExtraAppConfig"
+import django
+
+if django.VERSION < (3, 2): # pragma: no cover
+ default_app_config = "psqlextra.apps.PostgresExtraAppConfig" |
c2b5b1458a521b39fbefb9f13428587991d5e3e9 | packages/pcl-reference-assemblies.py | packages/pcl-reference-assemblies.py | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies-2014-04-14',
version='2014-04-14',
sources=['http://storage.bos.xamarin.... | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies',
version='2014-04-14',
sources=['http://storage.bos.xamarin.com/bot-pro... | Fix package name for PCL ref assemblies | Fix package name for PCL ref assemblies
| Python | mit | BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild | ---
+++
@@ -6,7 +6,7 @@
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
- name='PortableReferenceAssemblies-2014-04-14',
+ name='PortableReferenceAssemblies',
version='2014-04-14',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.