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 |
|---|---|---|---|---|---|---|---|---|---|---|
83c68749910933cdb3a8be1a4fc2c50709f671a1 | admin/common_auth/forms.py | admin/common_auth/forms.py | from __future__ import absolute_import
from django import forms
from django.contrib.auth.models import Group
from osf.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.Pas... | from __future__ import absolute_import
from django import forms
from django.contrib.auth.models import Group
from osf.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.Pas... | Add checkboxselectmultiple widget for admin form | Add checkboxselectmultiple widget for admin form
| Python | apache-2.0 | felliott/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,erinspace/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,icereval/osf.io,chennan47/osf.io,mfraezz/osf.io,adlius/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,leb... | ---
+++
@@ -23,7 +23,8 @@
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.all(),
- required=False
+ required=False,
+ widget=forms.CheckboxSelectMultiple
)
|
85c1a9e6dd9e4523d60638027da23fbfce7deff6 | stack/cluster.py | stack/cluster.py | from troposphere import (
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micro",
A... | from troposphere import (
iam,
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micr... | Add an instance profile for container instances | Add an instance profile for container instances
| Python | mit | caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics | ---
+++
@@ -1,4 +1,5 @@
from troposphere import (
+ iam,
Parameter,
Ref,
)
@@ -31,3 +32,27 @@
"Cluster",
template=template,
)
+
+
+# ECS container role
+container_instance_role = iam.Role(
+ "ContainerInstanceRole",
+ template=template,
+ AssumeRolePolicyDocument=dict(Statement=[dic... |
b6742ef3f8d1888e46938b2c678bfb093b7a31f2 | pymortgage/d3_schedule.py | pymortgage/d3_schedule.py | import json
class D3_Schedule:
def __init__(self, schedule):
self.schedule = schedule
def get_d3_schedule(self, by_year=None):
d3_data = []
if by_year:
d3_data.insert(0, self.add_year_key("balance"))
d3_data.insert(1, self.add_year_key("princi... | import json
class D3_Schedule:
def __init__(self, schedule):
self.schedule = schedule
def get_d3_schedule(self, by_year=None):
d3_data = []
keys = ['balance', 'principal', 'interest', 'amount']
if by_year:
for i in range(len(keys)):
... | Put some recurring things into a loop to simply code. | Put some recurring things into a loop to simply code.
| Python | apache-2.0 | csutherl/pymortgage,csutherl/pymortgage,csutherl/pymortgage | ---
+++
@@ -9,24 +9,16 @@
def get_d3_schedule(self, by_year=None):
d3_data = []
+ keys = ['balance', 'principal', 'interest', 'amount']
+
if by_year:
- d3_data.insert(0, self.add_year_key("balance"))
- d3_data.insert(1, self.add_year_key("princ... |
cda63e96b042de04b3aa12348a411229e9b9d973 | tools/glidein_cat.py | tools/glidein_cat.py | #!/bin/env python
#
# glidein_cat
#
# Execute a cat command on the job directory
#
# Usage:
# glidein_ls.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>
#
import os
import string
import stat
import sys
sys.path.append("lib")
sys.path.append("../lib")
import glideinMonitor
def c... | #!/bin/env python
#
# glidein_cat.py
#
# Description:
# Execute a cat command on a condor job working directory
#
# Usage:
# glidein_cat.py <cluster>.<process> [<file>] [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>]
#
# Author:
# Igor Sfiligoi (May 2007)
#
# License:
# Fermitools
#
import sys,os... | Change rel paths into abspaths and use helper module | Change rel paths into abspaths and use helper module
| Python | bsd-3-clause | bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS | ---
+++
@@ -1,38 +1,24 @@
#!/bin/env python
#
-# glidein_cat
+# glidein_cat.py
#
-# Execute a cat command on the job directory
+# Description:
+# Execute a cat command on a condor job working directory
#
# Usage:
-# glidein_ls.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr sec... |
c8f3b93b763189a3f420b2d91dd9fec3ba96b300 | catalog/serializers.py | catalog/serializers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from rest_framework import serializers
from catalog.models import Course, Category
from documents.serializers import DocumentSerializer
from telepathy.serializers import SmallThreadSerializer
class CourseSerializer(serializers.HyperlinkedM... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from rest_framework import serializers
from catalog.models import Course, Category
from documents.serializers import DocumentSerializer
from telepathy.serializers import SmallThreadSerializer
class CourseSerializer(serializers.HyperlinkedM... | Remove category slug from the API | Remove category slug from the API
| Python | agpl-3.0 | UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub,UrLab/DocHub | ---
+++
@@ -39,7 +39,7 @@
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
- fields = ('id', 'url', 'slug', 'name', 'parent', 'children', 'course_set')
+ fields = ('id', 'url', 'name', 'parent', 'children', 'course_set')
extra_kwarg... |
5c28e34a795f3dfd8eebdbeb2509525ce4195bba | subversion/bindings/swig/python/tests/core.py | subversion/bindings/swig/python/tests/core.py | import unittest, os
import svn.core
class SubversionCoreTestCase(unittest.TestCase):
"""Test cases for the basic SWIG Subversion core"""
def test_SubversionException(self):
self.assertEqual(svn.core.SubversionException().args, ())
self.assertEqual(svn.core.SubversionException('error message').args,
... | import unittest, os
import svn.core
class SubversionCoreTestCase(unittest.TestCase):
"""Test cases for the basic SWIG Subversion core"""
def test_SubversionException(self):
self.assertEqual(svn.core.SubversionException().args, ())
self.assertEqual(svn.core.SubversionException('error message').args,
... | Add a regression test for the bug fixed in r28485. | Add a regression test for the bug fixed in r28485.
* subversion/bindings/swig/python/tests/core.py
(SubversionCoreTestCase.test_SubversionException): Test explicit
exception fields.
| Python | apache-2.0 | jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion | ---
+++
@@ -11,6 +11,10 @@
('error message',))
self.assertEqual(svn.core.SubversionException('error message', 1).args,
('error message', 1))
+ self.assertEqual(svn.core.SubversionException('error message', 1).apr_err,
+ 1)
+ self.assertEqual(s... |
e53c1d6b592784cf0d94f31aa798e7a4563a9164 | app/soc/views/helper/decorators.py | app/soc/views/helper/decorators.py | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Remove not needed request argument in view decorator. | Remove not needed request argument in view decorator.
Patch by: Pawel Solyga
Review by: to-be-reviewed
--HG--
extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826
| Python | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -34,9 +34,9 @@
def view(func):
"""Decorator that insists that exceptions are handled by view."""
@wraps(func)
- def view_wrapper(request, *args, **kwds):
+ def view_wrapper(*args, **kwds):
try:
- return func(request, *args, **kwds)
+ return func(*args, **kwds)
except DeadlineEx... |
3272a507219b5ca8c3a498acd66db33432458767 | app/soc/views/helper/decorators.py | app/soc/views/helper/decorators.py | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Remove not needed request argument in view decorator. | Remove not needed request argument in view decorator.
Patch by: Pawel Solyga
Review by: to-be-reviewed
--HG--
extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%40826
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -34,9 +34,9 @@
def view(func):
"""Decorator that insists that exceptions are handled by view."""
@wraps(func)
- def view_wrapper(request, *args, **kwds):
+ def view_wrapper(*args, **kwds):
try:
- return func(request, *args, **kwds)
+ return func(*args, **kwds)
except DeadlineEx... |
136f3725f4f90bef566ad43b740b341f69236bc5 | tools/snippets/test/fixtures/python/runner.py | tools/snippets/test/fixtures/python/runner.py | #!/usr/bin/env python
"""Generate fixtures."""
import os
import json
import math as m
import numpy as np
from scipy import special
# Get the file path:
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
DIR = os.path.dirname(file)
def gen(x, name):
"""Generate fixture data a... | #!/usr/bin/env python
"""Generate fixtures."""
import os
import json
import math as m
import numpy as np
from scipy import special
# Get the file path:
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
DIR = os.path.dirname(FILE)
def gen(x, name):
"""Generate fixture data a... | Fix variable name in Python snippet | Fix variable name in Python snippet
| Python | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -12,7 +12,7 @@
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
-DIR = os.path.dirname(file)
+DIR = os.path.dirname(FILE)
def gen(x, name): |
2489ac6ce5a0229bbcee6e888f192eeca284106c | thinglang/parser/tokens/arithmetic.py | thinglang/parser/tokens/arithmetic.py | from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: ... | from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: ... | Use argument list instead of lhs/rhs pari in ArithmeticOperation | Use argument list instead of lhs/rhs pari in ArithmeticOperation
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -12,10 +12,11 @@
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
- self.lhs, self.operator, self.rhs = slice
+ self.arguments = [slice[0], slice[2]]
+ self.operator = slice[1]
def evaluate(self, stack):
- return self.OPERATIONS[... |
6a007316bd3c7576e83076bee5d3236a1891a512 | messente/api/sms/api/__init__.py | messente/api/sms/api/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2016 Messente Communications OÜ
#
# 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 ... | # -*- coding: utf-8 -*-
# Copyright 2016 Messente Communications OÜ
#
# 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 ... | Declare public interface for api.sms.api module | Declare public interface for api.sms.api module
| Python | apache-2.0 | messente/messente-python | ---
+++
@@ -26,3 +26,14 @@
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
+
+__all__ = [
+ "error",
+ "Response",
+ "sms",
+ "credit",
+ "delivery",
+ "pricing",
+ "number_verification",
+ "v... |
167108f64a7c9e8c910b9b0991ab8489f8e90866 | morse_modem.py | morse_modem.py | import cProfile
from cfg import *
from detect_tone import *
from gen_test import *
from element_resolve import *
if __name__ == "__main__":
#gen_test_data()
data = gen_test_data()
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
print detect_tone(data)
print element_resolve(*detect_tone(data))
... | import cProfile
from cfg import *
from detect_tone import *
from gen_test import *
from element_resolve import *
if __name__ == "__main__":
#gen_test_data()
data = gen_test_data()
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
| Remove extraneous print, comment out naked detect_tone call | Remove extraneous print, comment out naked detect_tone call
| Python | mit | nickodell/morse-code | ---
+++
@@ -11,7 +11,7 @@
data = gen_test_data()
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
- print detect_tone(data)
- print element_resolve(*detect_tone(data))
+ #print detect_tone(data)
+ element_resolve(*detect_tone(data))
|
8ea4bb1acdc6df80620955c85c85fe71c74174d4 | highton/call_mixins/list_note_call_mixin.py | highton/call_mixins/list_note_call_mixin.py | from highton.call_mixins import Call
from highton import fields
class ListNoteCallMixin(Call):
"""
A mixin to get all notes of inherited class
These could be: people || companies || kases || deals
"""
NOTES_OFFSET = 25
def list_notes(self, page=0, since=None):
"""
Get the no... | from highton.call_mixins import Call
from highton import fields
class ListNoteCallMixin(Call):
"""
A mixin to get all notes of inherited class
These could be: people || companies || kases || deals
"""
NOTES_OFFSET = 25
def list_notes(self, page=0, since=None):
"""
Get the no... | Fix wrong pagination param in ListNoteCallMixin | Fix wrong pagination param in ListNoteCallMixin
see #17
| Python | apache-2.0 | seibert-media/Highton,seibert-media/Highton | ---
+++
@@ -23,7 +23,7 @@
:rtype: list
"""
from highton.models.note import Note
- params = {'page': int(page) * self.NOTES_OFFSET}
+ params = {'n': int(page) * self.NOTES_OFFSET}
if since:
params['since'] = since.strftime(self.COLLECTION_DATETIME)
|
92aa83091c6f32758fe99d703fbc77d7a640a222 | src/sentry/api/permissions.py | src/sentry/api/permissions.py | from sentry.constants import MEMBER_USER
from sentry.models import Team, Project, User
class PermissionError(Exception):
pass
def has_perm(object, user, access=MEMBER_USER):
if user.is_superuser:
return True
# TODO: abstract this into a permission registry
if type(object) == User:
r... | from sentry.constants import MEMBER_USER
from sentry.models import Team, Project, User
class PermissionError(Exception):
pass
def has_perm(object, user, access=MEMBER_USER):
if user.is_superuser:
return True
# TODO: abstract this into a permission registry
if type(object) == User:
r... | Use == for permission check | Use == for permission check
| Python | bsd-3-clause | BayanGroup/sentry,jean/sentry,llonchj/sentry,alexm92/sentry,zenefits/sentry,JackDanger/sentry,kevinastone/sentry,fuziontech/sentry,gencer/sentry,JackDanger/sentry,gg7/sentry,camilonova/sentry,gg7/sentry,llonchj/sentry,BayanGroup/sentry,boneyao/sentry,nicholasserra/sentry,ifduyue/sentry,fuziontech/sentry,mvaled/sentry,s... | ---
+++
@@ -21,7 +21,10 @@
object = object.project
if type(object) == Project:
- return object in Project.objects.get_for_user(user, access=access)
+ return any(1
+ for o in Project.objects.get_for_user(user, access=access)
+ if object == o
+ )
raise T... |
8b4c8d30e70134a422576178534d41ebc9a92c88 | telethon/events/messagedeleted.py | telethon/events/messagedeleted.py | from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
@staticmethod
def build(update):
if isinstance(update, types.UpdateDeleteMessages):
... | from .common import EventBuilder, EventCommon, name_inner_event
from ..tl import types
@name_inner_event
class MessageDeleted(EventBuilder):
"""
Event fired when one or more messages are deleted.
"""
@staticmethod
def build(update):
if isinstance(update, types.UpdateDeleteMessages):
... | Fix events.MessageDeleted setting readonly properties | Fix events.MessageDeleted setting readonly properties
| Python | mit | LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,expectocode/Telethon | ---
+++
@@ -30,12 +30,5 @@
super().__init__(
chat_peer=peer, msg_id=(deleted_ids or [0])[0]
)
- if peer is None:
- # If it's not a channel ID, then it was private/small group.
- # We can't know which one was exactly unless we logged a... |
0d16478f62bfb7c761f70475933772c812f9bdde | app/tests/test_fixtures.py | app/tests/test_fixtures.py | """
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
def test_simple_app(app):
"""Verify basic application."""
assert app
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstance(config, dict)
def test_webdriver_current_url(webdriver... | """
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
from flask import Flask # type: ignore
def test_simple_app(app):
"""Verify basic application."""
assert isinstance(app, Flask)
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstan... | Improve app test and silence pylint | chore(fixture-tests): Improve app test and silence pylint
| Python | mpl-2.0 | defrank/roshi | ---
+++
@@ -5,11 +5,12 @@
:license: MPL-2.0
"""
+from flask import Flask # type: ignore
def test_simple_app(app):
"""Verify basic application."""
- assert app
+ assert isinstance(app, Flask)
def test_simple_config(config):
@@ -23,7 +24,7 @@
Chrome: 'data:,'
Firefox: 'about:blank'... |
dc2900ce180dbcd2b0a0f48e358c38fff67629e0 | rwt/tests/test_scripts.py | rwt/tests/test_scripts.py | from __future__ import unicode_literals
import textwrap
import sys
import subprocess
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
sc... | from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_fil... | Add test capturing error when attribute assignment occurs in the top of the script | Add test capturing error when attribute assignment occurs in the top of the script
| Python | mit | jaraco/rwt | ---
+++
@@ -3,6 +3,8 @@
import textwrap
import sys
import subprocess
+
+from rwt import scripts
def test_pkg_imported(tmpdir):
@@ -20,3 +22,12 @@
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
+
+
+class TestDepsReader:
+ def test_reads_files_wit... |
c9e19580c6488a5d46bc1a63e32c223802683179 | openprocurement/auth/provider.py | openprocurement/auth/provider.py | # coding: utf-8
from openprocurement.auth.provider_app import oauth_provider, db
import openprocurement.auth.models
import openprocurement.auth.views
def make_oath_provider_app(
global_conf,
sqlite='sqlite:///db.sqlite',
secret='abcdfg',
timezone='Europe/Kiev'):
oauth_provider.con... | # coding: utf-8
from openprocurement.auth.provider_app import oauth_provider, db
import openprocurement.auth.models
import openprocurement.auth.views
def make_oath_provider_app(
global_conf,
sqlite='sqlite:///db.sqlite',
secret='abcdfg',
timezone='Europe/Kiev',
hash_secret_key... | Create CLIENT for auction on start | Create CLIENT for auction on start
| Python | apache-2.0 | openprocurement/openprocurement.auth,Leits/openprocurement.auth,openprocurement/openprocurement.auth,Leits/openprocurement.auth | ---
+++
@@ -9,12 +9,30 @@
global_conf,
sqlite='sqlite:///db.sqlite',
secret='abcdfg',
- timezone='Europe/Kiev'):
+ timezone='Europe/Kiev',
+ hash_secret_key='',
+ auction_client_id='',
+ auction_client_secret=''):
oauth_provider.config.update({
... |
8c92c76d11b297e0b68b5f1b1711f462064fb33e | survey/urls.py | survey/urls.py | from django.conf.urls import patterns, url, include
from survey.views import *
urlpatterns = patterns('',
url(r'^about', 'survey.views.about', name='about'),
url(r'^management', 'survey.views.management', name='management'),
url(r'^contact', 'survey.views.contact', name='contact'),
# comment out line ... | from django.conf.urls import patterns, url, include
from survey.views import *
urlpatterns = patterns('',
url(r'^about', 'survey.views.about', name='about'),
url(r'^management', 'survey.views.management', name='management'),
url(r'^contact', 'survey.views.contact', name='contact'),
# comment out line ... | Remove survey2 route to close the survey | Remove survey2 route to close the survey
Close the survey for the Manchester researchers.
| Python | agpl-3.0 | mysociety/manchester-survey,mysociety/manchester-survey,mysociety/manchester-survey,mysociety/manchester-survey,mysociety/manchester-survey | ---
+++
@@ -7,7 +7,7 @@
url(r'^management', 'survey.views.management', name='management'),
url(r'^contact', 'survey.views.contact', name='contact'),
# comment out line below to close survey
- url(r'^survey2/(?P<id>[0-9A-Za-z]+)-(?P<token>.+)/$', 'survey.views.survey2', name='survey2'),
+ # url(r'... |
f7dd16abcab5d5e0134083267f21672de8e3d5e1 | hc/front/context_processors.py | hc/front/context_processors.py | from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_root": settings.SITE_ROOT,
"site_logo_url": settings.SITE_LOGO_URL,
}
| from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_logo_url": settings.SITE_LOGO_URL,
}
| Remove site_root from template context, it's never used | Remove site_root from template context, it's never used
| Python | bsd-3-clause | iphoting/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,iphoting/healthchecks | ---
+++
@@ -4,6 +4,5 @@
def branding(request):
return {
"site_name": settings.SITE_NAME,
- "site_root": settings.SITE_ROOT,
"site_logo_url": settings.SITE_LOGO_URL,
} |
dcdbd0e0a9959c760d7465c748f29acd1b2e353e | tests/integration/test_structs.py | tests/integration/test_structs.py | from .helper import IntegrationHelper
class TestGitHubIterator(IntegrationHelper):
def test_resets_etag(self):
cassette_name = self.cassette_name('resets_etag')
with self.recorder.use_cassette(cassette_name):
users_iter = self.gh.iter_all_users(number=10)
assert users_iter.... | from .helper import IntegrationHelper
class TestGitHubIterator(IntegrationHelper):
def test_resets_etag(self):
cassette_name = self.cassette_name('resets_etag')
with self.recorder.use_cassette(cassette_name):
users_iter = self.gh.all_users(number=10)
assert users_iter.etag ... | Fix usage of iter_all_repos in integration tests | Fix usage of iter_all_repos in integration tests
| Python | bsd-3-clause | wbrefvem/github3.py,icio/github3.py,jim-minter/github3.py,sigmavirus24/github3.py,h4ck3rm1k3/github3.py,agamdua/github3.py,degustaf/github3.py,krxsky/github3.py,balloob/github3.py,ueg1990/github3.py,itsmemattchung/github3.py,christophelec/github3.py | ---
+++
@@ -5,7 +5,7 @@
def test_resets_etag(self):
cassette_name = self.cassette_name('resets_etag')
with self.recorder.use_cassette(cassette_name):
- users_iter = self.gh.iter_all_users(number=10)
+ users_iter = self.gh.all_users(number=10)
assert users_iter... |
7f31d1ba671627f28bd57b49242b275f38fdff31 | server.py | server.py | from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
#AsyncIO buffer problem
req.trans... | from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
#AsyncIO buffer problem
req.trans... | Increase request buffer as workaround for stackoverflow in asyncio | Increase request buffer as workaround for stackoverflow in asyncio
| Python | mit | azzuwan/PyApiServerExample | ---
+++
@@ -15,8 +15,8 @@
Get alll articles
"""
#AsyncIO buffer problem
- req.transport.set_write_buffer_limits=4096
-
+ req.transport.set_write_buffer_limits(high=4096)
+
docs = article_service.all()
return req.Response(text=docs.to_json())
@@ -25,7 +25,7 @@
Retrieve articles by keywords
"""
#Asy... |
3a3adca2e5462a98c70a8624f880e35e497e5acc | server.py | server.py | import http.server
PORT = 8000
HOST = "127.0.0.1"
# This will display the site at `http://localhost:8000/`
server_address = (HOST, PORT)
# The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/
# Rather than attempt to display the cgi file itself, which a 'BaseHTTPRequestHandler' or
# 'SimpleHT... | import os
import http.server
PORT = int(os.environ.get("PORT", 8000))
HOST = "127.0.0.1"
# This will display the site at `http://localhost:8000/`
server_address = (HOST, PORT)
# The CGIHTTPRequestHandler class allows us to run the cgi script in /cgi-bin/
# Rather than attempt to display the cgi file itself, which a ... | Set port depending on environment | Set port depending on environment
| Python | mit | Charlotteis/guestbook | ---
+++
@@ -1,6 +1,7 @@
+import os
import http.server
-PORT = 8000
+PORT = int(os.environ.get("PORT", 8000))
HOST = "127.0.0.1"
# This will display the site at `http://localhost:8000/` |
7e33e3ed495adc871a49f7217705a7d5710e7ed8 | cfgov/v1/templatetags/share.py | cfgov/v1/templatetags/share.py | import os
from django import template
from wagtail.wagtailcore.models import Page
from django.conf import settings
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
ret... | import os
from django import template
from wagtail.wagtailcore.models import Page
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
return False
@register.assignment_... | Fix one more place where STAGING_HOSTNAME uses settings | Fix one more place where STAGING_HOSTNAME uses settings
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | ---
+++
@@ -2,7 +2,6 @@
from django import template
from wagtail.wagtailcore.models import Page
-from django.conf import settings
register = template.Library()
@@ -20,7 +19,7 @@
@register.assignment_tag(takes_context=True)
def staging_url(context, page):
url = page.url
- if settings.STAGING_HOSTNAM... |
fc30efcbea90835314be50e65608102fa538e55c | sri21_vmx_pvs_to_file.py | sri21_vmx_pvs_to_file.py | #!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = '... | #!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = '... | Clear unnecessary code, add comments on sorting | Clear unnecessary code, add comments on sorting
| Python | apache-2.0 | razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects | ---
+++
@@ -15,6 +15,6 @@
mode_pvs = get_pv_names(argv.mode)
+# File appears to be already sorted, so no need for next line
+# sorted(mode_pvs)
write_pvs_to_file(argv.filename, mode_pvs)
-
-print argv.filename |
23e1efbd24e317e6571d8436fc414dae9a3da767 | salt/output/__init__.py | salt/output/__init__.py | '''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Pri... | '''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
STATIC = (
'yaml_out',
'text_out',
'raw_out',
'json_out',
)
def display_output(data, out, opts=None):
'''
Pri... | Add function to outputter that returns the raw string to print | Add function to outputter that returns the raw string to print
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -45,3 +45,11 @@
if not out in outputters:
return outputters['pprint']
return outputters[out]
+
+
+def out_format(data, out, opts=None):
+ '''
+ Return the formatted outputter string for the passed data
+ '''
+ return get_printout(out, opts)(data).rstrip()
+ |
2d7974ac4895af5e7d2f5a627656bb3edbfa65a9 | config/config.py | config/config.py | def playerIcons(poi):
if poi['id'] == 'Player':
poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId']
return "Last known location for %s" % poi['EntityId']
def signFilter(poi):
if poi['id'] == 'Sign':
return "\n".join([poi['Text1'], poi['Text2'], poi['Text3'], poi['Text4']])... | def playerIcons(poi):
if poi['id'] == 'Player':
poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId']
return "Last known location for %s" % poi['EntityId']
# Only signs with "-- RENDER --" on the last line will be shown
# Otherwise, people can't have secret bases and the render is too b... | Add filter text to signs | Add filter text to signs
| Python | mit | mide/minecraft-overviewer,StefanBossbaly/minecraft-overviewer,StefanBossbaly/minecraft-overviewer,mide/minecraft-overviewer | ---
+++
@@ -3,9 +3,12 @@
poi['icon'] = "http://overviewer.org/avatar/%s" % poi['EntityId']
return "Last known location for %s" % poi['EntityId']
+# Only signs with "-- RENDER --" on the last line will be shown
+# Otherwise, people can't have secret bases and the render is too busy anyways.
def si... |
fb0eae3a9a760460f664adeef2ff71b2e8daac0f | twelve/env.py | twelve/env.py | import os
import extensions
class Environment(object):
def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs):
super(Environment, self).__init__(*args, **kwargs)
if names is None:
names = {}
self.adapter = adapter
self.environ = environ
... | import os
import extensions
class Environment(object):
def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs):
super(Environment, self).__init__(*args, **kwargs)
if names is None:
names = {}
self.adapter = adapter
self.environ = environ
... | Add a repr for twelve.Environment | Add a repr for twelve.Environment
| Python | bsd-3-clause | dstufft/twelve | ---
+++
@@ -21,6 +21,9 @@
def __getattr__(self, name):
return self.values.get(name)
+ def __repr__(self):
+ return "<twelve.Environment [{0}]>".format(",".join(self.values))
+
def _load_all(self):
# Load Services
self._load_services() |
25bbe2cfc1b3b8f926176d83fbaa5c53bb85651a | tinysrt.py | tinysrt.py | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(... | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_PATTERN = '''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+?)
'''
SUBTITLE_REGEX = re.compile(SUBTITLE_PATTERN, re.MULTILINE | re.DOTALL)
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def par... | Split out subtitle pattern from compilation phase | Split out subtitle pattern from compilation phase
| Python | mit | cdown/srt | ---
+++
@@ -4,11 +4,13 @@
import datetime
from collections import namedtuple
-SUBTITLE_REGEX = re.compile(r'''\
+SUBTITLE_PATTERN = '''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
-(.+)
-''')
+(.+?)
+
+'''
+SUBTITLE_REGEX = re.compile(SUBTITLE_PATTERN, re.MULTILINE | re.DOTALL)
Subtitle = namedtuple('Subt... |
f479db0d829977766607d9131ddc85b1349c6f4a | userApp/tests.py | userApp/tests.py | from django.test import TestCase
# Create your tests here.
class BasicTestCase(TestCase):
"""Test getting various urls for user app"""
def test_getting_login(self):
self.client.get('/user/login')
def test_getting_register(self):
self.client.get('/user/register')
def test_getting_(self... | from django.test import TestCase
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your tests here.
class TestUserFunction(TestCase):
"""Test getting various urls for user app"""
def setUp(self):
self.test_user = create_user()
def test_getting_login(self):
se... | Add more thorough testing to user app | Add more thorough testing to user app
| Python | mit | SPARLab/BikeMaps,SPARLab/BikeMaps,SPARLab/BikeMaps | ---
+++
@@ -1,13 +1,27 @@
from django.test import TestCase
+from django.contrib.auth import get_user_model
+User = get_user_model()
+
# Create your tests here.
-class BasicTestCase(TestCase):
+class TestUserFunction(TestCase):
"""Test getting various urls for user app"""
+ def setUp(self):
+ self.t... |
28f9f7e85bb8353435db322138d1bd624934110f | london_commute_alert.py | london_commute_alert.py | import datetime
import os
import requests
import sys
def update(lines):
url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status'
resp = requests.get(url).json()
result = []
for el in resp:
value = el['lineStatuses'][0]
state = value['statusSeverityDescription']
if el['id'] in lines... | import datetime
import os
import requests
import sys
def update(lines):
url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status'
resp = requests.get(url).json()
result = []
for el in resp:
value = el['lineStatuses'][0]
state = value['statusSeverityDescription']
if el['id'] in lines... | Halt emails for time being | Halt emails for time being
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -20,6 +20,8 @@
def email(delays):
+ # While tube is on shuttle service, don't email
+ return
os.chdir(sys.path[0])
with open('curl_raw_command.sh') as f:
raw_command = f.read() |
3efd847f8569a30b018925b39d1552a4aead6e8f | destroyer/destroyer.py | destroyer/destroyer.py | """destroyer.py - Main module file for the application. Includes the code for
the command line interface."""
import click
from .services.twitter import TwitterDestroyer
@click.group()
def cli():
pass
@click.command()
@click.option('--unfollow_nonfollowers', default=False, type=click.BOOL)
def twitter(unfollo... | """destroyer.py - Main module file for the application. Includes the code for
the command line interface."""
import click
from .services.twitter import TwitterDestroyer
from .services.facebook import FacebookDestroyer
@click.group()
def cli():
pass
@click.command()
@click.option('--unfollow_nonfollowers', de... | Update main module with facebook integration | Update main module with facebook integration
| Python | mit | jaredmichaelsmith/destroyer | ---
+++
@@ -5,6 +5,7 @@
import click
from .services.twitter import TwitterDestroyer
+from .services.facebook import FacebookDestroyer
@click.group()
@@ -19,6 +20,13 @@
twitter_destroyer.destroy()
+@click.command()
+def facebook():
+ facebook_destroyer = FacebookDestroyer()
+ facebook_destroyer... |
f9cb83b2279e00c8812895e1cc6b46438615f8ac | wafer/tests/test_menu.py | wafer/tests/test_menu.py | # -*- coding: utf-8 -*-
"""Tests for wafer menu utilities."""
from django.test import TestCase
from wafer.menu import Menu
class MenuTests(TestCase):
def test_mk_item_defaults(self):
self.assertEqual(Menu.mk_item(
u"My Label", u"http://example.com"
), {
"label": u"My La... | Add tests for mk_item and mk_menu. | Add tests for mk_item and mk_menu.
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | ---
+++
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+
+"""Tests for wafer menu utilities."""
+
+from django.test import TestCase
+
+from wafer.menu import Menu
+
+
+class MenuTests(TestCase):
+
+ def test_mk_item_defaults(self):
+ self.assertEqual(Menu.mk_item(
+ u"My Label", u"http://example.com"
... | |
02da53951e48fd6b164d883cdf5c63c7b7f08049 | rmake_plugins/multinode_client/nodetypes.py | rmake_plugins/multinode_client/nodetypes.py | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
class NodeType(object):
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Cli... | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
_nodeTypes = {}
class _NodeTypeRegistrar(type):
def __init__(self, name, bases, dict):
type.__init__(self, name, bases, dict)
_nodeTypes[self.nodeType] = self
class NodeType(object):
__metaclass__ = _NodeType... | Use metaclasses to register node types. | Use metaclasses to register node types.
| Python | apache-2.0 | fedora-conary/rmake-2,fedora-conary/rmake-2,fedora-conary/rmake-2,fedora-conary/rmake-2 | ---
+++
@@ -4,7 +4,16 @@
from rmake.lib.apiutils import thaw, freeze
+
+_nodeTypes = {}
+class _NodeTypeRegistrar(type):
+ def __init__(self, name, bases, dict):
+ type.__init__(self, name, bases, dict)
+ _nodeTypes[self.nodeType] = self
+
+
class NodeType(object):
+ __metaclass__ = _NodeTyp... |
c0c67c14cb9c91c8cd07bfe6d013639121d1c5f7 | crm/tests/test_contact_user.py | crm/tests/test_contact_user.py | from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from login.tests.model_maker import make_user
class TestContactUser(TestCase):
def test_link_user_to_contact(self):
... | from django.db import IntegrityError
from django.test import TestCase
from crm.tests.model_maker import (
make_contact,
make_user_contact,
)
from crm.tests.scenario import (
contact_contractor,
)
from login.tests.scenario import (
get_fred,
get_sara,
user_contractor,
)
class TestContactUser(T... | Update test to use standard scenario | Update test to use standard scenario
| Python | apache-2.0 | pkimber/crm,pkimber/crm,pkimber/crm | ---
+++
@@ -1,4 +1,3 @@
-from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
@@ -6,31 +5,32 @@
make_contact,
make_user_contact,
)
-from login.tests.model_maker import make_user
+from crm.tests.scenario import (
+ contact_contractor,
+)
+f... |
a20c88da5eb0b763072cc7bcba138983fe63ae31 | django_fsm_log/apps.py | django_fsm_log/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Djang... | from __future__ import unicode_literals
from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from django_fsm.signals import pre_transition, post_transition
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Djang... | Solve warning coming from django 4.0 | Solve warning coming from django 4.0
| Python | mit | ticosax/django-fsm-log,gizmag/django-fsm-log | ---
+++
@@ -9,6 +9,7 @@
class DjangoFSMLogAppConfig(AppConfig):
name = 'django_fsm_log'
verbose_name = "Django FSM Log"
+ default_auto_field = 'django.db.models.BigAutoField'
def ready(self):
backend = import_string(settings.DJANGO_FSM_LOG_STORAGE_METHOD) |
28126555aea9a78467dfcadbb2b14f9c640cdc6d | dwitter/templatetags/to_gravatar_url.py | dwitter/templatetags/to_gravatar_url.py | import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower()).hexdigest())
| import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
| Fix gravatar hashing error on py3 | Fix gravatar hashing error on py3
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | ---
+++
@@ -7,4 +7,4 @@
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
- hashlib.md5((email or '').strip().lower()).hexdigest())
+ hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest()) |
5a4fc9a89bfdb279ad0cda40f45b35ff3841c970 | voteswap/urls.py | voteswap/urls.py | """voteswap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | """voteswap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | Fix logout view so django stops complaining | Fix logout view so django stops complaining
| Python | mit | sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap | ---
+++
@@ -16,6 +16,7 @@
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
+from django.contrib.auth.views import logout
from voteswap.views import index
from voteswap.views import landing_page
@@ -27,7 +28,7 @@
url('', include('social.apps.django_app.... |
bf269c03f93cf26630e67b3e44384eaf1235f808 | tests/test_20_message.py | tests/test_20_message.py |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
import pytest
from eccodes_grib import eccodes
from eccodes_grib import message
TEST_DATA = os.path.join(os.path.dirname(__file__), 'sample-data', 'ERA5_levels.grib')
def test_Message():
codes_id = eccodes.grib... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
import pytest
from eccodes_grib import eccodes
from eccodes_grib import message
TEST_DATA = os.path.join(os.path.dirname(__file__), 'sample-data', 'ERA5_levels.grib')
def test_Message():
codes_id = eccodes.grib... | Check more possibilitie for File. | Check more possibilitie for File.
| Python | apache-2.0 | ecmwf/cfgrib | ---
+++
@@ -25,8 +25,17 @@
def test_File():
+ # check File init
+ with pytest.raises(RuntimeError):
+ next(message.File(TEST_DATA))
+
with message.File(TEST_DATA) as res:
assert sum(1 for _ in res) == 72
+ # check file_handle reset
with pytest.raises(RuntimeError):
n... |
3e86072667d486cb75e0cefca847bbdd2f032023 | charat2/views/guides.py | charat2/views/guides.py | import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
| import requests
def user_guide():
r = requests.get("https://karry.terminallycapricio.us/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
| Update the user guide URL. | Update the user guide URL.
| Python | agpl-3.0 | MSPARP/newparp,MSPARP/newparp,MSPARP/newparp | ---
+++
@@ -1,7 +1,7 @@
import requests
def user_guide():
- r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
+ r = requests.get("https://karry.terminallycapricio.us/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
4b183fb87952404e5a71ffd5c52ea1bba5bfc2b9 | csv2ofx/mappings/stripe.py | csv2ofx/mappings/stripe.py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via Stripe card processing
Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom).
The De... | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via Stripe card processing
Note that Stripe provides a Default set of columns or you can download
All columns. (as well as custom). The De... | Fix lint line length warnings (blocking manage checks) | Fix lint line length warnings (blocking manage checks)
| Python | mit | reubano/csv2ofx,reubano/csv2ofx | ---
+++
@@ -7,11 +7,13 @@
Provides a mapping for transactions obtained via Stripe card processing
-Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom).
-The Default set does not include card information, so provides no appropriate value for the
-PAYEE field for... |
041a3bbd512d1800067bc12f522238d681c35ac4 | sheared/web/__init__.py | sheared/web/__init__.py | # vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | # vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | Add proxy module to __all__. | Add proxy module to __all__.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@248 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared | ---
+++
@@ -19,4 +19,4 @@
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
- 'application']
+ 'application', 'proxy'] |
3a57dfd7138be531fa265bea282eb7c62a391ac2 | bin/debug/load_timeline_for_day_and_user.py | bin/debug/load_timeline_for_day_and_user.py | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | Fix the --verbose argument to properly take an int | Fix the --verbose argument to properly take an int
Without this, the `i % args.verbose` check would fail since `args.verbose` was
a string
| Python | bsd-3-clause | e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server | ---
+++
@@ -14,7 +14,7 @@
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
- parser.add_argument("-v", "--verbose",
+ parser.add_argument("-v", "--verbose", type=int,
help="after ho... |
2828f056d0daabe613a5fe00584ab1bf699989c3 | bliski_publikator/monitorings/forms.py | bliski_publikator/monitorings/forms.py | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import FormHorizontalMixin, SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from dal import autocomplete
from django import forms
from tinymce.widgets import TinyMCE
from django.utils.translation import ugettext_lazy as _
from ..institutions.m... | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import FormHorizontalMixin, SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from dal import autocomplete
from django import forms
from tinymce.widgets import TinyMCE
from django.utils.translation import ugettext_lazy as _
from ..institutions.m... | Add monitoring logo in form | Add monitoring logo in form
| Python | mit | watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator | ---
+++
@@ -36,7 +36,7 @@
class Meta:
model = Monitoring
- fields = ['name', 'description', 'active', 'max_point', ]
+ fields = ['name', 'logo', 'description', 'active', 'max_point', ]
widgets = {
'description': TinyMCE(attrs={'cols': 80, 'rows': 30}),
} |
994606d2641115f8af59657204d3d64f540bbfbd | data_structures/linked_list.py | data_structures/linked_list.py | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, values=None, head=None):
self.head = head
self.length = 0
def __repr__(... | class Node(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{val}'.format(val=self.val)
class LinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.length = 0
... | Update magic methods, and reorg args. | Update magic methods, and reorg args.
| Python | mit | sjschmidt44/python_data_structures | ---
+++
@@ -8,17 +8,37 @@
class LinkedList(object):
- def __init__(self, values=None, head=None):
- self.head = head
+ def __init__(self, iterable=()):
+ self._current = None
+ self.head = None
self.length = 0
+ for val in reversed(iterable):
+ self.insert(va... |
ad7bddb7fc4704893c0113bc48967ff3dd581e39 | demos/spritzer/settings.py | demos/spritzer/settings.py | import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
HANDLERS = (
'spritzer.spritzer_handler.SpritzerHandler',
'hurricane.handlers.comet.CometHandler',
)
APPLICATION_MANAGER = 'hurricane.managers.ipc'
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
TWITTER_USERNAME = 'py_hurricane'
TWITTER_... | import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
HANDLERS = (
'spritzer.spritzer_handler.SpritzerHandler',
'hurricane.handlers.comet.BroadcastCometHandler',
)
APPLICATION_MANAGER = 'hurricane.managers.ipc'
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
TWITTER_USERNAME = 'py_hurricane'... | Swap out CometHandler for BroadcastCometHandler in the Spritzer demo. | Swap out CometHandler for BroadcastCometHandler in the Spritzer demo.
| Python | bsd-3-clause | ericflo/hurricane,ericflo/hurricane | ---
+++
@@ -4,7 +4,7 @@
HANDLERS = (
'spritzer.spritzer_handler.SpritzerHandler',
- 'hurricane.handlers.comet.CometHandler',
+ 'hurricane.handlers.comet.BroadcastCometHandler',
)
APPLICATION_MANAGER = 'hurricane.managers.ipc' |
7af339d68d31e402df3a70b6596927439de0f2aa | doc/mkapidoc.py | doc/mkapidoc.py | #!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.j... | #!/usr/bin/env python
# Generates the API documentation.
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.j... | Hide Exscript.protocols.AbstractMethod from the API docs. | Hide Exscript.protocols.AbstractMethod from the API docs.
| Python | mit | maximumG/exscript,knipknap/exscript,maximumG/exscript,knipknap/exscript | ---
+++
@@ -18,6 +18,7 @@
'--exclude Exscript.FooLib',
'--exclude Exscript.AccountManager',
'--exclude Exscript.stdlib',
+ '--exclude Exscript.protocols.AbstractMethod',
... |
f9730bbcb9c36c973f3eff431c3f39ff18dda666 | django/comicsite/templatetags/comic_filters.py | django/comicsite/templatetags/comic_filters.py | from django import template
register = template.Library()
"""
Copied these from django/contrib/admin/templates/templatetags/admin_urls.
These are utility functions for generating urls to admin pages.
I want to extend the standard /admin url to always include the current project,
designated by /site/<projectname>/admi... | from django import template
register = template.Library()
"""
Copied these from django/contrib/admin/templates/templatetags/admin_urls.
These are utility functions for generating urls to admin pages.
I want to extend the standard /admin url to always include the current project,
designated by /site/<projectname>/admi... | Update for function name change in Django 1.8 | Update for function name change in Django 1.8
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | ---
+++
@@ -11,4 +11,4 @@
@register.filter
def project_admin_urlname(value, arg):
- return 'projectadmin:%s_%s_%s' % (value.app_label, value.modal_name, arg)
+ return 'projectadmin:%s_%s_%s' % (value.app_label, value.model_name, arg) |
23edca2a2a87ca0d96becd92a0bf930cc6c33b6f | alltheitems/world.py | alltheitems/world.py | import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World)... | import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World)... | Fix API method names called by World.block_at | Fix API method names called by World.block_at
| Python | mit | wurstmineberg/alltheitems.wurstmineberg.de,wurstmineberg/alltheitems.wurstmineberg.de | ---
+++
@@ -25,8 +25,8 @@
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
- Dimension.overworld: api.v2.chunk_info_overworld,
- Dimension.nether: api.v2.chunk_info_nether,
- Dimension.end: api.v2.chunk_info_end
+ Dimens... |
8a10dbe86f6ce02af1884fc9e68aa925003d9ad7 | pynder/session.py | pynder/session.py | from time import time
from datetime import timedelta
from . import api
from . import models
class Session(object):
def __init__(self, facebook_id, facebook_token, proxies=None):
self._api = api.TinderAPI(proxies)
# perform authentication
self._api.auth(facebook_id, facebook_token)
... | from time import time
from datetime import timedelta
from . import api
from . import models
class Session(object):
def __init__(self, facebook_id, facebook_token, proxies=None):
self._api = api.TinderAPI(proxies)
# perform authentication
self._api.auth(facebook_id, facebook_token)
... | Handle no nearby users gracefully. | Handle no nearby users gracefully.
| Python | mit | rforgione/pynder | ---
+++
@@ -14,7 +14,9 @@
self.profile = models.Profile(self._api.profile(), self)
def nearby_users(self):
- return [models.Hopeful(u, self) for u in self._api.recs()['results']]
+ response = self._api.recs()
+ users = response['results'] if 'results' in response else []
+ ... |
0383ee9511a4b002fbb3c00b3fc6812e8cc6bf1e | test/integration/fixture_server.py | test/integration/fixture_server.py | """
Tests against the URL Router
"""
from wsgiref.simple_server import make_server
from aragog.routing.decorator import Router
router = Router()
@router.route("/")
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type',... | """
Tests against the URL Router
"""
from wsgiref.simple_server import make_server
from aragog import Router
router = Router()
@router.route('/')
def simple_app(environ, start_response):
"""
Simplest possible application object
"""
status = '200 OK'
response_headers = [('Content-type', 'text/pl... | Update fixture server with environ route. | Update fixture server with environ route.
Minor changes to docstrings and change in quotation usage.
Router imported from aragog, not routing.decorator.
| Python | apache-2.0 | bramwelt/aragog | ---
+++
@@ -4,29 +4,49 @@
from wsgiref.simple_server import make_server
-from aragog.routing.decorator import Router
+from aragog import Router
router = Router()
-
-@router.route("/")
+@router.route('/')
def simple_app(environ, start_response):
- """Simplest possible application object"""
+ """
+ ... |
d7ebf5c6db9b73133915aabb3dbd9c5b283f9982 | ooni/tests/test_trueheaders.py | ooni/tests/test_trueheaders.py | from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3':... | from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['Va... | Fix unittest for true headers.. | Fix unittest for true headers..
| Python | bsd-2-clause | kdmurray91/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-prob... | ---
+++
@@ -1,6 +1,6 @@
from twisted.trial import unittest
-from ooni.utils.txagentwithsocks import TrueHeaders
+from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'], |
2536d58d1119bd2304f5c16f1109e42314595f65 | scripts/cat.py | scripts/cat.py | #!/usr/bin/env python
# Copyright 2021 David Robillard <d@drobilla.net>
# SPDX-License-Identifier: ISC
import sys
for filename in sys.argv[1:]:
with open(filename, 'r') as f:
sys.stdout.write(f.read())
| #!/usr/bin/env python3
# Copyright 2021 David Robillard <d@drobilla.net>
# SPDX-License-Identifier: ISC
import sys
for filename in sys.argv[1:]:
with open(filename, 'r') as f:
sys.stdout.write(f.read())
| Fix build on systems without a "python" executable | Fix build on systems without a "python" executable
This script is technically 2/3 compatible, but 3 is required to build anyway,
so whatever.
| Python | isc | drobilla/pugl,drobilla/pugl,drobilla/pugl | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2021 David Robillard <d@drobilla.net>
# SPDX-License-Identifier: ISC |
189353e4eb110facbabf9882e0af1ef16ced600f | openstack/tests/functional/network/v2/test_quota.py | openstack/tests/functional/network/v2/test_quota.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Fix network quota test so it works on gate | Fix network quota test so it works on gate
The gate does not create quotas by default, but devstack does.
This test is not important enough to make work for the gate which
would probably require some reconfiguration, but it is nice to
have it for devstack.
Change-Id: I6618b5ee8c1dde7773b83e8ba97092f30d595e8a
Partial-... | Python | apache-2.0 | stackforge/python-openstacksdk,openstack/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-openstacksdk,dtroyer/python-openstacksdk,briancurtin/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk | ---
+++
@@ -10,34 +10,19 @@
# License for the specific language governing permissions and limitations
# under the License.
-import uuid
-
from openstack.tests.functional import base
class TestQuota(base.BaseFunctionalTest):
- PROJECT_NAME = 'project-' + uuid.uuid4().hex
- PROJECT = None
-
- @clas... |
5c1fa71bf4d6dbe6fef0836a03f6b5d85e924f41 | src/urllib3/_version.py | src/urllib3/_version.py | # This file is protected via CODEOWNERS
__version__ = "1.25.9"
| # This file is protected via CODEOWNERS
__version__ = "1.26.0.dev0"
| Mark master branch as 1.26.0.dev0 for RTD | Mark master branch as 1.26.0.dev0 for RTD | Python | mit | sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3,urllib3/urllib3 | ---
+++
@@ -1,2 +1,2 @@
# This file is protected via CODEOWNERS
-__version__ = "1.25.9"
+__version__ = "1.26.0.dev0" |
e5591918d9ec792c64a25670f7bf7fde87ac078d | espei/citing.py | espei/citing.py | """
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@ar... | """
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@ar... | Fix unicode in citation (again) | DOC: Fix unicode in citation (again)
| Python | mit | PhasesResearchLab/ESPEI | ---
+++
@@ -13,7 +13,7 @@
journal = {MRS Communications},
month = {jun},
pages = {1--10},
-title = {{ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu–Mg}},
+title = {{ESPEI for efficient thermodynamic database development, modification, and unc... |
fde67686d2bd685e31cfc0e156314476b057db78 | xudd/tests/test_demos.py | xudd/tests/test_demos.py | from xudd.demos import special_hive
from xudd.demos import lotsamessages
def test_special_hive():
"""
This demo tests that demos are actually actors and are in fact subclassable.
"""
special_hive.main()
def test_lotsamessages():
"""
Test the lotsamessages demo (but not with too many messages ... | from xudd.demos import special_hive
from xudd.demos import lotsamessages
def test_special_hive():
"""
This demo tests that demos are actually actors and are in fact subclassable.
"""
special_hive.main()
def test_lotsamessages():
"""
Test the lotsamessages demo (but not with too many messages ... | Add inter-hive communication lotsamessages test | Add inter-hive communication lotsamessages test
| Python | apache-2.0 | xudd/xudd | ---
+++
@@ -14,4 +14,13 @@
"""
assert lotsamessages.main(num_experiments=20, num_steps=20) is True
+
+def test_lotsamessages_ihc():
+ """
+ Test the lotsamessages demo with inter-hive communication
+ """
+ assert lotsamessages.main(
+ num_experiments=20, num_steps=20, subprocesses=4) is... |
8b9ef7e731a8801535b9348dc0a6869de6c9ecfc | tests/__init__.py | tests/__init__.py | """
tests
~~~~~
Unit tests for the project.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
| """
tests
~~~~~
Tests for the library and tools.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details
"""
| Make the description of the tests package more precise. | Make the description of the tests package more precise.
| Python | mit | s3rvac/retdec-python | ---
+++
@@ -2,7 +2,7 @@
tests
~~~~~
- Unit tests for the project.
+ Tests for the library and tools.
:copyright: © 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
:license: MIT, see the ``LICENSE`` file for more details |
1fa2af46d9f1ee05d4e4fd16869803c3dfff23e0 | tests/protocol/primitives_tests.py | tests/protocol/primitives_tests.py | import unittest
from kiel.protocol import primitives
class PrimitivesTests(unittest.TestCase):
def test_string_repr(self):
s = primitives.String(u"foobar")
self.assertEqual(repr(s), '"u\'foobar\'"')
def test_array_repr(self):
a = primitives.Array.of(primitives.Int32)([1, 3, 6, 9])
... | import unittest
from kiel.protocol import primitives
class PrimitivesTests(unittest.TestCase):
def test_string_repr(self):
s = primitives.String(u"foobar")
self.assertEqual(repr(s), '%r' % repr(u"foobar"))
def test_array_repr(self):
a = primitives.Array.of(primitives.Int32)([1, 3, ... | Fix repr test for py34. | Fix repr test for py34.
| Python | apache-2.0 | wglass/kiel | ---
+++
@@ -8,7 +8,7 @@
def test_string_repr(self):
s = primitives.String(u"foobar")
- self.assertEqual(repr(s), '"u\'foobar\'"')
+ self.assertEqual(repr(s), '%r' % repr(u"foobar"))
def test_array_repr(self):
a = primitives.Array.of(primitives.Int32)([1, 3, 6, 9]) |
6191a5afd390cbd7e892e73af959d8d4cd68f52b | moksha/widgets/iframe.py | moksha/widgets/iframe.py | # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ... | # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ... | Make our IFrameWidget more configurable | Make our IFrameWidget more configurable
| Python | apache-2.0 | lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,ralphbean/moksha,lmacken/moksha,ralphbean/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha | ---
+++
@@ -24,10 +24,15 @@
from tw.api import Widget
class IFrameWidget(Widget):
- params = ['id', 'url']
+ params = ['id', 'url', 'title', 'height', 'width']
template = """
- <iframe id="${id}" src="${url}" width="100%" height="100%">
+ <h1>${title}</h1>
+ <iframe id="${id}" src="${url... |
d8623cb31b463ef98fbca0288e34c6ae24df4c82 | statsmodels/sandbox/stats/tests/test_runs.py | statsmodels/sandbox/stats/tests/test_runs.py | """
Tests corresponding to sandbox.stats.runs
"""
from numpy.testing import assert_almost_equal
from statsmodels.sandbox.stats.runs import runstest_1samp
def test_mean_cutoff():
x = [1] * 5 + [2] * 6 + [3] * 8
cutoff = "mean"
expected = (-4.007095978613213, 6.146988816717466e-05)
results = runstest_1s... | """
Tests corresponding to sandbox.stats.runs
"""
from numpy.testing import assert_almost_equal
from statsmodels.sandbox.stats.runs import runstest_1samp
def test_mean_cutoff():
x = [1] * 5 + [2] * 6 + [3] * 8
cutoff = "mean"
expected = (-4.007095978613213, 6.146988816717466e-05)
results = runstest_1s... | Fix missing line at end of file | STYLE: Fix missing line at end of file
Fix missing line
Remove whitespace | Python | bsd-3-clause | statsmodels/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,statsmod... | ---
+++
@@ -27,4 +27,3 @@
expected = (-3.944254410803499, 8.004864125547193e-05)
results = runstest_1samp(x, cutoff=cutoff, correction=False)
assert_almost_equal(expected, results)
- |
2f041e6ed7d07ef8932350b68581e8dfeaef903f | dashboard/dashboard/pinpoint/handlers/job.py | dashboard/dashboard/pinpoint/handlers/job.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import webapp2
from dashboard.pinpoint.models import job as job_module
class JobHandler(webapp2.RequestHandler):
def post(self):
job_id... | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import webapp2
from dashboard.pinpoint.models import job as job_module
class JobHandler(webapp2.RequestHandler):
def post(self):
job_id... | Move Job handler out of exception block. | [pinpoint] Move Job handler out of exception block.
The exception block is solely used for Job loading exceptions.
Review-Url: https://codereview.chromium.org/2768293003
| Python | bsd-3-clause | catapult-project/catapult,sahiljain/catapult,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapu... | ---
+++
@@ -16,13 +16,13 @@
# Validate parameters.
try:
job = job_module.JobFromId(job_id)
- self.response.write(json.dumps({'data': job.AsDict()}))
- except: # pylint: disable=bare-except
- # There's no narrower exception we can catch. Catching
- # google.net.proto.ProtocolBuffer.... |
132d160a365580d77c1f5763b1fd1ac044133bb0 | NYTimesArticleAPI/__init__.py | NYTimesArticleAPI/__init__.py | from nytapi import *
__version__ = "1.0.0"
__author__ = "Matt Morrison @MattDMo mattdmo@mattdmo.com"
__all__ = ["articleAPI"]
| from search_api import *
__version__ = "1.0.0"
__author__ = "Matt Morrison (@MattDMo)"
__all__ = ["articleAPI"]
if __name__ == "__main__":
print("This module cannot be run on its own. Please use by running ",
"\"from NYTimesArticleAPI import articleAPI\"")
exit(0)
| Print message if module is run on its own | Print message if module is run on its own
| Python | mit | MattDMo/NYTimesArticleAPI | ---
+++
@@ -1,5 +1,10 @@
-from nytapi import *
+from search_api import *
__version__ = "1.0.0"
-__author__ = "Matt Morrison @MattDMo mattdmo@mattdmo.com"
+__author__ = "Matt Morrison (@MattDMo)"
__all__ = ["articleAPI"]
+
+if __name__ == "__main__":
+ print("This module cannot be run on its own. Please use by ... |
bf1cc589147429eb4cc125904c7c0690a6deaf1c | testsuite/N802.py | testsuite/N802.py | #: Okay
def ok():
pass
#: N802
def __bad():
pass
#: N802
def bad__():
pass
#: N802
def __bad__():
pass
#: Okay
def _ok():
pass
#: Okay
def ok_ok_ok_ok():
pass
#: Okay
def _somehow_good():
pass
#: Okay
def go_od_():
pass
#: Okay
def _go_od_():
pass
#: N802
def NotOK():
pass
#: Oka... | #: Okay
def ok():
pass
#: N802
def __bad():
pass
#: N802
def bad__():
pass
#: N802
def __bad__():
pass
#: Okay
def _ok():
pass
#: Okay
def ok_ok_ok_ok():
pass
#: Okay
def _somehow_good():
pass
#: Okay
def go_od_():
pass
#: Okay
def _go_od_():
pass
#: N802
def NotOK():
pass
#: Oka... | Add more tests around ignored names | Add more tests around ignored names
| Python | mit | flintwork/pep8-naming | ---
+++
@@ -59,3 +59,10 @@
#: Okay
def tearDown():
pass
+
+#: Okay
+class TestCase:
+ def setUp(self):
+ pass
+ def tearDown(self):
+ pass |
36663add9f53da925f1d29c8c567ab30a1f33139 | tests/api_resources/checkout/test_session.py | tests/api_resources/checkout/test_session.py | from __future__ import absolute_import, division, print_function
import stripe
TEST_RESOURCE_ID = "loc_123"
class TestSession(object):
def test_is_creatable(self, request_mock):
resource = stripe.checkout.Session.create(
cancel_url="https://stripe.com/cancel",
client_reference_i... | from __future__ import absolute_import, division, print_function
import stripe
TEST_RESOURCE_ID = "cs_123"
class TestSession(object):
def test_is_creatable(self, request_mock):
resource = stripe.checkout.Session.create(
cancel_url="https://stripe.com/cancel",
client_reference_id... | Add support for retrieving a Checkout Session | Add support for retrieving a Checkout Session
| Python | mit | stripe/stripe-python | ---
+++
@@ -3,7 +3,7 @@
import stripe
-TEST_RESOURCE_ID = "loc_123"
+TEST_RESOURCE_ID = "cs_123"
class TestSession(object):
@@ -27,3 +27,10 @@
)
request_mock.assert_requested("post", "/v1/checkout/sessions")
assert isinstance(resource, stripe.checkout.Session)
+
+ def test_is_r... |
ce5b3402d9dc5bf69b96c45a810a987d6d4b4231 | tests/functional_tests/test_valid_recipes.py | tests/functional_tests/test_valid_recipes.py | import os
import pytest
from conda_verify import utilities
from conda_verify.errors import RecipeError
from conda_verify.verify import Verify
@pytest.fixture
def recipe_dir():
return os.path.join(os.path.dirname(__file__), 'test_recipes')
@pytest.fixture
def verifier():
recipe_verifier = Verify()
retu... | import os
import pytest
from conda_verify import utilities
from conda_verify.verify import Verify
@pytest.fixture
def recipe_dir():
return os.path.join(os.path.dirname(__file__), 'test_recipes')
@pytest.fixture
def verifier():
recipe_verifier = Verify()
return recipe_verifier
def test_valid_test_fil... | Change exception from RecipeError to SystemExit | Change exception from RecipeError to SystemExit
| Python | bsd-3-clause | mandeep/conda-verify | ---
+++
@@ -3,7 +3,6 @@
import pytest
from conda_verify import utilities
-from conda_verify.errors import RecipeError
from conda_verify.verify import Verify
@@ -24,5 +23,5 @@
try:
verifier.verify_recipe(rendered_meta=metadata, recipe_dir=recipe)
- except RecipeError as error:
+ except S... |
11feab5b49bf818e8dde90497d90dafc7ceb5183 | src/locations/models.py | src/locations/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class District(models.Model):
name = models.CharField(_('Name'), max_length=255, unique=True)
class Meta:
verbose_name = _('District')
verbose_name_plural = _('Districts')
def __unicode__(self):
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
class District(models.Model):
name = models.CharField(_('Name'), max_length=255, unique=True)
class Meta:
verbose_name = _('District')
verbose_name_plural = _('Districts')
ordering = ['name']
def... | Order locations and districts by name | Order locations and districts by name
| Python | mit | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign | ---
+++
@@ -8,6 +8,7 @@
class Meta:
verbose_name = _('District')
verbose_name_plural = _('Districts')
+ ordering = ['name']
def __unicode__(self):
return self.name
@@ -23,6 +24,7 @@
unique_together = ('district', 'name')
verbose_name = _('Location')
... |
760af101c3b47fa4cf4aaeba5bc67aa94d2ba060 | src/Exscript/Interpreter/stdlib/IPv4/util.py | src/Exscript/Interpreter/stdlib/IPv4/util.py | import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4... | import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4... | Enforce endianess when converting IPs to long. | Enforce endianess when converting IPs to long.
git-svn-id: 21715c51dd601a1fb57681abbfe4e8ed6f4259bf@205 4c10cf09-d433-0410-9a0a-09c53010615a
| Python | mit | maximumG/exscript,knipknap/exscript,knipknap/exscript,maximumG/exscript | ---
+++
@@ -21,10 +21,10 @@
def ip2int(ip):
if ip == '255.255.255.255':
return 0xFFFFFFFFl
- return struct.unpack('L', socket.inet_aton(ip))[0]
+ return struct.unpack('!L', socket.inet_aton(ip))[0]
def int2ip(number):
- return socket.inet_ntoa(struct.pack('L', number))
+ return socket.in... |
45add3b1d96022244b372fe07d6f6dceab23786d | councilmatic_core/management/commands/update_headshots.py | councilmatic_core/management/commands/update_headshots.py | from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
from django.conf import settings
from opencivicdata.core.models import Person as OCDPerson
import requests
class Command(BaseCommand):
help = 'Attach headshots to councilmembers'
def handle(self, *args, **o... | from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
from django.conf import settings
from opencivicdata.core.models import Person as OCDPerson
import requests
class Command(BaseCommand):
help = 'Attach headshots to councilmembers'
def handle(self, *args, **o... | Add prefix to headshot filenames for easy exclusion from gitignore | Add prefix to headshot filenames for easy exclusion from gitignore
| Python | mit | datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic | ---
+++
@@ -13,7 +13,7 @@
def handle(self, *args, **opetions):
for person in OCDPerson.objects.exclude(image=''):
councilmatic_person = person.councilmatic_person
- filename = councilmatic_person.slug + '.jpg'
+ filename = 'ocd-person-' + councilmatic_person.slug + '.j... |
d07a009d28f3ea17558fd867817f3b19ad93ddfe | lobster/commands/configure.py | lobster/commands/configure.py | import logging
import os
from lobster import util
from lobster.core.command import Command
from lockfile import AlreadyLocked
class Configure(Command):
@property
def help(self):
return 'change the configuration of a running lobster process'
def setup(self, argparser):
argparser.add_argume... | import logging
import os
from lobster import util
from lobster.core.command import Command
from lockfile import AlreadyLocked
class Configure(Command):
@property
def help(self):
return 'change the configuration of a running lobster process'
def setup(self, argparser):
argparser.add_argume... | Send a newline with configuration commands. | Send a newline with configuration commands.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | ---
+++
@@ -28,6 +28,6 @@
logger.info("check the log of the main process for success")
icp = open(os.path.join(args.config.workdir, 'ipc'), 'w')
- icp.write(args.command)
+ icp.write(args.command + '\n')
except Exception as e:
logger.error("can't... |
98307aec0d3182e3e461bd1ed287b75b26ae6e36 | migrations/0013_update_counter_options.py | migrations/0013_update_counter_options.py | import json
from redash import models
if __name__ == '__main__':
for vis in models.Visualization.select():
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
if 'rowNumber' in options:
options['rowNumber'] += 1
... | import json
from redash import models
if __name__ == '__main__':
for vis in models.Visualization.select():
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
if 'rowNumber' in options and options['rowNumber'] is not None:
... | Make the counter migration safer. | Make the counter migration safer. | Python | bsd-2-clause | amino-data/redash,rockwotj/redash,getredash/redash,jmvasquez/redashtest,hudl/redash,pubnative/redash,getredash/redash,vishesh92/redash,stefanseifert/redash,alexanderlz/redash,getredash/redash,stefanseifert/redash,denisov-vlad/redash,ninneko/redash,crowdworks/redash,denisov-vlad/redash,easytaxibr/redash,amino-data/redas... | ---
+++
@@ -6,7 +6,7 @@
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
- if 'rowNumber' in options:
+ if 'rowNumber' in options and options['rowNumber'] is not None:
options['rowNumber'] += 1
... |
deb66ebeca0b39c7ce62fc95b8a01bf973739e86 | rosidl_generator_py/rosidl_generator_py/__init__.py | rosidl_generator_py/rosidl_generator_py/__init__.py | # Copyright 2014-2015 Open Source Robotics Foundation, 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 applicabl... | # Copyright 2014-2015 Open Source Robotics Foundation, 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 applicabl... | Fix pyflakes complaining of imported but unused module. | Fix pyflakes complaining of imported but unused module.
| Python | apache-2.0 | esteve/rosidl,ros2/rosidl_typesupport,ros2/rosidl_typesupport,esteve/rosidl,esteve/rosidl_typesupport,esteve/rosidl_typesupport,esteve/rosidl_typesupport,ros2/rosidl,ros2/rosidl,ros2/rosidl,ros2/rosidl_typesupport,esteve/rosidl,ros2/rosidl | ---
+++
@@ -21,6 +21,7 @@
try:
from .generate_py_impl import generate_py
+ assert generate_py
__all__.append('generate_py')
except ImportError:
logger = logging.getLogger('rosidl_generator_py') |
fab1a05fbeaf082432bd9f05b1fa721519838aff | ObjectTracking/DisplayIPVideoStream.py | ObjectTracking/DisplayIPVideoStream.py | import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
| #!/usr/bin/python
# coding=utf-8
import cv2
import cv2.cv as cv
import datetime
cv2.namedWindow("preview")
# Video feed created with android ip webcam program
vc = cv2.VideoCapture("http://192.168.1.2:8080/videofeed?something.mjpeg")
# Save output video
width, height = 640, 480
writer = cv2.VideoWriter(filename="out... | Add snapshot feature on s key press Add recording feature | Add snapshot feature on s key press
Add recording feature
| Python | mit | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | ---
+++
@@ -1,8 +1,20 @@
+#!/usr/bin/python
+# coding=utf-8
import cv2
+import cv2.cv as cv
+import datetime
cv2.namedWindow("preview")
-vc = cv2.VideoCapture(0)
+# Video feed created with android ip webcam program
+vc = cv2.VideoCapture("http://192.168.1.2:8080/videofeed?something.mjpeg")
+
+# Save output vide... |
41854e9dbed5780359659f6717f16e08caecb8e8 | diss/__init__.py | diss/__init__.py |
import os
import hashlib
import magic
from datetime import datetime
from .settings import METADATA_PATH
from .meta import get_meta
from .encryption import copy_and_encrypt, decrypt_blob
from .utils import dumps
hashing = hashlib.sha256
def save_metadata(meta):
destination = os.path.join(METADATA_PATH, meta['id... |
import os
import hashlib
import magic
from datetime import datetime
from .settings import METADATA_PATH
from .meta import get_meta
from .encryption import copy_and_encrypt, decrypt_blob
from .utils import dumps
hashing = hashlib.sha256
def save_metadata(meta):
destination = os.path.join(METADATA_PATH, meta['id... | Fix filename instead of path in meta | Fix filename instead of path in meta
| Python | agpl-3.0 | hoh/Billabong,hoh/Billabong | ---
+++
@@ -41,7 +41,7 @@
'info': {
'type': magic.from_file(filepath).decode(),
'mimetype': magic.from_file(filepath, mime=True).decode(),
- 'filename': filepath,
+ 'filename': os.path.basename(filepath),
'path': filepath,
}
} |
6bcf987ac927c4cd9829b55ec2521d77fcc2c3ad | examples/test_mfa_login.py | examples/test_mfa_login.py | from seleniumbase import BaseCase
class TestMFALogin(BaseCase):
def test_mfa_login(self):
self.open("https://seleniumbase.io/realworld/login")
self.type("#username", "demo_user")
self.type("#password", "secret_pass")
self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")
... | from seleniumbase import BaseCase
class TestMFALogin(BaseCase):
def test_mfa_login(self):
self.open("https://seleniumbase.io/realworld/login")
self.type("#username", "demo_user")
self.type("#password", "secret_pass")
self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")
... | Add a click() call to an example test | Add a click() call to an example test
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -8,5 +8,6 @@
self.type("#password", "secret_pass")
self.enter_mfa_code("#totpcode", "GAXG2MTEOR3DMMDG")
self.highlight("img#image1")
+ self.click('a:contains("This Page")')
self.assert_text("Welcome!", "h1")
self.save_screenshot_to_logs() |
f9648e4b48d2affee103ad5f229492254e3e4dc8 | web3/web3/jsonrpc.py | web3/web3/jsonrpc.py | class Jsonrpc(object):
def __init__(self):
self.messageId = 0
@staticmethod
def getInstance():
return Jsonrpc()
def toPayload(self, method, params):
"""
Should be called to valid json create payload object
"""
if not method:
raise Exception(... | import json
class Jsonrpc(object):
def toPayload(self, reqid, method, params):
"""
Should be called to valid json create payload object
"""
if not method:
raise Exception("jsonrpc method should be specified!")
return json.dumps({
"jsonrpc": "2.0",
... | Move message id generation to requestmanager | Move message id generation to requestmanager
| Python | mit | pipermerriam/web3.py,shravan-shandilya/web3.py | ---
+++
@@ -1,27 +1,26 @@
+import json
+
class Jsonrpc(object):
- def __init__(self):
- self.messageId = 0
-
- @staticmethod
- def getInstance():
- return Jsonrpc()
-
- def toPayload(self, method, params):
+ def toPayload(self, reqid, method, params):
"""
Should be ca... |
d9f388d2b486da3bd5e3209db70d3e691aec584d | clowder/clowder/cli/yaml_controller.py | clowder/clowder/cli/yaml_controller.py | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class YAMLController(AbstractBaseController):
class Meta:
label = 'yaml'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Print clowder.yaml information'
... | from __future__ import print_function
import sys
from cement.ext.ext_argparse import expose
import clowder.util.formatting as fmt
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
from clowder... | Add `clowder yaml` logic to Cement controller | Add `clowder yaml` logic to Cement controller
| Python | mit | JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder | ---
+++
@@ -1,6 +1,16 @@
+from __future__ import print_function
+
+import sys
+
from cement.ext.ext_argparse import expose
+import clowder.util.formatting as fmt
from clowder.cli.abstract_base_controller import AbstractBaseController
+from clowder.util.decorators import (
+ print_clowder_repo_status,
+ vali... |
398718e615cab79066779cb19c2023062bc36110 | contrib/core/actions/inject_trigger.py | contrib/core/actions/inject_trigger.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Remove out of date comment. | Remove out of date comment.
| Python | apache-2.0 | Plexxi/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2 | ---
+++
@@ -23,20 +23,13 @@
class InjectTriggerAction(Action):
- """
- NOTE: Server where this action run needs to have access to the database.
-
- That's always the case right now, but if this assertion changes in the future, we should move
- to utilizing the API for dispatching a trigger.
- """
... |
7843ba68582c7da1312d081c0b741d57852d718f | test/utils/filesystem/name_sanitizer_spec.py | test/utils/filesystem/name_sanitizer_spec.py | from tempfile import TemporaryDirectory
from expects import expect
from hypothesis import given, assume, example
from hypothesis.strategies import text, characters
from mamba import description, it
from pathlib import Path
from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \
invalid_f... | from tempfile import TemporaryDirectory
from expects import expect
from hypothesis import given, assume, example
from hypothesis.strategies import text, characters
from mamba import description, it
from pathlib import Path
from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \
invalid_f... | Update the maximum allowed length for file name in sanitizer test | Update the maximum allowed length for file name in sanitizer test
| Python | mit | Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki | ---
+++
@@ -16,7 +16,7 @@
.not_to(contain_any(*invalid_filename_chars))
with it("should be possible to create a file name from a random sanitized string"):
- @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=255, min_size=1))
+ @given(text(characters(min_codepoint=... |
5945b27aa6b5ae43470738dd6638ffa4617f7be1 | poradnia/users/migrations/0014_auto_20170317_1927.py | poradnia/users/migrations/0014_auto_20170317_1927.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0013_profile_event_reminder_time'),
]
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
from django.db import migrations, models
try:
import django.contrib.auth.validators
extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
e... | Fix backward compatibility of migrations | Fix backward compatibility of migrations
| Python | mit | watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia | ---
+++
@@ -2,8 +2,12 @@
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
-import django.contrib.auth.validators
from django.db import migrations, models
+try:
+ import django.contrib.auth.validators
+ extra_kwargs = {'validators': [django.contrib.auth.validators.ASC... |
32d95efb4549a9cb3b3e6780efb292705de57713 | pronto_praise/pronto_praise/settings/heroku.py | pronto_praise/pronto_praise/settings/heroku.py | import dj_database_url
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
MIDDLEWARE = MIDDLEWARE + [
'whitenoise.middleware.WhiteNoiseMiddleware',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DATABASES['default'] = dj_database_url.config()
| import dj_database_url
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
MIDDLEWARE = MIDDLEWARE + [
'whitenoise.middleware.WhiteNoiseMiddleware',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DATABASES['default'] = dj_database_url.config()
| Revert "Turn on DEBUG mode" | Revert "Turn on DEBUG mode"
This reverts commit 1c0e3251c3b502375a9738508f20a18ed58532ec.
| Python | mit | prontotools/pronto-praise,prontotools/pronto-praise,prontotools/pronto-praise,prontotools/pronto-praise | ---
+++
@@ -3,7 +3,7 @@
from .base import *
-DEBUG = True
+DEBUG = False
ALLOWED_HOSTS = ['*']
|
74466e4bdce2a865718701b1bcccb2c884eac6ab | wsgi.py | wsgi.py | #!/usr/bin/env python3
import os
import logging
from sqlalchemy import create_engine
from portingdb import load
from portingdb import htmlreport
level = logging.DEBUG
logging.basicConfig(level=level)
logging.getLogger('sqlalchemy.engine').setLevel(level)
sqlite_path = os.path.join(os.environ['OPENSHIFT_TMP_DIR'], ... | #!/usr/bin/env python3
import os
import logging
from sqlalchemy import create_engine
from portingdb import load
from portingdb import htmlreport
level = logging.INFO
logging.basicConfig(level=level)
logging.getLogger('sqlalchemy.engine').setLevel(level)
sqlite_path = os.path.join(os.environ['OPENSHIFT_TMP_DIR'], '... | Reduce log level on OpenShift | Reduce log level on OpenShift
| Python | mit | sYnfo/portingdb,ari3s/portingdb,sYnfo/portingdb,fedora-python/portingdb,irushchyshyn/portingdb,irushchyshyn/portingdb,irushchyshyn/portingdb,ari3s/portingdb,irushchyshyn/portingdb,ari3s/portingdb,fedora-python/portingdb,fedora-python/portingdb,sYnfo/portingdb,ari3s/portingdb | ---
+++
@@ -8,7 +8,7 @@
from portingdb import load
from portingdb import htmlreport
-level = logging.DEBUG
+level = logging.INFO
logging.basicConfig(level=level)
logging.getLogger('sqlalchemy.engine').setLevel(level)
|
8f1f15dc66c357f2ace070c449dd5e407b1e9f33 | x10d.py | x10d.py | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def main(args):
serial_port = "/dev/ttyACM1"
baud = 9600
s = Serial(serial_port, ba... | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def main(args):
serial_port = args[1]
baud = 9600
s = Serial(serial_port, baud)
... | Add closing and argument for serial port | Add closing and argument for serial port
| Python | unlicense | umbc-hackafe/x10-controller | ---
+++
@@ -8,7 +8,7 @@
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def main(args):
- serial_port = "/dev/ttyACM1"
+ serial_port = args[1]
baud = 9600
s = Serial(serial_port, baud)
@@ -19,6 +19,7 @@
daemon_thread = Thread(target=daemon.listen, name="daemon-listener"... |
444a66b0b0da31ed4febea2dcd82fbf6d12ea107 | examples/deploy_local_file_resource.py | examples/deploy_local_file_resource.py | """
This example:
1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
itself active
3. Destroys the unit and application
"""
from juju import jasyncio
from juju.model import Model
from pathlib import Path
async def main():
model = Model()
print('C... | """
This example:
1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
itself active
3. Destroys the unit and application
"""
from juju import jasyncio
from juju.model import Model
from pathlib import Path
async def main():
model = Model()
print('C... | Make sure we cleanup even if fails in example | Make sure we cleanup even if fails in example
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju | ---
+++
@@ -18,6 +18,7 @@
# connect to current model with current user, per Juju CLI
await model.connect()
+ application = None
try:
print('Deploying local-charm')
base_dir = Path(__file__).absolute().parent.parent
@@ -33,6 +34,11 @@
print('Removing Charm')
aw... |
bea7fb4d47bf5cc87edcf1deff155b694e824295 | webapp/byceps/blueprints/board/formatting.py | webapp/byceps/blueprints/board/formatting.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.board.formatting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from cgi import escape
import bbcode
try:
from .smileys import get_smileys
except ImportError:
get_smileys = lamb... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.board.formatting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from html import escape
import bbcode
try:
from .smileys import get_smileys
except ImportError:
get_smileys = lam... | Use `html.escape` instead of the deprecated `cgi.escape`. | Use `html.escape` instead of the deprecated `cgi.escape`.
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | ---
+++
@@ -8,7 +8,7 @@
:License: Modified BSD, see LICENSE for details.
"""
-from cgi import escape
+from html import escape
import bbcode
|
5acee7067df2af2b351bfb4b5757b4d53f023d32 | radio/management/commands/export_talkgroups.py | radio/management/commands/export_talkgroups.py | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Import talkgroup info'
def add_arguments(self, parser):
parser.add_... | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Import talkgroup info'
def add_arguments(self, parser):
parser.add_... | Add system support to export talkgroups | Add system support to export talkgroups
| Python | mit | ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player | ---
+++
@@ -12,15 +12,25 @@
def add_arguments(self, parser):
parser.add_argument('file')
+ parser.add_argument(
+ '--system',
+ type=int,
+ default=-1,
+ help='Export talkgroups from only this system',
+ )
+
def handle(self, *args, **opti... |
025bc069e231b58977e7d8ea7c526849f227b9ff | pytest_pipeline/utils.py | pytest_pipeline/utils.py | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener = gzip.op... | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener... | Add utility function for executable checking | Add utility function for executable checking
| Python | bsd-3-clause | bow/pytest-pipeline | ---
+++
@@ -12,6 +12,7 @@
import gzip
import hashlib
+import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
@@ -27,3 +28,18 @@
hasher.update(buf)
buf = src.read(blocksize)
return hasher.hexdigest()
+
+
+def isexecfile(fname):
+ return os.path.isfile(fname... |
fbc0578a0a359c5bed5317a971f40128ca73429e | python/test/providers.py | python/test/providers.py | # -*- coding: utf-8 -*-
import stromx.runtime as sr
stream = sr.Stream()
stream.setName("My stream")
data = "dfdsfdsds\nkljöklöjkfldsjf"
factory = sr.Factory()
with sr.ZipFileOutput("provider_test.zip") as out:
out.initialize("filename")
out.openFile(".txt", sr.OutputProvider.OpenMode.TEXT)
out.file().wr... | # -*- coding: utf-8 -*-
import stromx.runtime as sr
stream = sr.Stream()
stream.setName("My stream")
data = "dfdsfdsds\nkljkljkfldsjf"
factory = sr.Factory()
with sr.ZipFileOutput("provider_test.zip") as out:
out.initialize("filename")
out.openFile(".txt", sr.OutputProvider.OpenMode.TEXT)
out.file().writ... | Fix python data provider test | Fix python data provider test
| Python | apache-2.0 | uboot/stromx,uboot/stromx | ---
+++
@@ -4,7 +4,7 @@
stream = sr.Stream()
stream.setName("My stream")
-data = "dfdsfdsds\nkljöklöjkfldsjf"
+data = "dfdsfdsds\nkljkljkfldsjf"
factory = sr.Factory()
with sr.ZipFileOutput("provider_test.zip") as out: |
40bc1f50e7b0605522feb4ac86daebb9f785eb88 | test/OLItest/globals.py | test/OLItest/globals.py | #Constants, that don't rely on anything else in the module
# Copyright (C) 2012- Sebastian Spaeth & contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... | #Constants, that don't rely on anything else in the module
# Copyright (C) 2012- Sebastian Spaeth & contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of th... | Use only 1 IMAP connection by default | tests: Use only 1 IMAP connection by default
We don't want to hammmer IMAP servers for the test series too much
to avoid being locked out. We will need a few tests to test
concurrent connections, but by default one connection should be fine.
Signed-off-by: Sebastian Spaeth <98dcb2717ddae152d5b359c6ea97e4fe34a29d4c@SS... | Python | apache-2.0 | frioux/offlineimap,frioux/offlineimap | ---
+++
@@ -33,5 +33,7 @@
[Repository IMAP]
type=IMAP
+# Don't hammer the server with too many connection attempts:
+maxconnections=1
folderfilter= lambda f: f.startswith('INBOX.OLItest')
""") |
bc634d8c04bc15ca381019dda08982b9e1badd1c | sncosmo/tests/test_builtins.py | sncosmo/tests/test_builtins.py | import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
de... | import pytest
import sncosmo
from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
from sncosmo.magsystems import _MAGSYSTEMS
from sncosmo.models import _SOURCES
bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
bandpass_interpolators = [i['name'] for i in
... | Add tests for all builtins | Add tests for all builtins
| Python | bsd-3-clause | sncosmo/sncosmo,sncosmo/sncosmo,sncosmo/sncosmo | ---
+++
@@ -2,33 +2,38 @@
import sncosmo
+from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
+from sncosmo.magsystems import _MAGSYSTEMS
+from sncosmo.models import _SOURCES
-@pytest.mark.might_download
-def test_hst_bands():
- """ check that the HST and JWST bands are accessible """
- ... |
d9e65fbf111f8584189a57059516afafb1e4d04c | test/projection_test.py | test/projection_test.py | from amii_tf_nn.projection import l1_projection_to_simplex
import tensorflow as tf
import pytest
def test_l1_no_negative():
patient = l1_projection_to_simplex(tf.constant([2.0, 8.0, 0.0]))
with tf.Session() as sess:
print(sess.run(patient))
strat = sess.run(patient)
x_strat = [0.2, 0.8... | from amii_tf_nn.projection import l1_projection_to_simplex
import tensorflow as tf
class ProjectionTest(tf.test.TestCase):
def test_l1_no_negative(self):
with self.test_session():
self.assertAllClose(
l1_projection_to_simplex(tf.constant([2.0, 8.0, 0.0])).eval(),
... | Use TensorFlow's test utilities and add a test for the L1 projection to simplex. | Use TensorFlow's test utilities and add a test for the L1 projection to simplex.
| Python | mit | AmiiThinks/amii-tf-nn | ---
+++
@@ -1,25 +1,42 @@
from amii_tf_nn.projection import l1_projection_to_simplex
import tensorflow as tf
-import pytest
-def test_l1_no_negative():
- patient = l1_projection_to_simplex(tf.constant([2.0, 8.0, 0.0]))
- with tf.Session() as sess:
- print(sess.run(patient))
- strat = sess.ru... |
d7a91fe283666f01aa06a707c536893cf1473fe3 | rtwilio/models.py | rtwilio/models.py | import datetime
from django.db import models
class TwilioResponse(models.Model):
date = models.DateTimeField()
message = models.CharField(max_length=64, primary_key=True)
account = models.CharField(max_length=64)
sender = models.CharField(max_length=16)
recipient = models.CharField(max_length=16)... | from django.db import models
from django.utils import timezone
class TwilioResponse(models.Model):
date = models.DateTimeField()
message = models.CharField(max_length=64, primary_key=True)
account = models.CharField(max_length=64)
sender = models.CharField(max_length=16)
recipient = models.CharFie... | Use timezone aware datetime now. | Use timezone aware datetime now.
| Python | bsd-3-clause | caktus/rapidsms-twilio | ---
+++
@@ -1,6 +1,5 @@
-import datetime
-
from django.db import models
+from django.utils import timezone
class TwilioResponse(models.Model):
@@ -13,5 +12,5 @@
def save(self, **kwargs):
if not self.date:
- self.date = datetime.datetime.now()
+ self.date = timezone.now()
... |
6340e6f02c3655dc2ab33a67491cc9b16e63e5b0 | redux/__main__.py | redux/__main__.py | from redux.codegenerator import compile_script
from argparse import ArgumentParser
from os.path import splitext
parser = ArgumentParser(description='Compile a Redux script to Rescript.')
parser.add_argument('filenames', metavar='FILE', nargs='+',
help='script to be compiled to Rescript')
args = pa... | from redux.codegenerator import compile_script
from argparse import ArgumentParser
from os.path import splitext
parser = ArgumentParser(description='Compile a Redux script to Rescript.')
parser.add_argument('input_filename', metavar='FILE',
help='script to be compiled to Rescript')
parser.add_argum... | Make compiler invocation more Makefile-friendly | Make compiler invocation more Makefile-friendly
| Python | mit | Muon/redux | ---
+++
@@ -3,15 +3,21 @@
from os.path import splitext
parser = ArgumentParser(description='Compile a Redux script to Rescript.')
-parser.add_argument('filenames', metavar='FILE', nargs='+',
+parser.add_argument('input_filename', metavar='FILE',
+ help='script to be compiled to Rescript')
+pars... |
5c214680889a40a2963572e1163b8aa6beeaebc4 | bayespy/nodes/__init__.py | bayespy/nodes/__init__.py | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
=... | ################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Package for nodes used to construct the model.
Stochastic nodes
=... | Add Take node to the node list in API doc | DOC: Add Take node to the node list in API doc
| Python | mit | jluttine/bayespy,bayespy/bayespy | ---
+++
@@ -88,6 +88,7 @@
SumMultiply
Add
Gate
+ Take
"""
# Currently, model construction and the inference network are not separated so |
60743b33e5034776576073b151c7a02dc0a40b7e | tests/unit_project/test_fields.py | tests/unit_project/test_fields.py | from djangosanetesting.cases import DatabaseTestCase
from djangomarkup.fields import RichTextField
from djangomarkup.models import SourceText
from exampleapp.models import Article
class TestRichTextField(DatabaseTestCase):
def setUp(self):
super(TestRichTextField, self).setUp()
self.field = Rich... | from djangosanetesting.cases import UnitTestCase
from djangomarkup.fields import RichTextField
from exampleapp.models import Article
class TestRichTextField(UnitTestCase):
def setUp(self):
super(TestRichTextField, self).setUp()
self.field = RichTextField(
instance = Article(),
... | Check proper error when accessing source without instance | Check proper error when accessing source without instance
| Python | bsd-3-clause | ella/django-markup | ---
+++
@@ -1,11 +1,10 @@
-from djangosanetesting.cases import DatabaseTestCase
+from djangosanetesting.cases import UnitTestCase
from djangomarkup.fields import RichTextField
-from djangomarkup.models import SourceText
from exampleapp.models import Article
-class TestRichTextField(DatabaseTestCase):
+class T... |
4313c5528efd02c45013907300b33436ce31eddd | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields, api
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course'
name = fields.Char(string="Title", required=True)
description = fields.Text(string="Description")
resp... | from openerp import models, fields, api
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course'
name = fields.Char(string="Title", required=True)
description = fields.Text(string="Description")
resp... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | mapuerta/openacademy-proyect | ---
+++
@@ -19,8 +19,23 @@
('name_description_check',
'CHECK(name != description)',
"The title of the course should not be the description"),
-
+
('name_unique',
'UNIQUE(name)',
"The course title must be unique"),
- ]
+ ]
+
+ @api.one #ap... |
440305707dfbf9a7a321b48250245edafc42aa73 | candidates/csv_helpers.py | candidates/csv_helpers.py | from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
not row['election_current'],
row['election_date'],
row['election'],
row['post_label']
... | from __future__ import unicode_literals
from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['el... | Sort on first name after last name | Sort on first name after last name
| Python | agpl-3.0 | mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/you... | ---
+++
@@ -7,6 +7,7 @@
def _candidate_sort_by_name_key(row):
return (
row['name'].split()[-1],
+ row['name'].rsplit(None, 1)[0],
not row['election_current'],
row['election_date'],
row['election'],
@@ -19,7 +20,9 @@
row['election_date'],
row['election... |
217af37f3aa7856770ce30b75df28bcd3582bb79 | geotrek/trekking/tests/test_filters.py | geotrek/trekking/tests/test_filters.py | # -*- coding: utf-8 -*-
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = TrekFilterSet
def create_pair_of_distinct_path(self):
u... | # -*- coding: utf-8 -*-
from geotrek.land.filters import *
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = TrekFilterSet
def test_land_... | Make sure land filters are setup when testing | Make sure land filters are setup when testing
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,camillemonchicourt/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,jo... | ---
+++
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from geotrek.land.filters import *
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
@@ -10,6 +11,10 @@
filterclass = TrekFilterSet
+ def test_land_filters_are_well_setup(self):
+ filt... |
1ce1998f649cf2449c0898d2b59630d715ab7154 | smallprox/core.py | smallprox/core.py | import asyncio
import os
import logging
import re
import dns.resolver
logging.basicConfig()
from .server import HTTPServer
from .mapper import update_config, add_container
logger = logging.getLogger('small-prox')
def _get_local_address():
resolver = dns.resolver.Resolver()
try:
resolver.query('doc... | import asyncio
import os
import logging
import re
import dns.resolver
logging.basicConfig()
from .server import HTTPServer
from .mapper import update_config, add_container
logger = logging.getLogger('small-prox')
def _get_local_address():
resolver = dns.resolver.Resolver()
try:
resolver.query('doc... | Fix getting host ip on linux | Fix getting host ip on linux
| Python | mit | nhumrich/small-prox | ---
+++
@@ -21,7 +21,7 @@
except:
# must be on linux, get host ip
result = os.popen('ip r').read()
- ip, _ = re.match('default via (.*?)\s', result).groups(1)
+ ip = re.match('default via (.*?)\s', result).groups(1)[0]
return ip
|
f531cfa07ba6e6e0d36ba768dbeb4706ae7cd259 | tlslite/utils/pycrypto_rsakey.py | tlslite/utils/pycrypto_rsakey.py | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""PyCrypto RSA implementation."""
from .cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
... | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""PyCrypto RSA implementation."""
from cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
... | Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working) | Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
| Python | lgpl-2.1 | ioef/tlslite-ng,ioef/tlslite-ng,ioef/tlslite-ng | ---
+++
@@ -3,7 +3,7 @@
"""PyCrypto RSA implementation."""
-from .cryptomath import *
+from cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
@@ -15,9 +15,9 @@
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.