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 |
|---|---|---|---|---|---|---|---|---|---|
413bebe630c29764dcbf17b114662427edfdac3c | pydot/errors.py | pydot/errors.py | class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
try:
self.err_code = js... | class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
self.err_code = json_response.get('... | Refactor error data extraction from JSON | Refactor error data extraction from JSON
| Python | mit | joshgeller/PyPardot |
13e4a0ef064460ffa90bc150dc04b9a1fff26a1c | blanc_basic_news/news/templatetags/news_tags.py | blanc_basic_news/news/templatetags/news_tags.py | from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
| from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('da... | Add a template tag to get the latest news posts. | Add a template tag to get the latest news posts.
| Python | bsd-3-clause | blancltd/blanc-basic-news |
649f2aa5a23541a4c57372eeb34a337d84dd0f86 | timed/tests/test_serializers.py | timed/tests/test_serializers.py | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key... | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
resour... | Remove obsolete pk_key in test | Remove obsolete pk_key in test
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend |
2b2401fcbefc5c385f5e84057a76a4fcdbed0030 | serfnode/handler/handler.py | serfnode/handler/handler.py | #!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
... | #!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
... | Set 'no_role' if role is not given | Set 'no_role' if role is not given
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode |
62a3ab3409dbc1dd22896fb7c3b5376c1b6432e2 | AcmePlumbingSend.py | AcmePlumbingSend.py | import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(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.selection_at_cursor... | import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(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.selection_at_cursor... | Remove artefact from earlier left mouse button selection | Remove artefact from earlier left mouse button selection
You used to be able to select with the left mouse button and then right click.
You can't now.
| Python | mit | lionicsheriff/SublimeAcmePlumbing |
ed2c56cd044f905c4325f42b4e9cf7a5df913bfd | books/models.py | books/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = f... | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = f... | Set created time with default callback | Set created time with default callback
auto_now is evil, as any editing and overriding is
almost completely impossible (e.g. unittesting)
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance |
5bc51f525c702cd43d3d7bc3819d179815c41807 | foliant/backends/pre.py | foliant/backends/pre.py | from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(sel... | from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(sel... | Allow to override the top-level slug. | Allow to override the top-level slug.
| Python | mit | foliant-docs/foliant |
4e3e1c3e70f5ba60ae9637febe4d95348561dd47 | db/editjsonfile.py | db/editjsonfile.py | #!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.geten... | #!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.geten... | Clean up input and output. | Clean up input and output. | Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash |
c37e3fe832ef3f584a60783a474b31f9f91e3735 | github_webhook/test_webhook.py | github_webhook/test_webhook.py | """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
... | """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
... | Fix mock import for Python 3 | Fix mock import for Python 3
| Python | apache-2.0 | fophillips/python-github-webhook |
8adbb5c9cc089663bcdc62496415d666c9f818a3 | service/inchi.py | service/inchi.py | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code =... | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.st... | Add log statement if REST API can't be accessed | Add log statement if REST API can't be accessed
| Python | bsd-3-clause | OpenChemistry/mongochemweb,OpenChemistry/mongochemweb |
94bcaa24f0dc1c0750023770574e26bb41183c6a | hangupsbot/plugins/namelock.py | hangupsbot/plugins/namelock.py | """Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatna... | """Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatna... | Make hangout rename itself after setchatname is called | Make hangout rename itself after setchatname is called
| Python | agpl-3.0 | makiftasova/hangoutsbot,cd334/hangoutsbot,jhonnyam123/hangoutsbot |
89b7b7f7fe1ec50f1d0bdfba7581f76326efe717 | dacapo_analyzer.py | dacapo_analyzer.py | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
... | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
... | Use only msecs of dacapo output. | [client] Use only msecs of dacapo output.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy |
f5cc0d9327f35d818b10e200404c849a5527aa50 | indra/databases/hgnc_client.py | indra/databases/hgnc_client.py | import urllib2
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
... | import urllib2
from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/... | Add caching to HGNC client | Add caching to HGNC client
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,jmuhlich/indra... |
3b3da9ffc5f8247020d2c6c58f83d95e8dbf8dd6 | serrano/cors.py | serrano/cors.py | from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_COR... | from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_COR... | Set Access-Control-Allow-Credentials for all responses | Set Access-Control-Allow-Credentials for all responses
In order to inform the browser to set the Cookie header on requests, this
header must be set otherwise the session is reset on every request.
| Python | bsd-2-clause | chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night |
77a965f27f75a8a5268ad95538d6625cecb44bfa | south/models.py | south/models.py | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migrat... | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app... | Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
| Python | apache-2.0 | matthiask/south,matthiask/south |
3ff91625fc99e279078547220fb4358d647c828a | deflect/widgets.py | deflect/widgets.py | from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard `... | from __future__ import unicode_literals
from itertools import chain
from django.contrib.admin.widgets import AdminTextInputWidget
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(AdminTextInputWidget):
"""
... | Change the superclass for admin DataList widget | Change the superclass for admin DataList widget
This adds an additional class so it displays the same as other
text fields in the admin interface.
| Python | bsd-3-clause | jbittel/django-deflect |
87cfac55b14083fdb8e346b9db1a95bb0f63881a | connect/config/factories.py | connect/config/factories.py | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class S... | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class S... | Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
| Python | bsd-3-clause | nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect |
78ba73998168d8e723d1c62942b19dabfd9ab229 | src/constants.py | src/constants.py | #!/usr/bin/env python
SIMULATION_TIME_IN_SECONDS = 40
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
TRAJECTORY_TYPE = 'linear'
| #!/usr/bin/env python
TRAJECTORY_TYPE = 'circular'
if TRAJECTORY_TYPE == 'linear':
SIMULATION_TIME_IN_SECONDS = 40
elif TRAJECTORY_TYPE == 'circular':
SIMULATION_TIME_IN_SECONDS = 120
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
| Define simulation time for linear and circular trajectories | Define simulation time for linear and circular trajectories
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking |
b3413818bf651c13cef047132813fb26a185cd33 | indra/tests/test_reading_files.py | indra/tests/test_reading_files.py | from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This... | from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.... | Fix the reading files test. | Fix the reading files test.
| Python | bsd-2-clause | johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy |
fd951edbef26dcab2a4b89036811520b22e77fcf | marry-fuck-kill/main.py | marry-fuck-kill/main.py | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | Remove TODO -- handlers have been cleaned up. | Remove TODO -- handlers have been cleaned up.
| Python | apache-2.0 | hjfreyer/marry-fuck-kill,hjfreyer/marry-fuck-kill |
366937921cfb13fd83fb5964d0373be48e3c8564 | cmsplugin_plain_text/models.py | cmsplugin_plain_text/models.py | # -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
| # -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
| Add `__str__` method to support Python 3 | Add `__str__` method to support Python 3
| Python | bsd-3-clause | chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text |
d15bfddd59f0009852ff5f69a665c8858a5cdd40 | __init__.py | __init__.py | r"""
============================================
msm - Markov state models (:mod:`pyemma.msm`)
============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
"""
from . import analysis
from . import estimation
from . import generation
from . ... | r"""
=============================================
msm - Markov state models (:mod:`pyemma.msm`)
=============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
its
msm
tpt
cktest
hmsm
"""
from . import analysis
from . impor... | Add autodoc for msm user-API | [doc] Add autodoc for msm user-API
| Python | bsd-3-clause | clonker/ci-tests |
08c2f9fe24b6ce7697bf725e70855e8d6861c370 | pandas/__init__.py | pandas/__init__.py | """This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except Impor... | """This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except Impor... | Use only absolute imports for python 3 | Use only absolute imports for python 3
| Python | apache-2.0 | Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco |
8e900343312fa644a21e5b209b83431ced3c3020 | inet/constants.py | inet/constants.py | import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ.get("OPS_KEY")
OPS_SECRET = os.environ.get("OPS_SECRET")
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['T... | import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ["OPS_KEY"]
OPS_SECRET = os.environ["OPS_SECRET"]
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_A... | Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised | Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised
| Python | mit | nestauk/inet |
08247c2d4cb3cf1879b568697d7888728ebb1c3b | parse_rest/role.py | parse_rest/role.py | # 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 distributed in the hope that it will ... | # 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 distributed in the hope that it will ... | Handle adding and removing relations from Roles. | Handle adding and removing relations from Roles.
This adds addRelation and removeRelation capabilities to Role, making it possible to add users to the users column and roles to the roles column in a Role object, for example. This prevents the error of Role not having the attribute addRelation or removeRelation when tr... | Python | mit | alacroix/ParsePy,milesrichardson/ParsePy,milesrichardson/ParsePy,alacroix/ParsePy |
02d67008d0f0bdc205ca9168384c4a951c106a28 | nintendo/common/transport.py | nintendo/common/transport.py |
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self... |
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self... | Add a few functions to Socket class | Add a few functions to Socket class
| Python | mit | Kinnay/NintendoClients |
60d8b38eac3c36bd754f5ed01aae6d3af1918adc | notifications/match_score.py | notifications/match_score.py | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self._event_feed = match.event.id
... | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
sel... | Add district feed to match score notification | Add district feed to match score notification
| Python | mit | phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-b... |
f4c56937caacb4709847d67752f4ff3cba4568f6 | tests/test_it.py | tests/test_it.py | import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck... | import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
... | Remove decorator 'skip_in_ci' from test_files | Remove decorator 'skip_in_ci' from test_files
Because implement stub of capture engine, 'Output slides pdf' test can run in CircleCI
| Python | mit | attakei/deck2pdf-python,attakei/deck2pdf-python,attakei/slide2pdf,attakei/deck2pdf,attakei/slide2pdf,attakei/deck2pdf |
d5b231fbc5dd32ded78e4499a49872487533cda4 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
... | from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecut... | Implement a test specifically for abbreviations | Implement a test specifically for abbreviations
| Python | bsd-3-clause | willingc/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,pjbull/cookiecutter,cguardia/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutt... |
1028afcdc1e8e1027b10fe5254f5fe5b9499eddd | tests/test_void.py | tests/test_void.py | """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_mod... | """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_m... | Fix imports for void tests | Fix imports for void tests
| Python | apache-2.0 | ec-geolink/glharvest,ec-geolink/glharvest,ec-geolink/glharvest |
43fd422599972f9385c9f3f9bc5a9a2e5947e0ea | web/webhooks.py | web/webhooks.py | from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def dispatch(re... | import hashlib
import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, ... | Check HMAC digests in webhook notifications before handling them. | Check HMAC digests in webhook notifications before handling them.
Bump #1
| Python | apache-2.0 | Jucyio/Jucy,Jucyio/Jucy,Jucyio/Jucy |
f9884fc274d2068051edb41f9ad13ad25a7f1c72 | isogram/isogram.py | isogram/isogram.py | from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
| from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's ma... | Add note about str.isalpha() method as an alternative | Add note about str.isalpha() method as an alternative
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
d2c368995e33b375404e3c01f79fdc5a14a48282 | polyaxon/libs/repos/utils.py | polyaxon/libs/repos/utils.py | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_project_code_reference(project, commit=None):
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=c... | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_code_reference(instance, commit=None, external_repo=None):
project = instance.project
repo = project.repo if project.has_code else external_repo
if not repo:
return None
if commit:
... | Extend code references with external repos | Extend code references with external repos
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
db93242b97eb8733192d38c4b0af0377759fd647 | pysal/model/access/__init__.py | pysal/model/access/__init__.py | from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access_log_stream
from access import access
| from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access
| Update import for access changes | [BUG] Update import for access changes
| Python | bsd-3-clause | pysal/pysal,weikang9009/pysal,lanselin/pysal,sjsrey/pysal |
724335a9719174d3aeb745ed2d4c161507a08bd3 | pysparkling/fileio/textfile.py | pysparkling/fileio/textfile.py | from __future__ import absolute_import, unicode_literals
import logging
from io import StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports t... | from __future__ import absolute_import, unicode_literals
import logging
from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. S... | Add fileio.TextFile and use it when reading and writing text files in RDD and Context. | Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
| Python | mit | giserh/pysparkling |
1b33866dd7f140efa035dfd32e0a912dfcf60f35 | utils/kvtable.py | utils/kvtable.py | '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
self.setting = Query()
def get(self, key):
"""Get the value of na... | '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
def get(self, key):
"""Get the value of named setti... | Use upsert to reduce chance of duplicates | Use upsert to reduce chance of duplicates
| Python | mit | randomic/antinub-gregbot |
d7db5b38bd90502575c68d7fd5548cb64cd7447a | services/disqus.py | services/disqus.py | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provide... | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provide... | Reword the permissions for Disqus | Reword the permissions for Disqus
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
02ef2f1cb4e1e0bf3696ea68b73d0d9c3b9c8657 | events/views.py | events/views.py | from datetime import date
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
return render_to_response('events/event_archive_month.html', {'month': month})
| from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
previous = month - timedelta(days=15)
next = month + timedelta(days=45)
return render_to_response('events/event_archive_month.html', {
'month': mont... | Add links to previous and next month | Add links to previous and next month
| Python | agpl-3.0 | vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre |
bf1f62cb7d91458e768ac31c26deb9ff67ff3a1e | rcamp/rcamp/settings/auth.py | rcamp/rcamp/settings/auth.py | AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
| AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
| Change PAM stack back to login | Change PAM stack back to login
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP |
a18f948a6b11522425aace5a591b5f622a5534d3 | payments/forms.py | payments/forms.py | from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
# pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| Disable R0924 check on PlanForm | Disable R0924 check on PlanForm
This check fails on Django 1.4 but not Django 1.5
| Python | mit | crehana/django-stripe-payments,aibon/django-stripe-payments,jawed123/django-stripe-payments,aibon/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,ZeevG/django-stripe-payments,jawed123/django-stripe-payments,grue/django-... |
3ede075c812b116629c5f514596669b16c4784df | fulltext/backends/__json.py | fulltext/backends/__json.py | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
... | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
... | Use format string. Readability. ValueError. | Use format string. Readability. ValueError.
| Python | mit | btimby/fulltext,btimby/fulltext |
b6c8921b7281f24f5e8353cd0542d7ca1d18cf37 | pymemcache/test/test_serde.py | pymemcache/test/test_serde.py | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
deserialized = python_memcache_dese... | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value... | Use byte strings after serializing with serde | Use byte strings after serializing with serde
The pymemcache client will return a byte string, so we'll do the same to test that the deserializer works as expected.
This currently fails with Python 3.
| Python | apache-2.0 | sontek/pymemcache,ewdurbin/pymemcache,sontek/pymemcache,bwalks/pymemcache,pinterest/pymemcache,pinterest/pymemcache |
6e583085ac056b7df2b29a94cd6743493c151684 | subjectivity_clues/clues.py | subjectivity_clues/clues.py | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_a... | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj'... | Add calculation to the lexicon | Add calculation to the lexicon
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis |
0db4d0f3df3b9541aaf6301c11f83376debb41ff | lib/get_version.py | lib/get_version.py | #!/usr/bin/env python
""" Extracts the version of the khmer project. """
import sys
import pkg_resources
try:
print pkg_resources.get_distribution( # pylint: disable=E1103
'khmer').version
except pkg_resources.DistributionNotFound:
print 'To build the khmer library, the distribution information'
... | import sys
sys.path.insert(0, '../')
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = '../khmer/_version.py'
versioneer.versionfile_build = '../khmer/_version.py'
versioneer.tag_prefix = 'v' # tags are like v1.2.0
versioneer.parentdir_prefix = '..'
print versioneer.get_version()
| Use versioneer for ./lib version | Use versioneer for ./lib version
- Allows the version to be obtained without khmer being installed.
| Python | bsd-3-clause | Winterflower/khmer,kdmurray91/khmer,souravsingh/khmer,souravsingh/khmer,Winterflower/khmer,jas14/khmer,ged-lab/khmer,ged-lab/khmer,Winterflower/khmer,F1000Research/khmer,F1000Research/khmer,jas14/khmer,kdmurray91/khmer,souravsingh/khmer,ged-lab/khmer,kdmurray91/khmer,F1000Research/khmer,jas14/khmer |
e046bbd4027275a94888bd70138000cdb2da67f3 | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | Add a title attribute to the SearchIndex for pages. | Add a title attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can display the title of the result without hitting the database to
actually pull the page.
| Python | bsd-3-clause | batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,bati... |
dcc5c7be6f8463f41e1d1697bdba7fd576382259 | master/rc_force.py | master/rc_force.py | # Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
reason=FixedParameter(name="reason", default=""),
bra... | # Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="rea... | Add ppc64le tarball rc force builder | Add ppc64le tarball rc force builder
| Python | mit | staticfloat/julia-buildbot,staticfloat/julia-buildbot |
f4be8fd80b1aad9babdfbc56dec331af635f5554 | migrations/versions/0165_another_letter_org.py | migrations/versions/0165_another_letter_org.py | """empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
... | """empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
... | Add East Riding of Yorkshire Council to migration | Add East Riding of Yorkshire Council to migration
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
dc0dfd4a763dceef655d62e8364b92a8073b7751 | chrome/chromehost.py | chrome/chromehost.py | #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.rea... | #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.rea... | Change chromhost to use normal sockets | Change chromhost to use normal sockets
| Python | mit | CacheBrowser/cachebrowser,NewBie1993/cachebrowser |
78ca616d611a6c9b8364cf25a21affd80e261ff8 | cutplanner/planner.py | cutplanner/planner.py | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = ... | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = ... | Set up list of needed pieces on init | Set up list of needed pieces on init
| Python | mit | alanc10n/py-cutplanner |
131f0d3a67bc6ba995d1f45dd8c85594d8d8e79c | tests/run_tests.py | tests/run_tests.py | """Python script to run all tests"""
import pytest
if __name__ == '__main__':
pytest.main()
| """Python script to run all tests"""
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
| Allow Jenkins to actually report build failures | Allow Jenkins to actually report build failures
| Python | mit | gatkin/declxml |
2d8ddb4ab59bc7198b637bcc9e51914379ff408b | tests/test_i18n.py | tests/test_i18n.py | import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
humanize.i18n.deactivate()
assert hum... | import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
try:
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секу... | Add i18n test for humanize.ordinal | Add i18n test for humanize.ordinal
| Python | mit | jmoiron/humanize,jmoiron/humanize |
8e26fa46ffdb9442254712b4083a973ab9ce6577 | Python/tangshi.py | Python/tangshi.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rs... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rs... | Print the character without Rhyme if it is not on the Rhyme Dictionary | Print the character without Rhyme if it is not on the Rhyme Dictionary
| Python | apache-2.0 | jmworsley/TangShi |
a8f3491811bb639ebb59f79c55f461ae063b06b8 | api/base/urls.py | api/base/urls.py | from django.conf import settings
from django.conf.urls import include, url
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^$', views.root),
url(r'^nodes/', include('api.nodes.urls', namespace='nodes')),
url(r'^users... | from django.conf import settings
from django.conf.urls import include, url, patterns
# from django.contrib import admin
from django.conf.urls.static import static
from . import views
urlpatterns = [
### API ###
url(r'^v2/', include(patterns('',
url(r'^$', views.root),
url(r'^nodes/', include... | Change API url prefix to 'v2' | Change API url prefix to 'v2'
| Python | apache-2.0 | TomBaxter/osf.io,cwisecarver/osf.io,pattisdr/osf.io,wearpants/osf.io,caseyrygt/osf.io,sbt9uc/osf.io,jmcarp/osf.io,adlius/osf.io,adlius/osf.io,GageGaskins/osf.io,dplorimer/osf,reinaH/osf.io,abought/osf.io,TomHeatwole/osf.io,petermalcolm/osf.io,hmoco/osf.io,pattisdr/osf.io,jeffreyliu3230/osf.io,zachjanicki/osf.io,billyhu... |
fb7754f15a8f0803c5417782e87d6fe153bf6d20 | migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py | migrations/versions/201503061726_573faf4ac644_added_end_date_to_full_text_index_events.py | """Added end_date to full text index events
Revision ID: 573faf4ac644
Revises: 342fa3076650
Create Date: 2015-03-06 17:26:54.718493
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_colum... | """Added end_date to full text index events
Revision ID: 573faf4ac644
Revises: 342fa3076650
Create Date: 2015-03-06 17:26:54.718493
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '573faf4ac644'
down_revision = '342fa3076650'
def upgrade():
op.alter_colum... | Use index name matching the current naming schema | Use index name matching the current naming schema
| Python | mit | OmeGak/indico,mvidalgarcia/indico,pferreir/indico,indico/indico,DirkHoffmann/indico,indico/indico,mic4ael/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,OmeGak/indico,DirkHoffmann/indico,mvidalgarcia/indico,DirkHoffmann/... |
029a159fe3f920d59e0168af72177b343daa4256 | phased/__init__.py | phased/__init__.py | from django.conf import settings
def generate_secret_delimiter():
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter(... | from django.conf import settings
from django.utils.hashcompat import sha_constructor
def generate_secret_delimiter():
return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()
LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
| Make use of Django's hashcompat module. | Make use of Django's hashcompat module. | Python | bsd-3-clause | OmarIthawi/django-phased,mab2k/django-phased,mab2k/django-phased,codysoyland/django-phased,OmarIthawi/django-phased |
c5a7feb3000bb3e234a3b87e8b20262eb9b94dfe | books/models.py | books/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = f... | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = f... | Create new model for debts and loans | Create new model for debts and loans
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance |
39c0dfd7821355c9d2ff2274f4dd6292e959ed87 | pronto/__init__.py | pronto/__init__.py | # coding: utf-8
"""
**pronto**: a Python frontend to ontologies
===========================================
"""
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.f... | # coding: utf-8
"""
**pronto**: a Python frontend to ontologies
===========================================
"""
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = 'martin.larralde@ens-cachan.fr'
try:
... | Remove Parser from __all__ (from pronto import *) | Remove Parser from __all__ (from pronto import *)
| Python | mit | althonos/pronto |
feefc687473b80adf30079e3ca23384459bb1558 | protractor/test.py | protractor/test.py | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | Update to pass live server url as param to protractor | Update to pass live server url as param to protractor
| Python | mit | penguin359/django-protractor,jpulec/django-protractor |
e78dd9bf1b9e1d20b8df34ee3328ee08afd45676 | contrib/migrateticketmodel.py | contrib/migrateticketmodel.py | #!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more... | #!/usr/bin/env python
#
# This script completely migrates a <= 0.8.x Trac environment to use the new
# default ticket model introduced in Trac 0.9.
#
# In particular, this means that the severity field is removed (or rather
# disabled by removing all possible values), and the priority values are
# changed to the more... | Fix missing import in contrib script added in [2630]. | Fix missing import in contrib script added in [2630].
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@2631 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac |
8974dc36e6ea0ab7b5ce3c78e9827d41cf1abcec | appengine_config.py | appengine_config.py | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | Enable the Appstats Interactive Playground. | Enable the Appstats Interactive Playground.
| Python | apache-2.0 | Koulio/rietveld,gco/rietveld,andyzsf/rietveld,google-code-export/rietveld,kscharding/integral-solutions-smxq,rietveld-codereview/rietveld,google-code-export/rietveld,v3ss0n/rietveld,ericmckean/rietveld,openlabs/cr.openlabs.co.in,aungzanbaw/rietveld,robfig/rietveld,Koulio/rietveld,arg0/rietveld,sajingeo/rietveld,openlab... |
176c03e26f46bad73df39c11ea4a190baca6fe54 | apps/authentication/tests.py | apps/authentication/tests.py | from django.core.urlresolvers import reverse
from django.test import TestCase
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
url = reverse('microauth_authentication:index')
response = self.client.get(url)
self.assertEqual(20... | from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
class HTTPGetRootTestCase(TestCase):
def setUp(self):
pass
def test_get_root_expect_http_200(self):
pipeline_settings = settings.PIPEL... | Make test not depend on django-pipeline | Make test not depend on django-pipeline
| Python | mit | microserv/microauth,microserv/microauth,microserv/microauth |
b501ee5dc2a41bf51f9f91c29501792338bf7269 | automatron/backend/controller.py | automatron/backend/controller.py | from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(self, config_file)
self.... | from functools import partial
from automatron.backend.plugin import PluginManager
from automatron.controller.controller import IAutomatronClientActions
from automatron.core.controller import BaseController
class BackendController(BaseController):
def __init__(self, config_file):
BaseController.__init__(se... | Use functools.partial for client action proxy. | Use functools.partial for client action proxy.
| Python | mit | automatron/automatron |
7925afd27ead247a017baf7a7dff97986904055f | comics/views.py | comics/views.py | from django.views import generic
from gallery.models import GalleryImage
from gallery import queries
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
... | from django.views import generic
from gallery.models import GalleryImage
from gallery import queries
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
... | Make it look nicer, possibly micro seconds faster | Make it look nicer, possibly micro seconds faster
| Python | mit | evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca |
04416cd9652a9fdc3ab58664ab4b96cbaff3f698 | simuvex/s_event.py | simuvex/s_event.py | import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_ad... | import itertools
event_id_count = itertools.count()
class SimEvent(object):
#def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None):
def __init__(self, state, event_type, **kwargs):
self.id = event_id_count.next()
self.type = event_type
self.ins_ad... | Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy. | Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
| Python | bsd-2-clause | axt/angr,schieb/angr,angr/angr,tyb0807/angr,f-prettyland/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,f-prettyland/angr,angr/angr,axt/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,chubbymaggie/angr,angr/simuvex,schieb/angr,iamahuman/angr,axt/angr,angr/angr,f-prettyland/angr,schieb/angr |
b1c1b28e58b59eac81954fb55570dfd389b99c0f | tests/acceptance/test_modify.py | tests/acceptance/test_modify.py | import datetime
from nose.tools import assert_raises
from scalymongo import Document
from scalymongo.errors import ModifyFailedError
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
class ModifyableDocument(Document):
__collection__ = __name__
__database__ = 'test'
structure = {
... | import datetime
from nose.tools import assert_raises
from scalymongo import Document
from scalymongo.errors import ModifyFailedError
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest
class BlogPostModifyExample(Document):
__collection__ = __name__
__database__ = 'test'
structure = {
... | Add more comprehensive testing of `modify` | acceptance: Add more comprehensive testing of `modify`
| Python | bsd-3-clause | allancaffee/scaly-mongo |
445a150982f2119b340d95edc66940e0ec54afbd | lib/ansiblelint/rules/NoFormattingInWhenRule.py | lib/ansiblelint/rules/NoFormattingInWhenRule.py | from ansiblelint import AnsibleLintRule
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']
def _is_valid(self, when):
if not isinstance(when, (str, unicode))... | from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include J... | Fix Python3 unicode test error | Fix Python3 unicode test error
| Python | mit | willthames/ansible-lint,dataxu/ansible-lint,MatrixCrawler/ansible-lint |
0e48b2130cc53caa9beb9a5f8ce09edbcc40f1b8 | ggplotx/tests/test_geom_point.py | ggplotx/tests/test_geom_point.py | from __future__ import absolute_import, division, print_function
import pandas as pd
from ggplotx import ggplot, aes, geom_point
def test_aesthetics():
df = pd.DataFrame({
'a': range(5),
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'... | from __future__ import absolute_import, division, print_function
import pandas as pd
from ggplotx import ggplot, aes, geom_point, theme
def test_aesthetics():
df = pd.DataFrame({
'a': range(5),
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
... | Add space on the RHS of geom_point test | Add space on the RHS of geom_point test
| Python | mit | has2k1/plotnine,has2k1/plotnine |
614a996dd8227808e796a369ed0faf1f9427f780 | organizer/views.py | organizer/views.py | from django.http.response import HttpResponse
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
html_output = "<html>\n"
html_output += "<head>\n"
html_output += " <title>"
html_output += "Don't Do This!</title>\n"
html_output += "</head>\n"
html_output += "<bod... | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(c... | Use template in homepage view. | Ch04: Use template in homepage view.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
7a24f314c426e55735836dd2f805d9e0364dc871 | tarbell/hooks.py | tarbell/hooks.py | # -*- coding: utf-8 -*-
hooks = {
'newproject': [], # (site)
'generate': [], # (site, dir, extra_context)
'publish': [], # (site, s3)
'install': [], # (site, project)
'preview': [], # (site)
'server_start': [], # (site)
'server_stop': [], ... | # -*- coding: utf-8 -*-
hooks = {
'newproject': [], # (site)
'generate': [], # (site, dir, extra_context)
'publish': [], # (site, s3)
'install': [], # (site, project)
'preview': [], # (site)
'server_start': [], # (site)
'server_stop': [], ... | Switch to Python 3-friendly `function.__name__` | Switch to Python 3-friendly `function.__name__`
| Python | bsd-3-clause | tarbell-project/tarbell,eyeseast/tarbell,tarbell-project/tarbell,eyeseast/tarbell |
e08395a35c37fa7f7c0311cc4c7a71537b8b4227 | tests/misc/print_exception.py | tests/misc/print_exception.py | try:
import uio as io
except ImportError:
import io
import sys
if hasattr(sys, 'print_exception'):
print_exception = sys.print_exception
else:
import traceback
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
def print_exc(e):
buf = io.StringIO()
... | try:
import uio as io
except ImportError:
import io
import sys
if hasattr(sys, 'print_exception'):
print_exception = sys.print_exception
else:
import traceback
print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f)
def print_exc(e):
buf = io.StringIO()
... | Add test for line number printing with large bytecode chunk. | tests/misc: Add test for line number printing with large bytecode chunk.
| Python | mit | henriknelson/micropython,AriZuu/micropython,AriZuu/micropython,micropython/micropython-esp32,micropython/micropython-esp32,PappaPeppar/micropython,MrSurly/micropython,MrSurly/micropython-esp32,infinnovation/micropython,trezor/micropython,micropython/micropython-esp32,lowRISC/micropython,torwag/micropython,PappaPeppar/m... |
9d0b1990b979de19939cc37cbefb86e1a0cd4e0f | test/perf/perf.py | test/perf/perf.py | import numpy as np
import pylab as pl
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*n... | import numpy as np
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observatio... | Remove pylab from import statements | Remove pylab from import statements
| Python | mit | wkearn/Kalman.jl,wkearn/Kalman.jl |
5f4155201afa92f048f28b9cd53681a6bc7966ab | vendor/eventlet-0.9.15/eventlet/convenience.py | vendor/eventlet-0.9.15/eventlet/convenience.py | # The history of this repository has been rewritten to erase the vendor/ directory
# Below is the md5sum and size of the file that was in the original commit
bde0e3a3a15c9bbb8d96f4d8a370d8c7
5753
| # The history of this repository has been rewritten to erase the vendor/ directory
# Below is the md5sum and size of the file that was in the original commit
5b7615cc9b13cf39cfa39db53e86977a
5751
| Drop eventlet bundle back to released state. Will workaround the bug we fixed there, in our own code. | Drop eventlet bundle back to released state. Will workaround the bug we fixed
there, in our own code.
| Python | mit | gratipay/aspen.py,gratipay/aspen.py |
e5b503d0e66f8422412d0cdeac4ba4f55f14e420 | spectrum/object.py | spectrum/object.py | # -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if t... | # -*- coding: utf-8 -*-
class Object:
"""Represents a generic Spectrum object
Supported Operations:
+-----------+--------------------------------------+
| Operation | Description |
+===========+======================================+
| x == y | Checks if t... | Change wording from future to present tense | Documentation: Change wording from future to present tense
| Python | mit | treefroog/spectrum.py |
9578081d1c6ce378687d605ba2350e08eddb6959 | scipy/ndimage/segment/setup.py | scipy/ndimage/segment/setup.py |
#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('segment', parent_package, top_path)
config.add_extension('_segmenter',
sources=['Segmenter_EXT.c',
... |
#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('segment', parent_package, top_path)
config.add_extension('_segmenter',
sources=['Segmenter_EXT.c',
... | Add tests as data_dir to ndimage.segment | Add tests as data_dir to ndimage.segment
| Python | bsd-3-clause | jamestwebber/scipy,mdhaber/scipy,ChanderG/scipy,Kamp9/scipy,Stefan-Endres/scipy,rmcgibbo/scipy,gdooper/scipy,mtrbean/scipy,petebachant/scipy,matthewalbani/scipy,fredrikw/scipy,efiring/scipy,apbard/scipy,ales-erjavec/scipy,mikebenfield/scipy,Eric89GXL/scipy,Newman101/scipy,sriki18/scipy,andyfaff/scipy,Stefan-Endres/scip... |
c06e28dae894823c0ae5385e0f9c047ceab8561c | zombies/tests.py | zombies/tests.py | from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic'... | from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story, StoryPoint
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',pictu... | Test case 2 for table storypoint | Test case 2 for table storypoint
| Python | apache-2.0 | ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project |
2baed20067fed71987bf7582fa9c9a5e53a63cb5 | python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py | python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py | s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
| s = "taintedString"
if s.startswith("tainted"): # $checks=s $branch=true
pass
sw = s.startswith # $f-:checks=s $f-:branch=true
if sw("safe"):
pass
| Test false negative from review | Python: Test false negative from review
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql |
46ae5bbeab37f8e2fe14607c01e385d746c2d163 | pymt/components.py | pymt/components.py | from __future__ import print_function
__all__ = []
import os
import sys
import warnings
import importlib
from glob import glob
from .framework.bmi_bridge import bmi_factory
from .babel import setup_babel_environ
def import_csdms_components():
debug = os.environ.get('PYMT_DEBUG', False)
setup_babel_environ(... | __all__ = []
import sys
from .plugin import load_csdms_plugins
for plugin in load_csdms_plugins():
__all__.append(plugin.__name__)
setattr(sys.modules[__name__], plugin.__name__, plugin)
| Move csdms-plugin loading to plugin module. | Move csdms-plugin loading to plugin module.
| Python | mit | csdms/pymt,csdms/coupling,csdms/coupling |
1e66aba5a2c82b09a6485842948aad49c654efb4 | scripts/load_topics_to_mongodb.py | scripts/load_topics_to_mongodb.py | import os
import csv
from pymongo import MongoClient
print('Parsing topics')
topics = {}
with open('topics.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
if line[0] == 1:
continue
topics[line[0]] = line[1:]
print('Connecting to MongoDB')
mongodb_client = M... | import os
import sys
import csv
from pymongo import MongoClient
print('Parsing topics')
topics = {}
with open(sys.argv[1], 'r') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
if line[0] == 1:
continue
topics[line[0]] = line[1:]
print('Connecting to MongoDB')
mongodb_c... | Fix script for loading topics into mongodb | Fix script for loading topics into mongodb | Python | mit | xenx/recommendation_system,xenx/recommendation_system |
eefa28f06620d568eda641b08c1caa9cff9a0c96 | resourcemanager.py | resourcemanager.py | # Manage resources here
import animation
sounds = {}
images = {}
animations = {}
loaded_resources = False
def load_resources():
"""Fills the structure above with the resources for the game.
"""
if loaded_resources:
return
loaded_resources = True
| # Manage resources here
import pygame
from pygame.locals import *
import animation
sounds = {}
images = {}
animations = {}
loaded_resources = False
sound_defs = {
"aoe" : "aoe.wav",
"big hit" : "big_hit.wav",
"burstfire" : "burstfire.wav",
"explosion" : "explosion.wav",
"fireball" : "fireball.... | Add sound definitions to resource manager | Add sound definitions to resource manager
| Python | mit | vwood/pyweek2013 |
e578c90cc542d3cf825645fa9376796a1e7c31f9 | lib/cache.py | lib/cache.py | import functools
import logging
import redis
import config
# Default options
redis_opts = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
redis_conn = None
cache_prefix = None
def init():
global redis_conn, cache_prefix
cfg = config.load()
cache = cfg.cache
if not... | import functools
import logging
import redis
import config
# Default options
redis_opts = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
redis_conn = None
cache_prefix = None
def init():
global redis_conn, cache_prefix
cfg = config.load()
cache = cfg.cache
if not... | Remove unneeded lru specific helper methods | Remove unneeded lru specific helper methods
| Python | apache-2.0 | dalvikchen/docker-registry,atyenoria/docker-registry,atyenoria/docker-registry,ewindisch/docker-registry,docker/docker-registry,ken-saka/docker-registry,wakermahmud/docker-registry,Carrotzpc/docker-registry,kireal/docker-registry,ewindisch/docker-registry,yuriyf/docker-registry,whuwxl/docker-registry,Haitianisgood/dock... |
52bb18cf1249e3f48764a7ed4e9546439692c5cb | packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py | packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py | import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self... | import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self.valobj.... | Fix TestSyntheticCapping for Python 3. | Fix TestSyntheticCapping for Python 3.
In Python 3, whitespace inconsistences are errors. This synthetic
provider had mixed tabs and spaces, as well as inconsistent
indentation widths. This led to the file not being imported,
and naturally the test failing. No functional change here, just
whitespace.
git-svn-id: 4... | Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb |
e6fa443412a909bc01e2dd8d9944ff3ddba35089 | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from .. import e, inf, nan, pi
| from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| Make the array API constants into dimension 0 arrays | Make the array API constants into dimension 0 arrays
The spec does not actually specify whether these should be dimension 0 arrays
or Python floats (which they are in NumPy). However, making them dimension 0
arrays is cleaner, and ensures they also have all the methods and attributes
that are implemented on the ndarra... | Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
f012d59f163a8b8a693dc894d211f077ae015d11 | Instanssi/kompomaatti/tests.py | Instanssi/kompomaatti/tests.py | from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v/asdf123456",
... | from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols and hostnames in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456",
"www.youtube.com/v... | Add more test data; improve feedback on failing case | kompomaatti: Add more test data; improve feedback on failing case
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org |
948c9c6ffb8a34e3acf00b8190bf65504f2bfaf6 | app.py | app.py | import falcon
from resources.waifu_message_resource import WaifuMessageResource
api = falcon.API()
api.add_route('/waifu/messages', WaifuMessageResource())
| import falcon
from resources.user_resource import UserResource, UserAuthResource
from resources.waifu_message_resource import WaifuMessageResource
from resources.waifu_resource import WaifuResource
api = falcon.API()
api.add_route('/user', UserResource())
api.add_route('/user/auth', UserAuthResource())
api.add_route(... | Add endpoints for all resources. | Add endpoints for all resources.
| Python | cc0-1.0 | sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend |
bea8b07180e6e9b2c786dfe37e12e75090363a1c | run.py | run.py | import os
import json
default_conf = {
'reddit': {
'username': '',
'password': '',
},
'twitter': {
'consumer_key': '',
'consumer_secret': '',
'access_token': '',
'access_secret': '',
},
}
if __name__ == '__main__':
if not os.path.isfile('config.json... | import os
import json
import sys
default_conf = {
'reddit': {
'username': '',
'password': '',
},
'twitter': {
'consumer_key': '',
'consumer_secret': '',
'access_token': '',
'access_secret': '',
},
}
def write_conf(conf):
config = json.dumps(conf, in... | Add twitter stuff to default config and allow easier merging of configs | Add twitter stuff to default config and allow easier merging of configs
| Python | mit | r3m0t/TweetPoster,joealcorn/TweetPoster,tytek2012/TweetPoster,aperson/TweetPoster |
9d65eaa14bc3f04ea998ed7bc43b7c71e5d232f7 | v3/scripts/testing/create-8gb-metadata.py | v3/scripts/testing/create-8gb-metadata.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = 'eric'
'''
Need to create some test data
'''
| #!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = 'eric'
'''
Need to create some test data
8 gigabytes dataset
'''
| Test script for generating metadata | Test script for generating metadata
| Python | mit | TheShellLand/pies,TheShellLand/pies |
53d09ddacc92a52219a3cd18bba606840b870fcd | vumi_http_proxy/test/test_servicemaker.py | vumi_http_proxy/test/test_servicemaker.py | from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.parseOptions([])
self.assertEqual(options["port"], ... | from vumi_http_proxy.servicemaker import (
Options, ProxyWorkerServiceMaker, client)
from vumi_http_proxy import http_proxy
from twisted.trial import unittest
from vumi_http_proxy.test import helpers
class TestOptions(unittest.TestCase):
def test_defaults(self):
options = Options()
options.par... | Patch out DNS resolver in makeService tests. | Patch out DNS resolver in makeService tests.
| Python | bsd-3-clause | praekelt/vumi-http-proxy,praekelt/vumi-http-proxy |
2cc55a25b13ac6575424ba70857a8419b796ca76 | _tests/macro_testing/runner.py | _tests/macro_testing/runner.py | # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This fun... | # -*- coding: utf-8 -*-
import os, os.path
import sys
import unittest
from macrotest import JSONSpecMacroTestCaseFactory
def JSONTestCaseLoader(tests_path, recursive=False):
"""
Load JSON specifications for Jinja2 macro test cases from the given
path and returns the resulting test classes.
This fun... | Make the paths not relative, so tests can be run from anywhere. | Make the paths not relative, so tests can be run from anywhere.
| Python | cc0-1.0 | imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh |
2cde3dbb69077054c6422cbe96e9b996be700d29 | pulldb/api/subscriptions.py | pulldb/api/subscriptions.py | import json
import logging
from google.appengine.api import oauth
from google.appengine.ext import ndb
from pulldb import users
from pulldb.api.base import OauthHandler, JsonModel
from pulldb.base import create_app, Route
from pulldb.models.subscriptions import Subscription, subscription_context
class ListSubs(Oauth... | import json
import logging
from google.appengine.api import oauth
from google.appengine.ext import ndb
from pulldb import users
from pulldb.api.base import OauthHandler, JsonModel
from pulldb.base import create_app, Route
from pulldb.models.subscriptions import Subscription, subscription_context
class ListSubs(Oauth... | Make subscription handler less oauth dependant | Make subscription handler less oauth dependant
| Python | mit | xchewtoyx/pulldb |
a18eb7509619914cd0565255730ed6bb40f14c9b | ovp_users/emails.py | ovp_users/emails.py | from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(sel... | from ovp_core.emails import BaseMail
class UserMail(BaseMail):
"""
This class is responsible for firing emails for Users
"""
def sendWelcome(self, context={}):
"""
Sent when user registers
"""
return self.sendEmail('welcome', 'Welcome', context)
def sendRecoveryToken(self, context):
"""... | Move BaseMail from ovp-users to ovp-core | Move BaseMail from ovp-users to ovp-core
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users |
709d4386a308ce8c0767eab1f2174ec321ea59fd | client/main.py | client/main.py | import requests
import yaml
def runLoop( config ):
"""
Runs indefinitely. On user input (card swipe), will gather the card number,
send it to the server configured, and if it has been authorized, open the
relay with a GPIO call.
"""
while True:
swipe = input()
cardNumber = swipe
print( 'The last input wa... | import requests
import yaml
def runLoop( config ):
"""
Runs indefinitely. On user input (card swipe), will gather the card number,
send it to the server configured, and if it has been authorized, open the
relay with a GPIO call.
"""
while True:
swipe = input()
cardNumber = swipe
print( 'The last input wa... | Rename funciton to match corresponding HTTP request | Rename funciton to match corresponding HTTP request
| Python | mit | aradler/Card-lockout,aradler/Card-lockout,aradler/Card-lockout |
7206d68648c91790ac4fa14a3074c77c97c01636 | mopidy/backends/base/__init__.py | mopidy/backends/base/__init__.py | import logging
from .current_playlist import CurrentPlaylistController
from .library import LibraryController, BaseLibraryProvider
from .playback import PlaybackController, BasePlaybackProvider
from .stored_playlists import (StoredPlaylistsController,
BaseStoredPlaylistsProvider)
logger = logging.getLogger('mopid... | import logging
from .current_playlist import CurrentPlaylistController
from .library import LibraryController, BaseLibraryProvider
from .playback import PlaybackController, BasePlaybackProvider
from .stored_playlists import (StoredPlaylistsController,
BaseStoredPlaylistsProvider)
logger = logging.getLogger('mopid... | Remove mixer from the Backend API as it is independent | Remove mixer from the Backend API as it is independent
| Python | apache-2.0 | adamcik/mopidy,vrs01/mopidy,pacificIT/mopidy,jmarsik/mopidy,jcass77/mopidy,glogiotatidis/mopidy,kingosticks/mopidy,ZenithDK/mopidy,rawdlite/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,tkem/mopidy,kingosticks/mopidy,jmarsik/mopidy,SuperStarPL/mopidy,bencevans/mopidy,diandiankan/mopidy,quartz55/mopidy,glogiotatidis/mopid... |
b24af9c3e4105d7acd2e9e13545f24d5a69ae230 | saleor/product/migrations/0018_auto_20161212_0725.py | saleor/product/migrations/0018_auto_20161212_0725.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 13:25
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def create_slugs(apps, schema_editor):
Value = apps.get_model('product', 'AttributeChoiceValue')
for value in Value.objects.a... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 13:25
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def create_slugs(apps, schema_editor):
Value = apps.get_model('product', 'AttributeChoiceValue')
for value in Value.objects.a... | Allow to revert data migaration | Allow to revert data migaration
| Python | bsd-3-clause | KenMutemi/saleor,maferelo/saleor,jreigel/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,tfroehlich82/saleor,KenMutemi/saleor,mociepka/saleor,car3oon/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,UITools/saleor,UITools/sal... |
9d0e9af5844772c18ca24d4012642d4518b66dfc | tests/test_judicious.py | tests/test_judicious.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import pytest
import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import random
import pytest
import judicious
def test_seeding():
r1 = random.random()
r2 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r3 = random.random()
r4 = random.random()
jud... | Add test of seeding PRNG | Add test of seeding PRNG
| Python | mit | suchow/judicious,suchow/judicious,suchow/judicious |
d46d908f5cfafcb6962207c45f923d3afb7f35a7 | pyrobus/__init__.py | pyrobus/__init__.py | from .robot import Robot
from .modules import *
| import logging
from .robot import Robot
from .modules import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
| Add null handler as default for logging. | Add null handler as default for logging.
| Python | mit | pollen/pyrobus |
c220c0a474a660c4c1167d42fdd0d48599b1b593 | tests/test_pathutils.py | tests/test_pathutils.py | from os.path import join
import sublime
import sys
from unittest import TestCase
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
path = join('/foo','bar','baz'... | from os.path import join, realpath
import os
import sublime
import sys
from unittest import TestCase
from functools import wraps
def subl_patch(pkg, obj=None):
def subl_deco(fn):
@wraps(fn)
def wrap(*args):
nonlocal pkg
o = []
if obj != None:
o +... | Make custom patch in package to test | Make custom patch in package to test
| Python | mit | blitzrk/sublime_libsass,blitzrk/sublime_libsass |
9eddd3b5c4635637faead9d7eae73efd2e324bdb | recipes/tests/test_views.py | recipes/tests/test_views.py | from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view... | from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from recipes.views import home_page
from recipes.models import Recipe
class HomePageViewTest(TestCase):
def test_root_url_resolves_to_home_page_view... | Use the test client to check all templates for correctness | Use the test client to check all templates for correctness
| Python | agpl-3.0 | XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd |
c1edc666630c03b6d85d9749e0695a9f19dd7c13 | src/collectd_scripts/handle_collectd_notification.py | src/collectd_scripts/handle_collectd_notification.py | #!/usr/bin/python
import sys
import os
import salt.client
def getNotification():
notification_dict = {}
isEndOfDictionary = False
for line in sys.stdin:
if not line.strip():
isEndOfDictionary = True
continue
if isEndOfDictionary:
break
key, value... | #!/usr/bin/python
import sys
import os
import salt.client
def getNotification():
notification_dict = {}
isEndOfDictionary = False
for line in sys.stdin:
if not line.strip():
isEndOfDictionary = True
continue
if isEndOfDictionary:
break
key, value... | Fix in collectd event notifier script. | Skynet: Fix in collectd event notifier script.
This patch adds a fix to collectd event notifier script,
by providing a value the "severity" field in the event
that it sends to salt-master event bus. with out that
event listener in the skyring server will fail to
process it.
Change-Id: I20b738468c8022a25024e4327434ae6... | Python | apache-2.0 | skyrings/skynet,skyrings/skynet |
545812b5e31b4894c600b2b172640bea27947db8 | ecmd-core/pyecmd/test_api.py | ecmd-core/pyecmd/test_api.py | from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId... | from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins... | Make fapi2 test conditional on fapi2 being built into ecmd | pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
| Python | apache-2.0 | mklight/eCMD,mklight/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD |
01e9df01bc17561d0f489f1647ce5e0c566372e5 | flocker/provision/__init__.py | flocker/provision/__init__.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Provisioning for acceptance tests.
"""
from ._common import PackageSource
from ._install import provision
from ._rackspace import rackspace_provisioner
from ._aws import aws_provisioner
# import digitalocean_provisioner
__all__ = [
'PackageSource',... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Provisioning for acceptance tests.
"""
from ._common import PackageSource
from ._install import provision
from ._rackspace import rackspace_provisioner
from ._aws import aws_provisioner
from ._digitalocean import digitalocean_provisioner
__all__ = [
... | Make the digitalocean provisioner public | Make the digitalocean provisioner public
| Python | apache-2.0 | wallnerryan/flocker-profiles,1d4Nf6/flocker,hackday-profilers/flocker,moypray/flocker,mbrukman/flocker,hackday-profilers/flocker,agonzalezro/flocker,1d4Nf6/flocker,w4ngyi/flocker,moypray/flocker,agonzalezro/flocker,mbrukman/flocker,adamtheturtle/flocker,moypray/flocker,AndyHuu/flocker,achanda/flocker,lukemarsden/flocke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.