commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
4b56e0da85cec4aa89b8105c3a7ca416a2f7919e | wdim/client/blob.py | wdim/client/blob.py | import json
import hashlib
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.H... | import json
import hashlib
from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data: Dic... | Allow Blob to be accessed with __getitem__ | Allow Blob to be accessed with __getitem__
| Python | mit | chrisseto/Still | ---
+++
@@ -1,5 +1,6 @@
import json
import hashlib
+from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
@@ -14,7 +15,7 @@
data = fields.DictField()
@classmethod
- async def create(cls, data):
+ async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hash... |
a78445cfada5cc1f77a7887dc5241071bef69989 | compass/tests/test_models.py | compass/tests/test_models.py | from django.test import TestCase
from compass.models import (Category,
Book)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestC... | from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestC... | Test correct heading returned in search results | Test correct heading returned in search results
| Python | mit | andela-osule/bookworm,andela-osule/bookworm | ---
+++
@@ -1,6 +1,6 @@
from django.test import TestCase
from compass.models import (Category,
- Book)
+ Book, Compass)
class CategoryTestCase(TestCase):
@@ -14,3 +14,17 @@
category = Category.create(title="Mock Category")
Book.create(titl... |
e299906aae483f1cb6deaff83a68519a042b92e6 | stripe/stripe_response.py | stripe/stripe_response.py | from __future__ import absolute_import, division, print_function
import json
class StripeResponse:
def __init__(self, body, code, headers):
self.body = body
self.code = code
self.headers = headers
self.data = json.loads(body)
@property
def idempotency_key(self):
... | from __future__ import absolute_import, division, print_function
import json
class StripeResponse(object):
def __init__(self, body, code, headers):
self.body = body
self.code = code
self.headers = headers
self.data = json.loads(body)
@property
def idempotency_key(self):
... | Make StripeResponse a new-style class | Make StripeResponse a new-style class
| Python | mit | stripe/stripe-python | ---
+++
@@ -3,8 +3,7 @@
import json
-class StripeResponse:
-
+class StripeResponse(object):
def __init__(self, body, code, headers):
self.body = body
self.code = code |
eaa2ef92eba11d44bf5159342e314b932d79f58d | fedora/__init__.py | fedora/__init__.py | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway. | Undo the webtest import... it's causing runtime failiure and unittests are
currently broken anyway.
| Python | lgpl-2.1 | fedora-infra/python-fedora | ---
+++
@@ -31,8 +31,5 @@
from fedora import release
__version__ = release.VERSION
-# Needed for our unit tests
-from fedora.wsgi.test import websetup
-
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup') |
b4061152064269f8848c374cf81a867a9c0a7388 | latex/errors.py | latex/errors.py | import re
LATEX_ERR_RE = re.compile(r'(?P<filename>[^:]+):(?P<line>[0-9]*):'
r'\s*(?P<error>.*)')
def parse_log(log, context_size=3):
lines = log.split('\n')
errors = []
for n, line in enumerate(lines):
m = LATEX_ERR_RE.match(line)
if m:
err = m.grou... | import re
LATEX_ERR_RE = re.compile(r'(?P<filename>[^:]+):(?P<line>[0-9]*):'
r'\s*(?P<error>.*)')
def parse_log(log, context_size=3):
lines = log.splitlines()
errors = []
for n, line in enumerate(lines):
m = LATEX_ERR_RE.match(line)
if m:
err = m.gro... | Use splitlines instead of split on new line. | Use splitlines instead of split on new line.
| Python | bsd-3-clause | mbr/latex | ---
+++
@@ -5,7 +5,7 @@
def parse_log(log, context_size=3):
- lines = log.split('\n')
+ lines = log.splitlines()
errors = []
for n, line in enumerate(lines): |
662287761b8549a86d3fb8c05ec37d47491da120 | flatblocks/urls.py | flatblocks/urls.py | from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
]
| from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path(
r"^edit/(?P<pk>\d+)/$",
staff_member_required(edit),
name="flatblocks-edit",
),
]
| Use raw string notation for regular expression. | Use raw string notation for regular expression.
| Python | bsd-3-clause | funkybob/django-flatblocks,funkybob/django-flatblocks | ---
+++
@@ -3,5 +3,9 @@
from flatblocks.views import edit
urlpatterns = [
- re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
+ re_path(
+ r"^edit/(?P<pk>\d+)/$",
+ staff_member_required(edit),
+ name="flatblocks-edit",
+ ),
] |
1cc6ec9f328d3ce045a4a1a50138b11c0b23cc3a | pyfr/ctypesutil.py | pyfr/ctypesutil.py | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
... | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath =... | Enable library paths to be explicitly specified. | Enable library paths to be explicitly specified.
All shared libraries loaded through the load_library function
can bow be specified explicitly through a suitable environmental
variable
PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here
where <LIB> corresponds to the name of the library, e.g. METIS.
| Python | bsd-3-clause | BrianVermeire/PyFR | ---
+++
@@ -14,15 +14,20 @@
def load_library(name):
+ # If an explicit override has been given then use it
+ lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
+ if lpath:
+ return ctypes.CDLL(lpath)
+
+ # Otherwise synthesise the library name and start searching
lname =... |
8237291e194aa900857fe382d0b8cefb7806c331 | ocradmin/ocrmodels/models.py | ocradmin/ocrmodels/models.py | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=... | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=... | Improve unicode method. Whitespace cleanup | Improve unicode method. Whitespace cleanup
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -23,11 +23,10 @@
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
-
def __unicode__(self):
"""
String representation.
"""
- return self.name
+ return "<%s: %s>" % (self.__class__.__name__, s... |
146d9eb75b55298886a3860976b19be5b42825b2 | deriva/core/base_cli.py | deriva/core/base_cli.py | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
... | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version, "A valid version string is required"
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epil... | Add some detail text to assertion. | Add some detail text to assertion.
| Python | apache-2.0 | informatics-isi-edu/deriva-py | ---
+++
@@ -7,7 +7,8 @@
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
- assert version
+ assert version, "A valid version string is required"
+
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog) |
e26b95803707e74dba2cc451476466eefc156f8f | tests/test_coefficient.py | tests/test_coefficient.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_pe... | # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_pe... | Fix evaluation date & test period | Fix evaluation date & test period
| Python | agpl-3.0 | sgmap/openfisca-france,sgmap/openfisca-france,antoinearnoud/openfisca-france,antoinearnoud/openfisca-france | ---
+++
@@ -15,7 +15,7 @@
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
- contrat_de_travail_fin='2017-11-30',
+ contrat_de_travail_fin='2017-12-01',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new... |
02df4f76b61556edc04869e8e70bf63c3df75ef3 | humbug/backends.py | humbug/backends.py | from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user ba... | from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user ba... | Allow case-insensitive email addresses when doing authentication | Allow case-insensitive email addresses when doing authentication
(imported from commit b52e39c7f706a2107b5d86e8e18293a46ed9e6ff)
| Python | apache-2.0 | armooo/zulip,qq1012803704/zulip,ikasumiwt/zulip,hj3938/zulip,nicholasbs/zulip,kou/zulip,pradiptad/zulip,jackrzhang/zulip,codeKonami/zulip,alliejones/zulip,Vallher/zulip,bastianh/zulip,natanovia/zulip,so0k/zulip,noroot/zulip,lfranchi/zulip,bitemyapp/zulip,wavelets/zulip,showell/zulip,codeKonami/zulip,praveenaki/zulip,dn... | ---
+++
@@ -17,7 +17,7 @@
return None
try:
- user = User.objects.get(email=username)
+ user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist: |
7a99695c7612609de294a6905820fad3e41afc43 | marketpulse/devices/models.py | marketpulse/devices/models.py | from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
| from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
class Meta:
orderi... | Order devices by manufacturer and model. | Order devices by manufacturer and model.
| Python | mpl-2.0 | johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse | ---
+++
@@ -9,3 +9,6 @@
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
+
+ class Meta:
+ ordering = ['manufacturer', 'model'] |
a760beb8d66222b456b160344eb0b4b7fccbf84a | Lib/test/test_linuxaudiodev.py | Lib/test/test_linuxaudiodev.py | from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
rais... | from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.EN... | Raise TestSkipped, not ImportError. Honesty's the best policy. | Raise TestSkipped, not ImportError.
Honesty's the best policy.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,4 @@
-from test_support import verbose, findfile, TestFailed
+from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
@@ -11,7 +11,7 @@
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES,... |
70db9410173183c83d80ca23e56ceb0d627fcbae | scripts/indices.py | scripts/indices.py | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCE... | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['storedfilenode'].create_index([
('tags', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user']... | Add index on file tags field | Add index on file tags field
| Python | apache-2.0 | baylee-d/osf.io,abought/osf.io,Johnetordoff/osf.io,felliott/osf.io,alexschiller/osf.io,mluo613/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,aaxelb/osf.io,wearpants/osf.io,hmoco/osf.io,mfraezz/osf.io,caseyrollins/osf.io,leb2dg/osf.io,emetsger/osf.io,caneruguz/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,bayle... | ---
+++
@@ -4,6 +4,9 @@
from pymongo import ASCENDING, DESCENDING
+db['storedfilenode'].create_index([
+ ('tags', ASCENDING),
+])
db['user'].create_index([
('emails', ASCENDING), |
ecbabd56f6afc4474402d3293bf11e3b6eb2e8f4 | server/__init__.py | server/__init__.py | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsR... | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsR... | Switch to generating REST end points from docker image | Switch to generating REST end points from docker image
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | ---
+++
@@ -25,6 +25,6 @@
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
- genRESTEndPointsForSlicerCLIsInDocker(info,
- 'HistomicsTK',
- 'dsarchive/hist... |
56dc9af410907780faba79699d274bef96a18675 | functionaltests/common/base.py | functionaltests/common/base.py | """
Copyright 2015 Rackspace
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
dist... | """
Copyright 2015 Rackspace
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
dist... | Remove unnecessary __init__ from functionaltests | Remove unnecessary __init__ from functionaltests
The __init__ just passes the same arguments, so it is not necessary
to implement it. This patch removes it for the cleanup.
Change-Id: Ib465356c47d06bfc66bef69126b089be24d19474
| Python | apache-2.0 | openstack/designate,openstack/designate,openstack/designate | ---
+++
@@ -21,9 +21,6 @@
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
- def __init__(self, *args, **kwargs):
- super(BaseDesignateTest, self).__init__(*args, **kwargs)
-
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass() |
40ca8cde872704438fecd22ae98bc7db610de1f9 | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | Rewrite Flickr to use the new scope selection system | Rewrite Flickr to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -14,17 +14,21 @@
api_domain = 'api.flickr.com'
available_permissions = [
- # (None, 'access only your public photos'),
- # ('read', 'access your public and private photos'),
- # ('write', 'upload, edit and replace your photos'),
+ (None, 'access only your public phot... |
267b0634546c55ebb42d6b1b9c3deca9d7408cc2 | run_tests.py | run_tests.py | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation
TEST_PATH Path to pac... | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path,... | Fix test runner to accept 1 arg | Fix test runner to accept 1 arg
| Python | mit | the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopr... | ---
+++
@@ -8,8 +8,7 @@
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
-SDK_PATH Path to the SDK installation
-TEST_PATH Path to package containing test modules"""
+SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_path):
@@ -23,8 +22... |
def9d7037a3c629f63e1a0d8c1721501abc110cd | linguee_api/downloaders/httpx_downloader.py | linguee_api/downloaders/httpx_downloader.py | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
... | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned... | Update the 503 error message. | Update the 503 error message.
| Python | mit | imankulov/linguee-api | ---
+++
@@ -1,6 +1,12 @@
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
+
+ERROR_503 = (
+ "The Linguee server returned 503. The API proxy was temporarily blocked by "
+ "Linguee. For more details, see https://github.com/imankulov/linguee-api#"
+ "the-api-server-... |
ffa00eaea02cda8258bf42d4fa733fb8693e2f0c | chemtrails/apps.py | chemtrails/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(s... | # -*- coding: utf-8 -*-
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
... | Read Neo4j config from ENV if present | Read Neo4j config from ENV if present
| Python | mit | inonit/django-chemtrails,inonit/django-chemtrails,inonit/django-chemtrails | ---
+++
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+
+import os
from django.apps import AppConfig
from django.conf import settings
@@ -29,5 +31,7 @@
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
- config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO... |
7a688f0712ff323668955a21ea335f3308fcc840 | wurstmineberg.45s.py | wurstmineberg.45s.py | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for w... | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for w... | Add “Start Minecraft” menu item | Add “Start Minecraft” menu item
From https://github.com/matryer/bitbar-plugins/blob/master/Games/minecraftplayers.1m.py
| Python | mit | wurstmineberg/bitbar-server-status | ---
+++
@@ -12,3 +12,6 @@
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
+
+print('---')
+print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft ... |
6cc904a4ee48f8bdbc52cff6cda254e5e69b3c48 | framework/analytics/migrate.py | framework/analytics/migrate.py | from website.app import init_app
from website.models import Node, User
from framework import Q
from framework.analytics import piwik
app = init_app("website.settings", set_backends=True)
# NOTE: This is a naive implementation for migration, requiring a POST request
# for every user and every node. It is possible to b... | from website.app import init_app
from website.models import Node, User
from framework import Q
from framework.analytics import piwik
app = init_app("website.settings", set_backends=True)
# NOTE: This is a naive implementation for migration, requiring a POST request
# for every user and every node. It is possible to b... | Update to latest version of ODM: Join queries with `&`, not `,` | Update to latest version of ODM: Join queries with `&`, not `,`
| Python | apache-2.0 | brandonPurvis/osf.io,GaryKriebel/osf.io,brianjgeiger/osf.io,kch8qx/osf.io,leb2dg/osf.io,zachjanicki/osf.io,cosenal/osf.io,jeffreyliu3230/osf.io,kushG/osf.io,mluo613/osf.io,GaryKriebel/osf.io,njantrania/osf.io,jinluyuan/osf.io,erinspace/osf.io,mfraezz/osf.io,barbour-em/osf.io,adlius/osf.io,HarryRybacki/osf.io,hmoco/osf.... | ---
+++
@@ -17,7 +17,7 @@
piwik.create_user(user)
-for node in Node.find(Q('is_public', 'eq', True), Q('is_deleted', 'eq', False)):
+for node in Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False)):
if node.piwik_site_id:
continue
|
75a4097006e6ea5f1693b9d746456b060974d8a0 | mtglib/__init__.py | mtglib/__init__.py | __version__ = '1.5.2'
__author__ = 'Cameron Higby-Naquin'
| __version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin'
| Increment minor version for new feature release. | Increment minor version for new feature release.
| Python | mit | chigby/mtg,chigby/mtg | ---
+++
@@ -1,2 +1,2 @@
-__version__ = '1.5.2'
+__version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin' |
d4db750d2ff2e18c9fced49fffe7a3073880078b | InvenTree/common/apps.py | InvenTree/common/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
pass
| # -*- coding: utf-8 -*-
import logging
from django.apps import AppConfig
logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.clear_restart_flag()
def clear_restart_flag(self):
"""
Clear the SERVER_RESTART_REQUI... | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | ---
+++
@@ -1,10 +1,30 @@
# -*- coding: utf-8 -*-
+import logging
+
from django.apps import AppConfig
+
+
+logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
- pass
+
+ self.clear_restart_flag()
+
+ def clear_restart_fl... |
ae918211a85654d7eaa848cbd09f717d0339f844 | database_email_backend/backend.py | database_email_backend/backend.py | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
retur... | Convert everything to unicode strings before inserting to DB | Convert everything to unicode strings before inserting to DB | Python | mit | machtfit/django-database-email-backend,machtfit/django-database-email-backend,jbinary/django-database-email-backend,stefanfoulis/django-database-email-backend,jbinary/django-database-email-backend | ---
+++
@@ -10,14 +10,14 @@
return
for message in email_messages:
email = Email.objects.create(
- from_email = message.from_email,
- to_emails = ', '.join(message.to),
- cc_emails = ', '.join(message.cc),
- bcc_emails = ', ... |
b4c97d3b7b914c193c018a1d808f0815778996b4 | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Remove comment from previous migration | Remove comment from previous migration
The migration was using a comment from the first one.
Change-Id: I25dc9ca79f30f156bfc4296c44e141991119635e
| Python | apache-2.0 | ilay09/keystone,rajalokan/keystone,mahak/keystone,openstack/keystone,ilay09/keystone,openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,rajalokan/keystone,rajalokan/keystone,ilay09/keystone | ---
+++
@@ -10,9 +10,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-# A null initial migration to open this repo. Do not re-use replace this with
-# a real migration, add additional ones in subsequent version scripts.
-
def upgrade(migrate_engine):
pas... |
cd0b6af73dd49b4da851a75232b5829b91b9030c | genome_designer/conf/demo_settings.py | genome_designer/conf/demo_settings.py | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
... | Allow refresh materialized view in DEMO_MODE. | Allow refresh materialized view in DEMO_MODE.
| Python | mit | woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone | ---
+++
@@ -22,6 +22,7 @@
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
+ 'main.xhr_handlers.refresh_materialized_variant_table',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
... |
e073e020d46953e15f0fb30d2947028c42261fc1 | cropimg/widgets.py | cropimg/widgets.py | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no f... | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueEr... | Make sure that the admin widget also supports Django 2 | Make sure that the admin widget also supports Django 2
| Python | mit | rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django | ---
+++
@@ -4,7 +4,7 @@
class CIImgWidget(ClearableFileInput):
- def render(self, name, value, attrs=None):
+ def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file as... |
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 | ---
+++
@@ -6,10 +6,9 @@
def __init__(self, json_response):
self.response = json_response
- try:
- self.err_code = json_response['@attributes']['err_code']
- self.message = str(json_response['err'])
- except KeyError:
+ self.err_code = json_response.get('@att... |
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 | ---
+++
@@ -1,4 +1,5 @@
from django import template
+from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@@ -12,3 +13,9 @@
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
+
+
+@register.assignmen... |
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 | ---
+++
@@ -11,7 +11,6 @@
test_nr = IntegerField()
class Meta:
- pk_key = 'test_nr'
resource_name = 'my-resource'
|
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 | ---
+++
@@ -13,5 +13,6 @@
if __name__ == '__main__':
handler = SerfHandlerProxy()
- handler.register(os.environ.get('ROLE', 'no_role'), MyHandler())
+ role = os.environ.get('ROLE') or 'no_role'
+ handler.register(role, MyHandler())
handler.run() |
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 | ---
+++
@@ -11,6 +11,5 @@
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
- self.remove_selection("1") # in case it was expanded
self.view.sel().clear()
self.view.run_command("acme_plumbing", message) |
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 | ---
+++
@@ -15,7 +15,7 @@
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
- created = fields.DateTimeField(auto_now=True)
+ created = fields.DateTimeField(default=timezone.no... |
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 | ---
+++
@@ -14,7 +14,9 @@
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self._preprocessed_dir_name = f'{self.get_slug()}.pre'
+ self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
+
+ self._preprocessed_dir_name = f'{self._p... |
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 | ---
+++
@@ -23,12 +23,11 @@
print "Error in json"
print e
print "Try again (y/n)? ",
- input = sys.stdin.readline()
+ input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
- pri... |
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 | ---
+++
@@ -3,7 +3,10 @@
from __future__ import print_function
import unittest
-from mock import Mock
+try:
+ from unittest.mock import Mock
+except ImportError:
+ from mock import Mock
from github_webhook.webhook import 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 | ---
+++
@@ -3,6 +3,7 @@
from subprocess import Popen, PIPE
import tempfile
import os
+import sys
config = {}
with open ('../config/conversion.json') as fp:
@@ -15,9 +16,8 @@
if request.status_code == 200:
cjson = request.json();
else:
+ print >> sys.stderr, "Unable to access REST API: %s" % reque... |
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 | ---
+++
@@ -20,3 +20,6 @@
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
+
+ """Rename Hangout"""
+ yield from bot._client.setchatname(event.conv_id, ' '.join(args)) |
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 | ---
+++
@@ -15,7 +15,7 @@
, 'tradesoap'
, 'xalan'))
-WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
+WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
""" |
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... | ---
+++
@@ -1,8 +1,10 @@
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: |
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 | ---
+++
@@ -19,8 +19,8 @@
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
+ response['Access-Control-Allow-Credentials... |
73219ea03b46599b4e2c84a301599c7f1f331751 | sal/urls.py | sal/urls.py | import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.Login... | import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.Login... | Fix linter complaint and append rather than cat lists. | Fix linter complaint and append rather than cat lists.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal | ---
+++
@@ -26,4 +26,4 @@
]
if settings.DEBUG:
- urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
+ urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve)) |
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 | ---
+++
@@ -4,9 +4,6 @@
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_migration(cls, migration): |
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 | ---
+++
@@ -2,13 +2,13 @@
from itertools import chain
-from django import forms
+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(forms.Tex... |
87929f67c0036bf9a0a2ad237c1a03b675484a74 | mcgill_app/main.py | mcgill_app/main.py | import graphs
import star
def main():
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude")
# Temperatures of black bodies (K) mapped to style of lines on graph.
te... | import graphs
import star
def main():
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude / W * sr^-1 * m^-3")
# Temperatures of black bodies (K) mapped to style of lin... | Change units on graph y-axis | Change units on graph y-axis
| Python | mit | jackromo/GSOCMcgillApplication | ---
+++
@@ -6,7 +6,7 @@
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
- graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude")
+ graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude / W * sr^-... |
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 | ---
+++
@@ -18,6 +18,7 @@
model = SiteConfig
site = factory.SubFactory(Site)
+ logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
- email_header = factory.django.ImageField(filenam... |
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 | ---
+++
@@ -1,7 +1,12 @@
#!/usr/bin/env python
-SIMULATION_TIME_IN_SECONDS = 40
+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(SI... |
9150618ca2a1c4b8917596547f73d9c1cc207fda | monkeys/release.py | monkeys/release.py | from invoke import task, run
@task
def makerelease(version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("grunt")
if not local_only:
... | from invoke import task, run
@task
def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("grunt")
if not local_only:... | Make invoke tasks work with the new version of invoke. | cm: Make invoke tasks work with the new version of invoke.
| Python | apache-2.0 | ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked | ---
+++
@@ -2,7 +2,7 @@
@task
-def makerelease(version, local_only=False):
+def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
|
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 | ---
+++
@@ -1,10 +1,12 @@
from os import path
-from indra.tools.reading.read_files import read_files, get_readers
+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')
+
+... |
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 | ---
+++
@@ -21,7 +21,6 @@
import models
def main():
- # TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler), |
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 | ---
+++
@@ -9,3 +9,6 @@
def __unicode__(self):
return self.body
+
+ def __str__(self):
+ return self.body |
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 | ---
+++
@@ -1,8 +1,8 @@
r"""
-============================================
+=============================================
msm - Markov state models (:mod:`pyemma.msm`)
-============================================
+=============================================
.. currentmodule:: pyemma.msm
@@ -11,6 +11,12 @@... |
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 | ---
+++
@@ -14,7 +14,7 @@
__all__ = ()
if pandas is not None:
- from pandas_data import PandasDataFrame
+ from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
@@ -24,9 +24,9 @@
geopandas = None
if geopandas is not None:
- from geopandas_data import Geopanda... |
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 | ---
+++
@@ -4,8 +4,8 @@
load_dotenv(find_dotenv())
-OPS_KEY = os.environ.get("OPS_KEY")
-OPS_SECRET = os.environ.get("OPS_SECRET")
+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['TWITTE... |
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 | ---
+++
@@ -30,6 +30,28 @@
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
+
+ def removeRelation(self, key, className, objectsId):
+ self.manageRelation('RemoveRelation', key, className, objectsId)
+
+ def addRelation(self, key, className... |
d0f4209f373d91a82339ddfc15445e84f4cf0ac8 | oscar_sagepay/config.py | oscar_sagepay/config.py | from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE... | from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE... | Fix typo retrieving vendor prefix | Fix typo retrieving vendor prefix
Properly get the OSCAR_SAGEPAY_TX_CODE_PREFIX from the project settings
| Python | bsd-3-clause | django-oscar/django-oscar-sagepay-direct | ---
+++
@@ -14,5 +14,5 @@
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
-VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEOAY_TX_CODE_PREFIX",
+VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_S... |
fe34b3be69c119729febefd23f80a24203383f8a | pidman/__init__.py | pidman/__init__.py | # Project Version and Author Information
__author__ = "EUL Systems"
__copyright__ = "Copyright 2010, Emory University General Library"
__credits__ = ["Rebecca Koeser", "Ben Ranker", "Alex Thomas", "Scott Turnbull"]
__email__ = "libsys-dev@listserv.cc.emory.edu"
# Version Info, parsed below for actual version number.
_... | Update project version and other metadata from previous | Update project version and other metadata from previous
| Python | apache-2.0 | emory-libraries/pidman,emory-libraries/pidman | ---
+++
@@ -0,0 +1,13 @@
+# Project Version and Author Information
+__author__ = "EUL Systems"
+__copyright__ = "Copyright 2010, Emory University General Library"
+__credits__ = ["Rebecca Koeser", "Ben Ranker", "Alex Thomas", "Scott Turnbull"]
+__email__ = "libsys-dev@listserv.cc.emory.edu"
+
+# Version Info, parsed ... | |
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 | ---
+++
@@ -23,5 +23,13 @@
except BlockingIOError:
pass
+ def bind(self, addr=("", 0)): self.s.bind(addr)
+ def sendto(self, data, addr): self.s.sendto(data, addr)
+ def recvfrom(self, num):
+ try:
+ return self.s.recvfrom(num)
+ except BlockingIOError:
+ return None, None
+
def get_address(sel... |
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... | ---
+++
@@ -7,8 +7,9 @@
def __init__(self, match):
self.match = match
- self._event_feed = match.event.id
- # TODO Add notion of District to Match model?
+ self.event = match.event.get()
+ self._event_feed = self.event.key_name
+ self._district_feed = self.event.even... |
79c12316cf132acdb5e375ea30f1cc67d7fd11ed | thehonestgenepipeline/celeryconfig.py | thehonestgenepipeline/celeryconfig.py | from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='rpc://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('imput... | from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='amqp://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('impu... | Change from rpc to amqp backend | Change from rpc to amqp backend
Otherwise retrieving result are problematic
| Python | mit | TheHonestGene/thehonestgene-pipeline | ---
+++
@@ -1,7 +1,7 @@
from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
-CELERY_RESULT_BACKEND='rpc://'
+CELERY_RESULT_BACKEND='amqp://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json' |
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 | ---
+++
@@ -5,7 +5,6 @@
from . import (
current_dir,
test_dir,
- skip_in_ci,
)
@@ -17,8 +16,7 @@
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
- @skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testsli... |
cabf0004d6e7e3687cdd2ebe9aebeede01877e69 | tests/run_tests.py | tests/run_tests.py | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = '... | Add unit to the test directories | Add unit to the test directories
| Python | bsd-3-clause | jstnlef/pika,reddec/pika,pika/pika,Tarsbot/pika,Zephor5/pika,knowsis/pika,shinji-s/pika,fkarb/pika-python3,vitaly-krugl/pika,vrtsystems/pika,benjamin9999/pika,skftn/pika,renshawbay/pika-python3,hugoxia/pika,zixiliuyue/pika | ---
+++
@@ -15,7 +15,7 @@
if platform == 'darwin':
platform = 'bsd'
-DIRECTORIES = ['functional'] # Unit tests to be added here
+DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS: |
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... | ---
+++
@@ -1,4 +1,4 @@
-from cookiecutter.main import is_repo_url
+from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
@@ -6,7 +6,6 @@
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
... |
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 | ---
+++
@@ -6,7 +6,7 @@
import RDF
-from glharvest import util
+from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
@@ -16,7 +16,7 @@
def test_can_load_a_simple_void_file():
- model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
+ m = u... |
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 | ---
+++
@@ -1,6 +1,8 @@
+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()
@@ -14,10 +16,21 @@
return HttpResponse()
+def verify... |
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 | ---
+++
@@ -7,3 +7,7 @@
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 marginally slower |
16630b23238ee66c8e4ca6017db934befc6ab71e | py/garage/garage/sql/sqlite.py | py/garage/garage/sql/sqlite.py | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(
db_uri, *,
check_same_thread=False,
echo=False,
pragmas=()):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
... | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(
db_uri, *,
check_same_thread=False,
echo=False,
pragmas=()):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
... | Replace double quotes with single quotes | Replace double quotes with single quotes
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | ---
+++
@@ -25,9 +25,9 @@
dbapi_connection.isolation_level = None
# Enable foreign key.
cursor = dbapi_connection.cursor()
- cursor.execute("PRAGMA foreign_keys = ON")
+ cursor.execute('PRAGMA foreign_keys = ON')
for name, value in pragmas:
- cursor.execute... |
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 | ---
+++
@@ -3,11 +3,13 @@
from db.models.repos import CodeReference
-def get_project_code_reference(project, commit=None):
- if not project.has_code:
+def get_code_reference(instance, commit=None, external_repo=None):
+ project = instance.project
+
+ repo = project.repo if project.has_code else external... |
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 | ---
+++
@@ -3,5 +3,4 @@
from access import weights
from access import helpers
from access.datasets import datasets
-from access import access_log_stream
from access import access |
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 | ---
+++
@@ -1,7 +1,7 @@
from __future__ import absolute_import, unicode_literals
import logging
-from io import StringIO
+from io import BytesIO, StringIO
from . import codec
from .file import File
@@ -61,7 +61,9 @@
if stream is None:
stream = StringIO()
- stream = self.codec.co... |
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 | ---
+++
@@ -8,10 +8,10 @@
"""Wrapper around a TinyDB table.
"""
+ setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
- self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
@... |
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 | ---
+++
@@ -20,9 +20,9 @@
api_domain = 'disqus.com'
available_permissions = [
- (None, 'read data on your behalf'),
- ('write', 'read and write data on your behalf'),
- ('admin', 'read and write data on your behalf and moderate your forums'),
+ (None, 'access your contact info'... |
43a2f2f27110f45e8a0d19004dac097ae67949c9 | gunicorn_config.py | gunicorn_config.py | import os
import sys
import traceback
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
workers = 5
worker_class = "eventlet"
errorlog = "/home/vcap/logs/gunicorn_error.log"
bind = "0.0.0.0:{}".format(os.getenv("PORT"))
disable_redirect_access_to_syslog = True
gunicorn.SERVER_SOFTWARE = 'None'
def... | import os
import sys
import traceback
import eventlet
import socket
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
workers = 5
worker_class = "eventlet"
errorlog = "/home/vcap/logs/gunicorn_error.log"
bind = "0.0.0.0:{}".format(os.getenv("PORT"))
disable_redirect_access_to_syslog = True
gunicorn.... | Fix rediss ssl eventlet sslerror bug | Fix rediss ssl eventlet sslerror bug
This is the same as [^1].
I did a test deploy to double check that Redis on PaaS doesn't work
without this.
[^1]: https://github.com/alphagov/notifications-api/pull/3508/commits/a2cbe2032565c61b971659aed28ebd4b096ea87d
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -1,6 +1,8 @@
import os
import sys
import traceback
+import eventlet
+import socket
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
@@ -17,3 +19,21 @@
worker.log.info("worker received ABORT")
for stack in sys._current_frames().values():
worker.log.error(''.join(... |
9691ff0a1fa5fee4895cc5cff33ca169498dbbc6 | encrypt.py | encrypt.py | from PIL import Image
import stepic
import sys
import os
from moviepy.editor import *
import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos")
def encrypt_video(filename, userinfo):
# Orignal Video
original = VideoFileClip(filename+".mp4")
t0 = 56
first_half = VideoFileClip(file... | from PIL import Image
import stepic
import sys
import os
from moviepy.editor import *
import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos")
def encrypt_video(filename, userinfo):
# Orignal Video
original = VideoFileClip(filename+".mp4")
t0 = 56
first_half = VideoFileClip(filen... | Add newline to a file | Add newline to a file
| Python | apache-2.0 | AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp,AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp,tcyrus-hackathon/scurvy-webapp,AntiPiracy/webapp | ---
+++
@@ -4,7 +4,7 @@
import os
from moviepy.editor import *
-import moviepy.editor as mpy
+import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos") |
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 | ---
+++
@@ -1,7 +1,13 @@
-from datetime import date
+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_... |
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 | ---
+++
@@ -8,6 +8,6 @@
LOGIN_URL = '/login'
PAM_SERVICES = {
- 'default': 'curc-twofactor-duo',
+ 'default': 'login',
'csu': 'csu'
} |
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-... | ---
+++
@@ -4,5 +4,5 @@
class PlanForm(forms.Form):
-
+ # pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")]) |
b19330abc312c8bdfa66d46b8ed9f8541a371b6b | fbmsgbot/bot.py | fbmsgbot/bot.py | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient()
def send_message(self, message, completion):
def _completion(response, error):
print error
... | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
print error
... | Fix errors in set_welcome and update for http_client | Fix errors in set_welcome and update for http_client
| Python | mit | ben-cunningham/pybot,ben-cunningham/python-messenger-bot | ---
+++
@@ -7,7 +7,7 @@
def __init__(self, token):
self.api_token = token
- self.client = HttpClient()
+ self.client = HttpClient(token)
def send_message(self, message, completion):
@@ -28,7 +28,6 @@
_completion)
def set_welcome(self, message, completion):
- ... |
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 | ---
+++
@@ -15,17 +15,16 @@
for item in obj:
_to_text(text, item)
- elif isinstance(obj, string_types):
- text.write(obj)
- text.write(u' ')
+ elif isinstance(obj, string_types + integer_types):
+ text.write(u'%s ' % obj)
- elif isinstance(obj, integer_types):
-... |
8ba775d863e269e30ad60e0f449650575e3ff855 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.16.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.16.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.16.1 | Increment version number to 0.16.1
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.16.0"
+__version__ = "0.16.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
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 | ---
+++
@@ -2,17 +2,29 @@
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'k... |
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 | ---
+++
@@ -4,6 +4,18 @@
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,
+ ... |
13d0dfd957c1159c7fe6377637b10996ef91afcd | imhotep/shas.py | imhotep/shas.py | from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo",
('commit', 'origin', 'remote_repo', 'ref'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
retur... | from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo",
('commit', 'origin', 'remote_repo', 'ref'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
retur... | Use github's `clone_url` instead of mandating ssh. | Use github's `clone_url` instead of mandating ssh.
| Python | mit | richtier/imhotep,justinabrahms/imhotep,justinabrahms/imhotep | ---
+++
@@ -35,7 +35,7 @@
remote = None
if self.has_remote_repo:
remote = Remote(name=self.json['head']['repo']['owner']['login'],
- url=self.json['head']['repo']['ssh_url'])
+ url=self.json['head']['repo']['clone_url'])
ret... |
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 | ---
+++
@@ -1,16 +1,10 @@
-#!/usr/bin/env python
-""" Extracts the version of the khmer project. """
+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 =... |
c07f9d2b455ec312d22a5aa07f9d724ee4cd1e42 | grab/tools/logs.py | grab/tools/logs.py | import logging
def default_logging(grab_log='/tmp/grab.log'):
"""
Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file.
"""
logging.basicConfig(level=logging.DEBUG)
glog = logging.getLogger('grab')
glog.propagate = False
... | import logging
def default_logging(grab_log='/tmp/grab.log', level=logging.DEBUG, mode='a'):
"""
Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file.
"""
logging.basicConfig(level=level)
glog = logging.getLogger('grab')
g... | Create additional options for default_logging function | Create additional options for default_logging function
| Python | mit | SpaceAppsXploration/grab,maurobaraldi/grab,giserh/grab,lorien/grab,SpaceAppsXploration/grab,subeax/grab,huiyi1990/grab,raybuhr/grab,DDShadoww/grab,codevlabs/grab,pombredanne/grab-1,liorvh/grab,lorien/grab,DDShadoww/grab,huiyi1990/grab,codevlabs/grab,alihalabyah/grab,liorvh/grab,maurobaraldi/grab,subeax/grab,istinspring... | ---
+++
@@ -1,6 +1,6 @@
import logging
-def default_logging(grab_log='/tmp/grab.log'):
+def default_logging(grab_log='/tmp/grab.log', level=logging.DEBUG, mode='a'):
"""
Customize logging output to display all log messages
except grab network logs.
@@ -8,9 +8,9 @@
Redirect grab network logs int... |
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... | ---
+++
@@ -9,6 +9,7 @@
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
+ title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self): |
227244ae21c98b52a460beb942a8200ab66c0633 | grappa/__init__.py | grappa/__init__.py | # -*- coding: utf-8 -*
"""
`grappa` provides two different testing styles: `should` and `expect`.
should
------
Example using ``should`` style::
from grappa import should
should('foo').be.equal.to('foo')
'foo' | should.be.equal.to('foo')
expect
------
Example using ``expect`` style::
from grappa ... | # -*- coding: utf-8 -*
"""
`grappa` provides two different testing styles: `should` and `expect`.
should
------
Example using ``should`` style::
from grappa import should
should('foo').be.equal.to('foo')
'foo' | should.be.equal.to('foo')
expect
------
Example using ``expect`` style::
from grappa ... | Bump version: 0.1.8 → 0.1.9 | Bump version: 0.1.8 → 0.1.9
| Python | mit | grappa-py/grappa | ---
+++
@@ -40,4 +40,4 @@
__license__ = 'MIT'
# Current package version
-__version__ = '0.1.8'
+__version__ = '0.1.9' |
4ca82986828514f26d06270477a2d243ebd91294 | tests/hummus/test_document.py | tests/hummus/test_document.py | # -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
... | # -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
... | Update tests for new API. | Update tests for new API.
| Python | mit | concordusapps/python-hummus,concordusapps/python-hummus | ---
+++
@@ -12,7 +12,7 @@
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
- document = hummus.Document(filename=stream.name)
+ document = hummus.Document(stream.name)
document.begin()
document.end()
|
58eede75663fda02a7323fa6579a6ca8ac83f2fd | belogging/defaults.py | belogging/defaults.py |
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'... |
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'... | Replace %(module)s with %(pathname)s in DEFAULT_KVP_FORMAT | Replace %(module)s with %(pathname)s in DEFAULT_KVP_FORMAT
The pathname gives more context in large projects that contains repeated module
names (eg models, base, etc).
| Python | mit | georgeyk/belogging | ---
+++
@@ -29,7 +29,7 @@
}
-DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s module=%(module)s line=%(lineno)s message=%(message)s'
+DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60, |
273dd930836345fccc42e8f1a6720f04b29a46f1 | pytui/settings.py | pytui/settings.py | from __future__ import unicode_literals
DEBUG_MODULES = [
# 'pytui',
]
VERSION = '0.3.1b'
| from __future__ import unicode_literals
DEBUG_MODULES = [
# 'pytui',
]
VERSION = '0.3.1b0'
| Repair version, beta needs a number. | Repair version, beta needs a number.
| Python | mit | martinsmid/pytest-ui | ---
+++
@@ -3,4 +3,4 @@
# 'pytui',
]
-VERSION = '0.3.1b'
+VERSION = '0.3.1b0' |
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 | ---
+++
@@ -1,7 +1,7 @@
# 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"],
+ builderNames=["package_osx... |
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 | ---
+++
@@ -15,6 +15,7 @@
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
+ ('503', 'East Riding of Yorkshire Council'),
]
|
73dd57a0d27b08089f91f303d3d36e428b108618 | CI/syntaxCheck.py | CI/syntaxCheck.py | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... | Revert "Fix the location path of OpenIPSL" | Revert "Fix the location path of OpenIPSL"
This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
| Python | bsd-3-clause | SmarTS-Lab/OpenIPSL,OpenIPSL/OpenIPSL,SmarTS-Lab/OpenIPSL,tinrabuzin/OpenIPSL | ---
+++
@@ -18,7 +18,7 @@
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
-passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")
+passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL |
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 | ---
+++
@@ -24,21 +24,24 @@
return text
-sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-socket_name = '/tmp/cachebrowser.sock'
-sock.connect(socket_name)
+# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+# socket_name = '/tmp/cachebrowser.sock'
+# sock.connect(socket_name)
+sock = socke... |
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 | ---
+++
@@ -9,7 +9,8 @@
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
- self.pieces_needed = needed.reverse
+ self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
+ self.pieces_needed.reverse()
self.cut_l... |
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 | ---
+++
@@ -1,5 +1,8 @@
"""Python script to run all tests"""
+import sys
+
import pytest
+
if __name__ == '__main__':
- pytest.main()
+ sys.exit(pytest.main()) |
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 | ---
+++
@@ -7,9 +7,13 @@
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ assert humanize.ordinal(5) == "5th"
- humanize.i18n.activate("ru_RU")
- assert humanize.naturaltime(three_seconds) == "3 секунды назад"
-
- humanize.i18n.deactivat... |
7cde727c5a1a5de652e6b1c3d207c5b51fe719cf | mission.py | mission.py | # coding: utf-8
"""
Mission simulation.
"""
from rover import Plateau, Rover, Heading, Command
if __name__ == '__main__':
instructions = open('instructions.txt', 'r')
# Prepare the plateau to landings.
data = instructions.readline().split()
x, y = map(int, data)
plateau = Plateau(x, y)
# D... | # coding: utf-8
"""
Mission simulation.
"""
from rover import Plateau, Rover, Heading, Command
if __name__ == '__main__':
instructions = open('instructions.txt', 'r')
# Prepare the plateau to landings.
data = instructions.readline().split()
x, y = map(int, data)
plateau = Plateau(x, y)
# D... | Fix to deal with invalid commands. | Fix to deal with invalid commands.
| Python | mit | rodrigobraga/Mars-Rover-Challenge | ---
+++
@@ -23,7 +23,7 @@
# Parse and run instructions.
commands = instructions.readline().strip()
for cmd in commands:
- command = getattr(Command, cmd)
+ command = getattr(Command, cmd, None)
rover.execute(command)
print(rover) |
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 | ---
+++
@@ -26,7 +26,9 @@
for line in f:
line = line.rstrip()
for key in line:
- if ping.match(mydict[key]):
+ if key not in mydict:
+ print key
+ elif ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.