commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
ad622ab0a4a70187ffb023687a64497657d79442
members/views.py
members/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first...
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): ...
Use default auth django app
Use default auth django app
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
03d9c825bb7e86550b3d6fa9afd39c126cb9034d
basis_set_exchange/__init__.py
basis_set_exchange/__init__.py
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_fam...
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_fam...
Add simple function to get the version of the bse
Add simple function to get the version of the bse
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
bcb24ef03a65d80c09ef47f19a64fd854a70c082
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), ...
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, ...
Test PrintReport with a real stream
Test PrintReport with a real stream
Python
mit
ktnyt/chainer,pfnet/chainer,rezoo/chainer,hvy/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,jnishi/chainer,niboshi/chainer,hvy/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,chainer/chainer,keisuke-umezawa/cha...
798e547eba14721009854796e4306dc7d739bc03
manage.py
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
UPDATE - change env variable
UPDATE - change env variable
Python
mit
mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah
95eb73ce7645ae6275fbb958ec803ce521b16198
helusers/urls.py
helusers/urls.py
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.Lo...
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to u...
Check configuration before specifying urlpatterns
Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
0778a0a47967f0283a22908bcf89c0d98ce1647f
tests/test_redefine_colors.py
tests/test_redefine_colors.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
Test color redefinition on nix
Test color redefinition on nix
Python
bsd-3-clause
MisanthropicBit/colorise
963ad8662b44d223bd5003c848dccc65802016e3
src/tests/utils.py
src/tests/utils.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse...
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_ma...
Use mdptoolbox.example.small in the tests
[tests] Use mdptoolbox.example.small in the tests
Python
bsd-3-clause
yasserglez/pymdptoolbox,silgon/pymdptoolbox,sawcordwell/pymdptoolbox,yasserglez/pymdptoolbox,sawcordwell/pymdptoolbox,silgon/pymdptoolbox,McCabeJM/pymdptoolbox,McCabeJM/pymdptoolbox
810c4061a4ba34eef862a5c8e0d6fafbdb9ec566
allauth/socialaccount/providers/stripe/provider.py
allauth/socialaccount/providers/stripe/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_ui...
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', defa...
Add proper stringification via StripeAccount.to_str
feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.
Python
mit
pztrick/django-allauth,rsalmaso/django-allauth,pztrick/django-allauth,lukeburden/django-allauth,bittner/django-allauth,pennersr/django-allauth,pennersr/django-allauth,bittner/django-allauth,AltSchool/django-allauth,lukeburden/django-allauth,lukeburden/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,rsalma...
6fb5110d4fb1c3de7d065267f9d8f7302c303ec1
allauth/socialaccount/providers/twitch/provider.py
allauth/socialaccount/providers/twitch/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): ...
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): ...
Add user_read as default scope
twitch: Add user_read as default scope
Python
mit
bittner/django-allauth,pennersr/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pztrick/django-allauth,lukeburden/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,rsalmas...
9ac9efbea5ad9e51d564ec563fe25349726ec1f7
inpassing/view_util.py
inpassing/view_util.py
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) =...
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) ...
Add function to figure out if a given daystate ID is valid for an org
Add function to figure out if a given daystate ID is valid for an org
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
fa404452f77b3756e2a54df75c6503cae697e118
mentor/forms.py
mentor/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "e...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "passw...
Copy email address to username
Copy email address to username
Python
mit
amaunder21/c4tkmentors,amaunder21/c4tkmentors
808cd0f8ac27a9f113efddba50a37837f364723e
idios/models.py
idios/models.py
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from d...
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.Foreig...
Revert "added GFK for group"
Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.
Python
bsd-3-clause
eldarion/idios,eldarion/idios,paltman/idios,rbrady/idios,rbrady/idios,paltman/idios
5c7f881cd2122be826c2c7351c1c221479ebec39
lib/challenge.py
lib/challenge.py
# python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-----...
# python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self):...
Add SimpleNamespace objects for model and result of challange parent class.
Add SimpleNamespace objects for model and result of challange parent class.
Python
mit
elmar-hinz/Python.Challenges
f053615c51a7b937e4dedc561757f675e95380a7
poradnia/cases/migrations/0002_auto_20150102_1532.py
poradnia/cases/migrations/0002_auto_20150102_1532.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags',...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
Fix cases migrations after drop tags
Fix cases migrations after drop tags
Python
mit
rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia
43e4e154df6274ea80b5d495a682c2d17cdb178d
cla_backend/apps/knowledgebase/tests/test_events.py
cla_backend/apps/knowledgebase/tests/test_events.py
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] ...
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN',...
Add new outcome codes to tests
Add new outcome codes to tests
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
1de4a0edd0f3c43b53e3a91c10d23155889791c6
tca/chat/tests.py
tca/chat/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ ...
Add a helper mixin for view test cases
Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).
Python
bsd-3-clause
mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend
a688c8287c7f4c52d856f5bef363a73526a7b1d8
orders/views.py
orders/views.py
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_p...
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__boo...
Optimize number of SQL queries in Order details view
Optimize number of SQL queries in Order details view
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
b90433326e2d99b34acceb8552b038501a7d238d
examples/regression_offset_autograd.py
examples/regression_offset_autograd.py
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function ...
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function ...
Fix regression autograd example for python3
Fix regression autograd example for python3
Python
bsd-3-clause
nkoep/pymanopt,nkoep/pymanopt,nkoep/pymanopt,tingelst/pymanopt,pymanopt/pymanopt,pymanopt/pymanopt,j-towns/pymanopt
92631d96a9acac10e8af98bbaa5ec2afee1ae12f
openrcv/main.py
openrcv/main.py
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: ...
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): ...
Add code for generating test files.
Add code for generating test files.
Python
mit
cjerdonek/open-rcv,cjerdonek/open-rcv
5cd87adf93502a4de5b413c2f537af57ffe4c418
paley.py
paley.py
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math....
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math....
Use 2D array instead of 1D to keep track of which edges have been drawn
Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessary
Python
mit
smpcole/paley-graph-drawer,smpcole/paley-graph-drawer
78ef59e29e2bed99d07261ff947f16be69e0e6b5
tests/fake_dbus_tools/swm.py
tests/fake_dbus_tools/swm.py
import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/...
import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/...
Replace gtk mainloop with glib mainloop
Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails
Python
mpl-2.0
advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp
13c1410de300a7f414b51cb001534f021441a00f
tests/test_authentication.py
tests/test_authentication.py
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() ...
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() ...
Test that there is a json content type
Test that there is a json content type
Python
mit
jenca-cloud/jenca-authentication
b82d67fa5f4b0ccb9b31a640e65226fea5887c67
typhon/__init__.py
typhon/__init__.py
# -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import ...
import functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from ....
Add top-level function to control the loglevel
Add top-level function to control the loglevel
Python
mit
atmtools/typhon,atmtools/typhon
4a1bf1bfce80a7ee25e6a60ebf350f86d89a0b58
report.py
report.py
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg....
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg....
Fix ratio followers/following only displayed for "humans"
Fix ratio followers/following only displayed for "humans"
Python
mit
franckbrignoli/twitter-bot-detection
d2793192f88cfc7f5054048583fb514ac1904ffd
posts.py
posts.py
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_js...
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sam...
Move stuff to function for ross
Move stuff to function for ross
Python
mit
RossCarriga/repost-data
81e236f81343f7e4f21cf6b01329d3d1ac738f9f
tests/test_pulse_types.py
tests/test_pulse_types.py
import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = Qub...
import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFac...
Make test environment use CNOT_CR implementation of CNOT.
Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.
Python
apache-2.0
BBN-Q/QGL,BBN-Q/QGL
cab417f187b66b5ec2f98fc69dcb8f8e98c43b86
tests/tests/middleware.py
tests/tests/middleware.py
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.asse...
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.asse...
Add test for invalid bearer token
Add test for invalid bearer token
Python
mit
Rediker-Software/doac
f31f17da75557ce45977589d7da0e1b1fd6612dd
niftianon/cli.py
niftianon/cli.py
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymis...
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMA...
Add docstring to command line entrypoint function
Add docstring to command line entrypoint function
Python
mit
jstutters/niftianon
ca19a982f5302fa0aefbaad2b97fa338b01103b3
queue.py
queue.py
from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(se...
from __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def ...
Complete first pass of functions
Complete first pass of functions
Python
mit
jay-tyler/data-structures,jonathanstallings/data-structures
0a4057a1c220076a34182327de9b01e8412ad68e
neutron_fwaas/tests/functional/test_fwaas_driver.py
neutron_fwaas/tests/functional/test_fwaas_driver.py
# Copyright (c) 2015 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
# Copyright (c) 2015 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
Use BaseSudoTestCase instead of BaseLinuxTestCase
Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628
Python
apache-2.0
openstack/neutron-fwaas,gaolichuang/neutron-fwaas,gaolichuang/neutron-fwaas,openstack/neutron-fwaas
624c52c63084f91429400fcc590e70b9c122ba7c
oslo/__init__.py
oslo/__init__.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
# 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 # d...
Remove extraneous vim editor configuration comments
Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324
Python
apache-2.0
varunarya10/oslo.i18n,openstack/oslo.i18n
e334f80c5252aabacff5b14df368f4326056c81c
lib/weblogic/wlst/create_oia_domain.py
lib/weblogic/wlst/create_oia_domain.py
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.s...
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "...
Revert "added function to change OIA AdminServer nodemanager credentials"
Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.
Python
bsd-2-clause
kapfenho/iam-deployer,kapfenho/iam-deployer,kapfenho/iam-deployer,kapfenho/iam-deployer
e6e121e1756d215bcf452522e268899d8669614c
dev_settings.py
dev_settings.py
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ...
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django E...
Use `$ which bower` by default
Use `$ which bower` by default @benrudolph What do you think of this approach?
Python
bsd-3-clause
qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
97f84c2e7643e295623ccd09d1b447d405fd5bfa
wal_e/blobstore/s3/s3_credentials.py
wal_e/blobstore/s3/s3_credentials.py
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E'...
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E'...
Fix InstanceProfileProvider class for boto 2.24
Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that t...
Python
bsd-3-clause
heroku/wal-e,ajmarks/wal-e,DataDog/wal-e,x86Labs/wal-e,modulexcite/wal-e,ArtemZ/wal-e,fdr/wal-e,tenstartups/wal-e,intoximeters/wal-e,equa/wal-e,wal-e/wal-e,RichardKnop/wal-e,nagual13/wal-e
6fbe2615770cfccf5b1711bf1a1c51bb14334341
txircd/modules/cmode_s.py
txircd/modules/cmode_s.py
from txircd.modbase import Mode class SecretMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"].clear() # other +s stuff is hiding in other modules. ...
from twisted.words.protocols import irc from txircd.modbase import Mode class SecretMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "NAMES": return data remove = [] for chan in data["targetchan"]: if "p" in chan.mode and chan.name not in user.channels: user.sendMessage(irc.ERR_NOSUCH...
Hide secret channels from /NAMES users
Hide secret channels from /NAMES users
Python
bsd-3-clause
ElementalAlchemist/txircd,DesertBus/txircd,Heufneutje/txircd
79c9ee6107b841986054915c23f8456c80097c5b
osgtest/tests/test_13_gridftp.py
osgtest/tests/test_13_gridftp.py
import os import osgtest.library.core as core import unittest class TestStartGridFTP(unittest.TestCase): def test_01_start_gridftp(self): core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid' core.state['gridftp.started-server'] = False if not core.rpm_is_installed('globu...
import os from osgtest.library import core, osgunittest import unittest class TestStartGridFTP(osgunittest.OSGTestCase): def test_01_start_gridftp(self): core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid' core.state['gridftp.started-server'] = False core.skip_ok_unless...
Update 13_gridftp to use OkSkip functionality
Update 13_gridftp to use OkSkip functionality git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16527 4e558342-562e-0410-864c-e07659590f8c
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
6a1f01dd815bf8054a30a85acafa233c8b397c6d
read_DS18B20.py
read_DS18B20.py
import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() ret...
import datetime import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folders = glob.glob(base_dir + '28-*') devices = map(lambda x: os.path.basename(x), device_folders) device_files = map(lambda x: x + '/w1_slave', device_folders) def...
Augment read to handle multiple connected DS18B20 devices
Augment read to handle multiple connected DS18B20 devices
Python
mit
barecode/iot_temp_sensors,barecode/iot_temp_sensors,barecode/iot_temp_sensors
494378256dc5fc6fed290a87afcbcc79b31eb37e
linguine/ops/word_cloud_op.py
linguine/ops/word_cloud_op.py
class WordCloudOp: def run(self, data): terms = { } results = [ ] try: for corpus in data: tokens = corpus.tokenized_contents for token in tokens: if token in terms: terms[token]+=1 e...
class WordCloudOp: def run(self, data): terms = { } results = [ ] try: for corpus in data: tokens = corpus.tokenized_contents for token in tokens: if token in terms: terms[token]+=1 e...
Sort term frequency results by frequency
Sort term frequency results by frequency
Python
mit
rigatoni/linguine-python,Pastafarians/linguine-python
dc934f178c5101e0aad592b55101c36608a2eab9
girder/molecules/molecules/utilities/pagination.py
girder/molecules/molecules/utilities/pagination.py
def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', -1)] return limit, offset, sort def parse_pagination_params(param...
from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', SortDir.DESCENDING)] return l...
Use SortDir.DESCENDING for default sort direction
Use SortDir.DESCENDING for default sort direction Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
Python
bsd-3-clause
OpenChemistry/mongochemserver
169a17849349e91cc1673c573437a9922bd07aa5
massa/domain.py
massa/domain.py
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Col...
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Col...
Add a command to find a measurement by id.
Add a command to find a measurement by id.
Python
mit
jaapverloop/massa
fa14a8d4733c32269323878b85ac80590ff7f39e
pyconde/sponsorship/tasks.py
pyconde/sponsorship/tasks.py
from contextlib import closing from django.core import mail from django.template.loader import render_to_string from django.conf import settings from django.contrib.auth.models import User from pyconde.sponsorship.models import JobOffer from pyconde.accounts.models import Profile from pyconde.celery import app @ap...
from contextlib import closing from django.core import mail from django.template.loader import render_to_string from django.conf import settings from django.contrib.auth.models import User from pyconde.sponsorship.models import JobOffer from pyconde.accounts.models import Profile from pyconde.celery import app @ap...
Add comment on mail connection
Add comment on mail connection
Python
bsd-3-clause
EuroPython/djep,pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,pysv/djep,EuroPython/djep,pysv/djep
916c4235f4e05d943ce26993e0db0db35993b4e4
blinkylib/patterns/gradient.py
blinkylib/patterns/gradient.py
import blinkypattern import blinkylib.blinkycolor class Gradient(blinkypattern.BlinkyPattern): def __init__(self, blinkytape, start_color, end_color): super(Gradient, self).__init__(blinkytape) self._start_color = start_color self._end_color = end_color def setup(self): super(G...
import blinkypattern import blinkylib.blinkycolor class Gradient(blinkypattern.BlinkyPattern): def __init__(self, blinkytape, start_color, end_color): super(Gradient, self).__init__(blinkytape) self._pixels = self._make_rgb_gradient(start_color, end_color) def setup(self): super(Gradie...
Refactor Gradient to clean up loops and redundancy
Refactor Gradient to clean up loops and redundancy
Python
mit
jonspeicher/blinkyfun
1093601daf8d42f0e3745788e51c1b843d29f2d7
git-keeper-robot/gkeeprobot/keywords/ServerSetupKeywords.py
git-keeper-robot/gkeeprobot/keywords/ServerSetupKeywords.py
# Copyright 2018 Nathan Sommer and Ben Coleman # # 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 3 of the License, or # (at your option) any later version. # # This program is dis...
# Copyright 2018 Nathan Sommer and Ben Coleman # # 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 3 of the License, or # (at your option) any later version. # # This program is dis...
Add command to stop gkeepd
Add command to stop gkeepd
Python
agpl-3.0
git-keeper/git-keeper,git-keeper/git-keeper
17206b44148f490b865561d191f88e85b6181613
back_office/tests_models.py
back_office/tests_models.py
from decimal import Decimal from django.db import IntegrityError from django.test import TestCase from .models import ClassType class ClassTypeClassTypeTestCases(TestCase): """ Testing Class Type model """ def setUp(self): self.class_type, created = ClassType.objects.get_or_create(name='Class ...
from decimal import Decimal from django.db import IntegrityError from django.test import TestCase from .models import ClassType class ClassTypeTestCases(TestCase): """ Testing Class Type model """ def setUp(self): self.class_type, created = ClassType.objects.get_or_create(name='Class Type...
Fix the Class Type Test Cases class name, and enhance the create new
Fix the Class Type Test Cases class name, and enhance the create new
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
3cd9fc540e9989c1842b38d35f9e01bd269a5957
pib/stack.py
pib/stack.py
"""The Pibstack.yaml parsing code.""" import yaml class StackConfig(object): """The configuration for the stack.""" def __init__(self, path_to_repo): self.services = {} # map service name to config dict self.databases = {} # map database name to config dict self.path_to_repo = pat...
"""The Pibstack.yaml parsing code.""" import yaml from .schema import validate class StackConfig(object): """The configuration for the stack.""" def __init__(self, path_to_repo): self.services = {} # map service name to config dict self.databases = {} # map database name to config dict ...
Validate the schema when loading it.
Validate the schema when loading it.
Python
apache-2.0
datawire/pib
f659b022a942acdeef8adf75d32f1e77ee292b88
apps/domain/src/main/core/manager/request_manager.py
apps/domain/src/main/core/manager/request_manager.py
from typing import Union from typing import List from datetime import datetime from .database_manager import DatabaseManager from ..database.requests.request import Request from .role_manager import RoleManager from ..exceptions import RequestError class RequestManager(DatabaseManager): schema = Request de...
from typing import Union from typing import List from datetime import datetime from .database_manager import DatabaseManager from ..database.requests.request import Request from .role_manager import RoleManager from ..exceptions import RequestError from syft.core.node.domain.service import RequestStatus from syft.core...
Update create_request method / Create status method
Update create_request method / Create status method
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
e4ef3df9401bde3c2087a7659a54246de8ec95c6
src/api/urls.py
src/api/urls.py
from rest_framework.routers import SimpleRouter # from bingo_server.api import views as bingo_server_views router = SimpleRouter() router.register('games', bingo_server_views.GameViewSet) urlpatterns = router.urls
from rest_framework.routers import DefaultRouter # from bingo_server.api import views as bingo_server_views router = DefaultRouter() router.register('games', bingo_server_views.GameViewSet) urlpatterns = router.urls
Add root view to API
Add root view to API
Python
mit
steakholders-tm/bingo-server
b59fead0687dd3dbacae703cc1ea0c49305c44eb
shcol/cli.py
shcol/cli.py
from __future__ import print_function import argparse import shcol __all__ = ['main'] def main(cmd_args): parser = argparse.ArgumentParser( description='Generate columnized output for given string items.' ) parser.add_argument('items', nargs='+', help='an item to columnize') parser.add_argume...
from __future__ import print_function import argparse import shcol __all__ = ['main'] def main(cmd_args): parser = argparse.ArgumentParser( description='Generate columnized output for given string items.', version='shcol {}'.format(shcol.__version__) ) parser.add_argument('items', nargs='...
Add command-line option for program version.
Add command-line option for program version.
Python
bsd-2-clause
seblin/shcol
f0c9acaedd9cc36d91758f383a4c703866cde4c7
idavoll/error.py
idavoll/error.py
# Copyright (c) 2003-2008 Ralph Meijer # See LICENSE for details. class Error(Exception): msg = '' def __str__(self): return self.msg class NodeNotFound(Error): pass class NodeExists(Error): pass class NotSubscribed(Error): """ Entity is not subscribed to this node. """ class S...
# Copyright (c) 2003-2008 Ralph Meijer # See LICENSE for details. class Error(Exception): msg = '' def __str__(self): return self.msg class NodeNotFound(Error): pass class NodeExists(Error): pass class NotSubscribed(Error): """ Entity is not subscribed to this node. """ cla...
Adjust spacing to match Twisted's.
Adjust spacing to match Twisted's. --HG-- extra : convert_revision : svn%3Ae60b0d31-0b1b-0410-851a-a02d0c527677/trunk%40258
Python
mit
ralphm/idavoll
50d9601ea0fa35a9d5d831353f5a17b33dc7d8bf
panoptes_client/subject_set.py
panoptes_client/subject_set.py
from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.subject import Subject class SubjectSet(PanoptesObject): _api_slug = 'subject_sets' _link_slug = 'subject_sets' _edit_attributes = ( 'display_name', { 'links': ( 'project', ...
from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.subject import Subject class SubjectSet(PanoptesObject): _api_slug = 'subject_sets' _link_slug = 'subject_sets' _edit_attributes = ( 'display_name', { 'links': ( 'project', ...
Revert "Don't try to save SubjectSet.links.project on exiting objects"
Revert "Don't try to save SubjectSet.links.project on exiting objects" This reverts commit b9a107b45cf2569f9effa1c8836a65255f2f3e64. Superseded by 7d2fecab46f0ede85c00fba8335a8dd74fe16489
Python
apache-2.0
zooniverse/panoptes-python-client
18a074eac431ba4a556cccb4ebf00aa43647631d
SublimePlumbSend.py
SublimePlumbSend.py
import sublime, sublime_plugin import os from SublimePlumb.Mouse import MouseCommand class SublimePlumbSend(MouseCommand): """ Sends the current selected text to the plumbing """ def run(self, edit): file_name = self.view.file_name() message = { "data": self.view.substr(self.selecti...
import sublime, sublime_plugin import os from SublimePlumb.Mouse import MouseCommand class SublimePlumbSend(MouseCommand): """ Sends the current selected text to the plumbing """ def run(self, edit): file_name = self.view.file_name() message = { "data": self.view.substr(self.selecti...
Move selection clearing to before running the action
Move selection clearing to before running the action This allows actions like "jump" to modify the selection
Python
mit
lionicsheriff/SublimeAcmePlumbing
709b9e57d8ea664715fd9bb89729f99324c3e0c2
libs/utils.py
libs/utils.py
from django.core.cache import cache #get the cache key for storage def cache_get_key(*args, **kwargs): import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.append(str(key)...
from django.core.cache import cache def cache_get_key(*args, **kwargs): """Get the cache key for storage""" import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): if key == "clear_cache": continue serialise.appen...
Delete cache first before setting new value
Delete cache first before setting new value
Python
mit
daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban
6b49f7b1948ab94631c79304c91f8d5590d03e40
addons/project/models/project_config_settings.py
addons/project/models/project_config_settings.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProjectConfiguration(models.TransientModel): _name = 'project.config.settings' _inherit = 'res.config.settings' company_id = fields.Many2one('res.company', string...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProjectConfiguration(models.TransientModel): _name = 'project.config.settings' _inherit = 'res.config.settings' company_id = fields.Many2one('res.company', string...
Enable `Timesheets` option if `Time Billing` is enabled
[IMP] project: Enable `Timesheets` option if `Time Billing` is enabled
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
ac209811feb25dfe9b5eac8b1488b42a8b5d73ba
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image)...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image)...
Update SQL data migration to exclude NULL and blank image values.
Update SQL data migration to exclude NULL and blank image values.
Python
bsd-3-clause
mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune,mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune
3761217b9d835f862418d580dcf1342734befe45
system.py
system.py
from enum import IntFlag class SystemFlag(IntFlag): controller = 1 movement = 2 graphics = 4 collision = 8 logic = 16 state = 32
from enum import IntFlag class SystemFlag(IntFlag): controller = 1 movement = 2 graphics = 4 collision = 8 logic = 16 state = 32 blood = 64
Fix flags bug hasattr returns True if the attribute is None
Fix flags bug hasattr returns True if the attribute is None Use forward references for type hinting in entity
Python
agpl-3.0
joetsoi/moonstone,joetsoi/moonstone
4e2f64164b09c481a56920c1b98dd2a38ac02338
scripts/process_realtime_data.py
scripts/process_realtime_data.py
import django django.setup() from busshaming.data_processing import process_realtime_dumps if __name__ == '__main__': process_realtime_dumps.process_next(10)
import django #import cProfile django.setup() from busshaming.data_processing import process_realtime_dumps if __name__ == '__main__': #cProfile.run('process_realtime_dumps.process_next(10)', filename='output.txt') process_realtime_dumps.process_next(10)
Add profiling code (commented) for profiling the realtime processing.
Add profiling code (commented) for profiling the realtime processing.
Python
mit
katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming
50f8efd7bcbf032fd0295c460b98640d0bf6c1ed
smithers/smithers/conf/server.py
smithers/smithers/conf/server.py
from os import getenv GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb' STATSD_HOST = 'graphite1.private.phx1.mozilla.com' STATSD_PORT = 8125 STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV')) COUNTRY_MIN_SHARE = 500
from os import getenv GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb' STATSD_HOST = getenv('STATSD_HOST', 'graphite1.private.phx1.mozilla.com') STATSD_PORT = 8125 STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV')) COUNTRY_MIN_SHARE = 500
Make statsd host configurable via env.
Make statsd host configurable via env.
Python
mpl-2.0
mozilla/mrburns,mozilla/mrburns,mozilla/mrburns
ea046e8996c3bbad95578ef3209b62972d88e720
opps/images/widgets.py
opps/images/widgets.py
from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) return rende...
from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" _height = "" _width = "" if value: _value = "{0}{1}".format(settin...
Add _height/_width on widget MultipleUpload
Add _height/_width on widget MultipleUpload
Python
mit
jeanmask/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps
a783c1739a4e6629f428904901d674dedca971f9
l10n_ch_payment_slip/__manifest__.py
l10n_ch_payment_slip/__manifest__.py
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - ISR inpayment slip (PVR/BVR/ESR)', 'summary': 'Print inpayment slip from your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localiza...
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - ISR inpayment slip (PVR/BVR/ESR)', 'summary': 'Print inpayment slip from your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localiza...
Fix dependency to remove std print isr button
Fix dependency to remove std print isr button
Python
agpl-3.0
brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland
e0f102d9af8b13da65736eb6dd185de64d3dbafb
susumutakuan.py
susumutakuan.py
import discord import asyncio import os import signal import sys #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrupt sys.exit('Sh...
import discord import asyncio import os import signal import sys import subprocess #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrup...
Add DM support, and first start at self-update
Add DM support, and first start at self-update
Python
mit
gryffon/SusumuTakuan,gryffon/SusumuTakuan
b990ce64de70f9aec3bc4480b1a7714aa5701a45
aiohttp/__init__.py
aiohttp/__init__.py
# This relies on each of the submodules having an __all__ variable. __version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .er...
# This relies on each of the submodules having an __all__ variable. __version__ = '0.22.0a0' import multidict # noqa from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa from .client import * # noqa from .client_reqrep import * # noqa from .er...
Add FileSender to top level
Add FileSender to top level
Python
apache-2.0
KeepSafe/aiohttp,jettify/aiohttp,pfreixes/aiohttp,z2v/aiohttp,panda73111/aiohttp,rutsky/aiohttp,mind1master/aiohttp,singulared/aiohttp,z2v/aiohttp,juliatem/aiohttp,KeepSafe/aiohttp,Eyepea/aiohttp,arthurdarcet/aiohttp,jettify/aiohttp,moden-py/aiohttp,arthurdarcet/aiohttp,alex-eri/aiohttp-1,KeepSafe/aiohttp,panda73111/ai...
122ba850fb9d7c9ca51d66714dd38cb2187134f3
Lib/setup.py
Lib/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpo...
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate...
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Python
bsd-3-clause
josephcslater/scipy,rmcgibbo/scipy,ndchorley/scipy,lukauskas/scipy,vberaudi/scipy,dch312/scipy,gfyoung/scipy,andyfaff/scipy,chatcannon/scipy,WarrenWeckesser/scipy,mtrbean/scipy,argriffing/scipy,nvoron23/scipy,WillieMaddox/scipy,aarchiba/scipy,anntzer/scipy,lhilt/scipy,nonhermitian/scipy,teoliphant/scipy,minhlongdo/scip...
a6526ada6991d689d5351643c67b57805be59f16
python_recipes/multiprocessing_keyboard_interrupt.py
python_recipes/multiprocessing_keyboard_interrupt.py
import signal import time import multiprocessing def handle_KeyboardInterrupt(): signal.signal(signal.SIGINT, signal.SIG_IGN) def doSomething(number): time.sleep(1) print "received {0}".format(number) class Worker(object): def __init__(self, poolSize): self.pool = multiprocessing.Pool(poolSi...
import signal import time import multiprocessing # See here for detail: # https://noswap.com/blog/python-multiprocessing-keyboardinterrupt def handle_KeyboardInterrupt(): signal.signal(signal.SIGINT, signal.SIG_IGN) def doSomething(number): time.sleep(1) print "received {0}".format(number) class Worker(...
Add the source of this solution
Add the source of this solution
Python
apache-2.0
wangshan/sketch,wangshan/sketch,wangshan/sketch,wangshan/sketch
67ca9f09cd2cfb5e646b9a09b540c5ff88276201
pydirections/models/models.py
pydirections/models/models.py
from schematics.models import Model from schematics.types import StringType class Step(Model): """ Represents an individual step """ html_instructions = StringType() class Leg(Model): """ Represents an individual leg """ start_address = StringType() end_address = StringType() class Route(Model): """ ...
from schematics.models import Model from schematics.types import StringType, DecimalType from schematics.types.compound import ListType class Distance(Model): """ Represents the duration of a leg/step """ value = DecimalType() text = StringType() class Duration(Model): """ Represents the duration of a leg/st...
Add more details to routes
Add more details to routes
Python
apache-2.0
apranav19/pydirections
f32621c2c8ad207e152f10279e36f56970f48026
python/ecep/portal/widgets.py
python/ecep/portal/widgets.py
from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div,...
from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div,...
Set optional class on map widget if class attribute passed
Set optional class on map widget if class attribute passed
Python
mit
smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning
b26dc2f572fdd8f90a8241c3588870603d763d4d
examples/voice_list_webhook.py
examples/voice_list_webhook.py
#!/usr/bin/env python import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird...
#!/usr/bin/env python import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird...
Exit in voice webhook deletion example, if result is empty
Exit in voice webhook deletion example, if result is empty
Python
bsd-2-clause
messagebird/python-rest-api
2c43a04e5027a5f8cc2739ea93ab24057a07838f
tests/common.py
tests/common.py
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This file is part of my GSoC'15 project for Cuckoo Sandbox: # http://www.cuckoosandbox.org # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import os import unittest import subprocess TE...
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This file is part of my GSoC'15 project for Cuckoo Sandbox: # http://www.cuckoosandbox.org # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import os import unittest import platform impor...
Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines
Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines
Python
mit
cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer,cuckoobox/cuckoo,cuckoobox/cuckoo,cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer,cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer
2b63977524d8c00c7cecebf5f055488a447346f1
api.py
api.py
import webapp2 from google.appengine.api import channel from google.appengine.api import users class Channel(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({"token": ""}) return token = channel.create_channel...
import webapp2 from google.appengine.api import channel from google.appengine.api import users class Channel(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: self.response.write({"token": ""}) return token = channel.create_channel...
Send a message back to client
Send a message back to client
Python
mit
misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample,misterwilliam/gae-channels-sample
315da880c81e02e8c576f51266dffaf19abf8e13
commen5/templatetags/commen5_tags.py
commen5/templatetags/commen5_tags.py
from django import template from django.template.defaulttags import CommentNode register = template.Library() def commen5(parser, token): """ Ignores everything between ``{% commen5 %}`` and ``{% endcommen5 %}``. """ parser.skip_past('endcommen5') return CommentNode() commen5 = register.tag(comme...
from django import template from django.template.defaulttags import CommentNode register = template.Library() @register.tag def commen5(parser, token): """ Ignores everything between ``{% commen5 %}`` and ``{% endcommen5 %}``. """ parser.skip_past('endcommen5') return CommentNode()
Use the sexy, new decorator style syntax.
Use the sexy, new decorator style syntax.
Python
mit
bradmontgomery/django-commen5
ad66203ccf2a76dde790c582e8915399fd4e3148
Code/Python/Kamaelia/Kamaelia/Visualisation/__init__.py
Code/Python/Kamaelia/Kamaelia/Visualisation/__init__.py
#!/usr/bin/env python # Copyright (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General P...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License,...
Change license to Apache 2
Change license to Apache 2
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
1e010e940390ae5b650224363e4acecd816b2611
settings_dev.py
settings_dev.py
import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Settings.tmLanguage" % PLUGIN_NAME) TPL = "{\n\t$0\n}" class NewSettingsCommand(sublime_plugin.WindowComm...
import sublime_plugin from .sublime_lib.path import root_at_packages, get_package_name PLUGIN_NAME = get_package_name() SETTINGS_SYNTAX = ("Packages/%s/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax" % PLUGIN_NAME) TPL = '''\ { "$1": $0 }'''.replace(" " * 4, "\t") class ...
Update syntax path for new settings file command
Update syntax path for new settings file command
Python
mit
SublimeText/AAAPackageDev,SublimeText/AAAPackageDev,SublimeText/PackageDev
cc1e5bc1ae3b91973d9fa30ab8e0f9cb3c147a9e
ddt.py
ddt.py
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): ...
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): ...
Use __name__ from data object to set the test method name, if available.
Use __name__ from data object to set the test method name, if available. Allows to provide user-friendly names for the user instead of the default raw data formatting.
Python
mit
domidimi/ddt,edx/ddt,domidimi/ddt,datadriventests/ddt,edx/ddt,datadriventests/ddt
b419e78a42e7b8f073bc5d9502dffc97c5d627fb
apps/chats/forms.py
apps/chats/forms.py
from django import forms from django.contrib.auth.models import User from chats.models import Chat from profiles.models import FriendGroup class PublicChatForm(forms.ModelForm): """Public-facing Chat form used in the web-interface for users.""" class Meta: fields = ('text',) model = Chat...
from django import forms from django.contrib.auth.models import User from chats.models import Chat from profiles.models import FriendGroup class PublicChatForm(forms.ModelForm): """Public-facing Chat form used in the web-interface for users.""" class Meta: fields = ( 'friend_groups',...
Add friend_groups to the ChatForm
Add friend_groups to the ChatForm
Python
mit
tofumatt/quotes,tofumatt/quotes
db52a15b190db1d560959d5bc382b5aa8d7f5a57
mpld3/test_plots/test_axis.py
mpld3/test_plots/test_axis.py
"""Plot to test ticker.FixedFormatter""" import matplotlib.pyplot as plt import numpy as np import mpld3 def create_plot(): positions, labels = [0, 1, 10], ['A','B','C'] plt.xticks(positions, labels) return plt.gcf() def test_axis(): fig = create_plot() html = mpld3.fig_to_html(fig) plt.clo...
"""Plot to test ticker.FixedFormatter""" import matplotlib.pyplot as plt import numpy as np import mpld3 def create_plot(): positions, labels = [0, 1, 10], ['A','B','C'] plt.yticks(positions) plt.xticks(positions, labels) return plt.gcf() def test_axis(): fig = create_plot() html = mpld3.fi...
Add test for custom tick locations, no labels
Add test for custom tick locations, no labels
Python
bsd-3-clause
kdheepak89/mpld3,kdheepak89/mpld3,aflaxman/mpld3,jakevdp/mpld3,mpld3/mpld3,e-koch/mpld3,jakevdp/mpld3,etgalloway/mpld3,mpld3/mpld3,aflaxman/mpld3,etgalloway/mpld3,e-koch/mpld3
2f860583a99b88324b19b1118b4aea29a28ae90d
polling_stations/apps/data_collection/management/commands/import_portsmouth.py
polling_stations/apps/data_collection/management/commands/import_portsmouth.py
from django.contrib.gis.geos import Point from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "E06000044" addresses_name = "local.2018-05-03/Version 1/Democracy_Club__03May2018.tsv" stations_name = "local.2018-0...
from django.contrib.gis.geos import Point from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "E06000044" addresses_name = ( "local.2019-05-02/Version 1/Democracy_Club__02May2019Portsmouth.tsv" ) sta...
Add import script for Portsmouth
Add import script for Portsmouth Closes #1502
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
61398045cb6bb5a0849fd203ebbe85bfa305ea60
favicon/templatetags/favtags.py
favicon/templatetags/favtags.py
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} ""...
from django import template from django.utils.safestring import mark_safe from favicon.models import Favicon, config register = template.Library() @register.simple_tag(takes_context=True) def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} ""...
Mark comment as safe. Otherwise it is displayed.
Mark comment as safe. Otherwise it is displayed.
Python
mit
arteria/django-favicon-plus
b858b2640b8e509c1262644eda02afb05d90ff18
project/slacksync/management/commands/sync_slack_users.py
project/slacksync/management/commands/sync_slack_users.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from slacksync.membersync import SlackMemberSync from slacksync.utils import api_configured class Command(BaseCommand): help = 'Make sure all members are in Slack and optionally kick non-members' def add_arguments(self,...
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from slacksync.membersync import SlackMemberSync from slacksync.utils import api_configured class Command(BaseCommand): help = 'Make sure all members are in Slack and optionally kick non-members' def add_arguments(self,...
Fix autoremove in wrong place
Fix autoremove in wrong place
Python
mit
HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
7c13c15c3c1791a7ed545db562fb01e890658bdd
shared/management/__init__.py
shared/management/__init__.py
from django.db.models.signals import post_syncdb from django.conf import settings from django.core import management import os import re FIXTURE_RE = re.compile(r'^[^.]*.json$') def load_data(sender, **kwargs): """ Loads fixture data after loading the last installed app """ if kwargs['app'].__name__ ...
from django.db.models.signals import post_syncdb from django.conf import settings from django.core import management import os import re FIXTURE_RE = re.compile(r'^[^.]*.json$') def load_data(sender, **kwargs): """ Loads fixture data after loading the last installed app """ if kwargs['app'].__name__...
Update syncdb to also regenerate the index.
Update syncdb to also regenerate the index.
Python
mit
Saevon/webdnd,Saevon/webdnd,Saevon/webdnd
c5e265143540f29a3bb97e8413b1bb3cffbd35c4
push/utils.py
push/utils.py
import os import random def get_random_word(config): file_size = os.path.getsize(config.paths.wordlist) word = "" with open(config.paths.wordlist, "r") as wordlist: while not word.isalpha() or not word.islower() or len(word) < 5: position = random.randint(1, file_size) wor...
import hashlib import os import random def get_random_word(config): file_size = os.path.getsize(config.paths.wordlist) word = "" with open(config.paths.wordlist, "r") as wordlist: while not word.isalpha() or not word.islower() or len(word) < 5: position = random.randint(1, file_size) ...
Make shuffle handle the host list size changing.
Make shuffle handle the host list size changing.
Python
bsd-3-clause
reddit/push
5f6e525f11b12de98dfadfc721176caa193541e3
slackclient/_slackrequest.py
slackclient/_slackrequest.py
import requests class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} return requests.post( 'https://{0}/api/{1}'.format(domain, request), data=dict(post_data, token=token), )
import json import requests class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): post_data = post_data or {} for k, v in post_data.items(): if not isinstance(v, (str, unicode)): post_data[k] = json.dumps(v) ...
Add support for nested structure, e.g. attachments.
Add support for nested structure, e.g. attachments. > The optional attachments argument should contain a JSON-encoded array of > attachments. > > https://api.slack.com/methods/chat.postMessage This enables simpler calls like this: sc.api_call('chat.postMessage', {'attachments': [{'title': 'hello'}]})
Python
mit
slackapi/python-slackclient,slackapi/python-slackclient,slackhq/python-slackclient,slackapi/python-slackclient
0d3737aa2d9ecc435bc110cb6c0045d815b57cad
pygelf/tls.py
pygelf/tls.py
from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, cert=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) self.cert = cert def makeSocket(self, timeout=1): ...
from __future__ import print_function from pygelf.tcp import GelfTcpHandler import ssl import socket import sys class GelfTlsHandler(GelfTcpHandler): def __init__(self, validate=False, ca_certs=None, **kwargs): super(GelfTlsHandler, self).__init__(**kwargs) if validate and ca_certs is None: ...
Add parameter 'validate' to TLS handler
Add parameter 'validate' to TLS handler
Python
mit
keeprocking/pygelf,keeprocking/pygelf
70672da6b94ae0f272bd875e4aede28fab7aeb6f
pyluos/io/ws.py
pyluos/io/ws.py
import os import socket import websocket from . import IOHandler def resolve_hostname(hostname, port): # We do our own mDNS resolution # to enforce we only search for IPV4 address # and avoid a 5s timeout in the websocket on the ESP # See https://github.com/esp8266/Arduino/issues/2110 addrinfo =...
import os import socket import websocket from . import IOHandler def resolve_hostname(hostname, port): # We do our own mDNS resolution # to enforce we only search for IPV4 address # and avoid a 5s timeout in the websocket on the ESP # See https://github.com/esp8266/Arduino/issues/2110 addrinfo =...
Add \r at the end of Web socket
Add \r at the end of Web socket
Python
mit
pollen/pyrobus
ab2b3bda76a39e34c0d4a172d3ede7ed9e77b774
base/ajax.py
base/ajax.py
import json from django.contrib.auth import get_user_model from dajaxice.decorators import dajaxice_register @dajaxice_register(method="GET") def getuser(request, query): User = get_user_model() qs = User.objects.filter(username__icontains=query) |\ User.objects.filter(first_name__icontains=query) |\...
import json from django.contrib.auth import get_user_model from dajaxice.decorators import dajaxice_register @dajaxice_register(method="GET") def getuser(request, query): User = get_user_model() qs = User.objects.filter(username__icontains=query) |\ User.objects.filter(first_name__icontains=query) |\...
Add filters to message recipient autocomplete.
Add filters to message recipient autocomplete.
Python
bsd-3-clause
ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio
582bb1f7a2de8756bcb72d79d61aab84c09ef503
beetle_sass/__init__.py
beetle_sass/__init__.py
import sass def render_sass(raw_content): return sass.compile(string=raw_content) def register(context, plugin_config): sass_extensions = ['sass', 'scss'] context.content_renderer.add_renderer(sass_extensions, render_sass)
from os import path import sass def render_sass(raw_content): return sass.compile(string=raw_content) def includer_handler(content, suggested_path): content = render_sass(content.decode('utf-8')) file_path, _ = path.splitext(suggested_path) return '{}.css'.format(file_path), content.encode('utf-8')...
Add includer handler as well as content renderer
Add includer handler as well as content renderer
Python
mit
Tenzer/beetle-sass
1d09a1c92f813af26abfea60846345b3757e356a
blog/views.py
blog/views.py
import os from django.views.generic import TemplateView class ArticleView(TemplateView): def get_template_names(self): article_name = self.kwargs.get('article_name', 'notfound') return [os.path.join('blog', 'blog', article_name, 'index.html')]
import os from django.views.generic import TemplateView from django.template.base import TemplateDoesNotExist from django.http import Http404 from django.template.loader import get_template class ArticleView(TemplateView): def get_template_names(self): article_name = self.kwargs.get('article_name', 'not...
Make sure that missing blog pages don't 500
Make sure that missing blog pages don't 500
Python
mit
stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb
b8eb16ac78c081711236d73e5c099ed734f897ac
pyscriptic/refs.py
pyscriptic/refs.py
from pyscriptic.containers import CONTAINERS from pyscriptic.storage import STORAGE_LOCATIONS class Reference(object): """ Contains the information to either create or link a given container to a reference through a protocol via an intermediate name. Attributes ---------- container_id : str ...
from pyscriptic.containers import CONTAINERS, list_containers from pyscriptic.storage import STORAGE_LOCATIONS _AVAILABLE_CONTAINERS_IDS = None def _available_container_ids(): """ This helper function fetchs a list of all containers available to the currently active organization. It then stores the conta...
Check container IDs when making new References
Check container IDs when making new References
Python
bsd-2-clause
naderm/pytranscriptic,naderm/pytranscriptic
1a5c1ea0815d30048d7dbce56adf2503b9c82c28
moksha/widgets/container/tests/test_container.py
moksha/widgets/container/tests/test_container.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...
Update our container test case
Update our container test case
Python
apache-2.0
ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,ralphbean/moksha,ralphbean/moksha,lmacken/moksha,pombredanne/moksha
35ffe6bb97a30970d4bc3c265b6337712669ee09
githubsetupircnotifications.py
githubsetupircnotifications.py
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import argparse import getpass import sys import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username') parser.add_argument('--password') parser.add_argumen...
""" github-setup-irc-notifications - Configure all repositories in an organization with irc notifications """ import argparse import getpass import sys import github3 def error(message): print(message) sys.exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument('--username') ...
Add error function to remove duplicate code
Add error function to remove duplicate code
Python
mit
kragniz/github-setup-irc-notifications
859a23790968c84cdbc4fa7467957a3a1ed1e069
greatbigcrane/project/forms.py
greatbigcrane/project/forms.py
""" Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm 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 agre...
""" Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm 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 agre...
Add a name for the recipe section
Add a name for the recipe section
Python
apache-2.0
pnomolos/greatbigcrane,pnomolos/greatbigcrane
61cf5a4ab4d7b9e0cb95925acc633aa7cb156d59
taggit/models.py
taggit/models.py
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.generic import GenericForeignKey from django.db import models from django.template.defaultfilters import slugify class Tag(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def _...
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.generic import GenericForeignKey from django.db import models from django.template.defaultfilters import slugify class Tag(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, max...
Make slug unique and fix the max_length.
Make slug unique and fix the max_length.
Python
bsd-3-clause
izquierdo/django-taggit,theatlantic/django-taggit2,doselect/django-taggit,gem/django-taggit,theatlantic/django-taggit,Maplecroft/django-taggit,benjaminrigaud/django-taggit,kminkov/django-taggit,twig/django-taggit,cimani/django-taggit,decibyte/django-taggit,IRI-Research/django-taggit,eugena/django-taggit,theatlantic/dja...
b3757884bdaa6e488d54ee51f943dbb3578ea469
stores/forms.py
stores/forms.py
from django import forms from django.db.models import get_model from django.utils.translation import ugettext as _ StoreAddress = get_model('stores', 'StoreAddress') class StoreSearchForm(forms.Form): STATE_CHOICES = ( (_('VIC'), _('Victoria')), (_('NSW'), _('New South Wales')), (_('SA')...
from django import forms from django.db.models import get_model from django.utils.translation import ugettext as _ StoreAddress = get_model('stores', 'StoreAddress') class StoreSearchForm(forms.Form): STATE_CHOICES = ( (_('VIC'), _('Victoria')), (_('NSW'), _('New South Wales')), (_('SA')...
Remove limit for search field
Remove limit for search field
Python
bsd-3-clause
django-oscar/django-oscar-stores,django-oscar/django-oscar-stores,django-oscar/django-oscar-stores
fe50886a42bf7fa5e3217134e1f7a732960ab2d9
nbgrader/tests/apps/test_nbgrader_generate_config.py
nbgrader/tests/apps/test_nbgrader_generate_config.py
import os from .. import run_nbgrader from .base import BaseTestApp class TestNbGraderGenerateConfig(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["generate_config", "--help-all"]) def test_generate_config(self): """Is the config file pr...
import os from .. import run_nbgrader from .base import BaseTestApp class TestNbGraderGenerateConfig(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["generate_config", "--help-all"]) def test_generate_config(self): """Is the config file pr...
Add assertion for issue gh-1089
Add assertion for issue gh-1089
Python
bsd-3-clause
jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader
d8a861c47df6b41c27f2ec43474766284ba728af
bot/logger/message_sender/reusable/limiter/group.py
bot/logger/message_sender/reusable/limiter/group.py
from bot.logger.message_sender.message_builder import MessageBuilder from bot.logger.message_sender.reusable.limiter import ReusableMessageLimiter class ReusableMessageLimiterGroup(ReusableMessageLimiter): def __init__(self, *limiters: ReusableMessageLimiter): self.limiters = limiters def should_issu...
from bot.logger.message_sender.message_builder import MessageBuilder from bot.logger.message_sender.reusable.limiter import ReusableMessageLimiter class ReusableMessageLimiterGroup(ReusableMessageLimiter): def __init__(self, *limiters: ReusableMessageLimiter): self.limiters = limiters def should_issu...
Make ReusableMessageGroup broadcast the notify_about_to_send_message to all limiters
Make ReusableMessageGroup broadcast the notify_about_to_send_message to all limiters
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
769fa2c0c777ac88702e6b3802de4909c8f8df22
sh_app/forms.py
sh_app/forms.py
from django import forms from django.forms import Textarea from sh_app.models import User, SH_User, League, Suggestion class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password') class SH_UserFor...
from django import forms from django.forms import Textarea from sh_app.models import User, SH_User, League, Suggestion class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password') class SH_UserFor...
Remove isPrivate field on league form
Remove isPrivate field on league form
Python
mit
skill-huddle/skill-huddle,skill-huddle/skill-huddle
6dd52ba31141f28e1f37e32f8c3de6932ed49b4f
make_mozilla/base/tests/assertions.py
make_mozilla/base/tests/assertions.py
from nose.tools import eq_, ok_ from django.core.urlresolvers import resolve, reverse def assert_routing(url, view_function, name = '', kwargs = {}): resolved_route = resolve(url) ok_(resolved_route.func is view_function) if kwargs: eq_(resolved_route.kwargs, kwargs) if name: eq_(revers...
from nose.tools import eq_, ok_ from django.core.urlresolvers import resolve, reverse def assert_routing(url, view_function_or_class, name = '', kwargs = {}): resolved_route = resolve(url) ok_((resolved_route.func is view_function_or_class) or (type(resolved_route.func) is view_function_or_class)) if kwarg...
Allow assert_routing to cope with Feed instances used as route endpoints
Allow assert_routing to cope with Feed instances used as route endpoints
Python
bsd-3-clause
mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org
e6873d3d40d868e743a239c6a74a345c2999541e
dusty_coffin/elasticsearch_custom/edit_spreadsheet.py
dusty_coffin/elasticsearch_custom/edit_spreadsheet.py
import urllib.request from io import BytesIO import pandas as pd import ujson from elasticsearch import Elasticsearch csv = urllib.request.urlopen("https://docs.google.com/spreadsheet/pub?key=0Ahf71UaPpMOSdGl0NnQtSFgyVFpvSmV3R2JobzVmZHc&output=csv").read() bio = BytesIO(csv) csv_pd = pd.DataFrame.from_csv(bio)...
import urllib.request from io import BytesIO import pandas as pd import ujson from elasticsearch import Elasticsearch csv = urllib.request.urlopen("https://docs.google.com/spreadsheet/pub?key=1h1udf_H073YaVlZs0fkYUf9dC6KbEZAhF1veeLExyXo&gid=937170620&output=csv").read() bio = BytesIO(csv) csv_pd = pd.DataFrame...
Edit spreadsheet is now fixed.
Edit spreadsheet is now fixed.
Python
mit
bhillmann/dusty_coffin,bhillmann/dusty_coffin,bhillmann/dusty_coffin,bhillmann/dusty_coffin
8eb0b7fcd6ffb81d6b0fc69cb31c7625550583d7
targetrupypy.py
targetrupypy.py
from pypy.jit.codewriter.policy import JitPolicy from rupypy.main import entry_point def target(driver, args): driver.exe_name = "rupypy-c" return entry_point, None def jitpolicy(driver): return JitPolicy()
from pypy.jit.codewriter.policy import JitPolicy from rupypy.main import entry_point def target(driver, args): driver.exe_name = "./bin/topaz" return entry_point, None def jitpolicy(driver): return JitPolicy()
Move towards a normal bin directory.
Move towards a normal bin directory.
Python
bsd-3-clause
babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,kachick/topaz,kachick/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,kachick/topaz,topazproject/topaz,topazproject/topaz,topazproject/topaz
39561a89ea497776d980d3eda97fc2f75493528f
internal_social_auth/views.py
internal_social_auth/views.py
import logging from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.views.generic.base import View from social_auth.exceptions import AuthFailed from social_auth.views import complete logger = logging.getLogger(__name__) class AuthComplete(View): def get(se...
import logging from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.utils.encoding import force_text from django.views.generic.base import View from social_auth.exceptions import AuthFailed from social_auth.views import complete logger = logging.getLogger(__name_...
Clean up the AuthComplete API a little
Clean up the AuthComplete API a little
Python
bsd-2-clause
incuna/incuna-internal-social-auth
97b000547898d6aa3006f07cf2ef9d8656a67865
conllu/__init__.py
conllu/__init__.py
from __future__ import unicode_literals from conllu.models import TokenList from conllu.parser import parse_token_and_metadata def parse(data, fields=None): return [ TokenList(*parse_token_and_metadata(sentence, fields=fields)) for sentence in data.split("\n\n") if sentence ] def par...
from __future__ import unicode_literals from conllu.models import TokenList from conllu.parser import parse_token_and_metadata def parse(data, fields=None): return [ TokenList(*parse_token_and_metadata(sentence, fields=fields)) for sentence in data.split("\n\n") if sentence ] def _i...
Add incremental parsing versions of parse and parse_tree
Add incremental parsing versions of parse and parse_tree
Python
mit
EmilStenstrom/conllu
9e3a6190b2dcfd7de03ef5c974b400a51219839e
pyof/v0x04/symmetric/hello.py
pyof/v0x04/symmetric/hello.py
"""Defines Hello message.""" # System imports # Third-party imports from pyof.v0x01.symmetric.hello import Hello __all__ = ('Hello',)
"""Defines Hello message.""" # System imports from enum import Enum from pyof.foundation.base import GenericMessage, GenericStruct from pyof.foundation.basic_types import BinaryData, FixedTypeList, UBInt16 from pyof.v0x04.common.header import Header, Type # Third-party imports __all__ = ('Hello', 'HelloElemHeader...
Add Hello class and related classes for v0x04
Add Hello class and related classes for v0x04 Fix #302 Fix #303
Python
mit
cemsbr/python-openflow,kytos/python-openflow