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 |
|---|---|---|---|---|---|---|---|---|---|---|
7fc58c651ea4d2d9db8b37a9f9768cecc834b225 | primestg/__init__.py | primestg/__init__.py | try:
__version__ = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
__version__ = 'unknown'
| import os
try:
__version__ = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
__version__ = 'unknown'
_ROOT = os.path.abspath(os.path.dirname(__file__))
def get_data(path):
filename = isinstance(path, (list, tuple)) and path[0] or path
return os.path.joi... | Add function to get relative path in repository | Add function to get relative path in repository
| Python | agpl-3.0 | gisce/primestg | ---
+++
@@ -1,5 +1,14 @@
+import os
+
try:
__version__ = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
__version__ = 'unknown'
+
+_ROOT = os.path.abspath(os.path.dirname(__file__))
+
+
+def get_data(path):
+ filename = isinstance(path, (list, tuple)) an... |
2d0ad125a63592fc64c52432fc8e697c681f465c | webapp/element43/apps/auth/urls.py | webapp/element43/apps/auth/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('apps.auth.views',
#
# Authentication and Registration URLs
#
# Registration
url(r'^register/activate/(?P<key>[a-zA-Z0-9]+)/$', 'activate', name='activate_account'),
url(r'^register/$', 'register', name='registration'),
# P... | from django.conf.urls import patterns, url
urlpatterns = patterns('apps.auth.views',
#
# Authentication and Registration URLs
#
# Registration
url(r'^register/activate/(?P<key>[a-zA-Z0-9-]+)/$', 'activate', name='activate_account'),
url(r'^register/$', 'register', name='registration'),
# ... | Allow a hypen in activation URL | Allow a hypen in activation URL
Make activation work with my login (ei-grad).
| Python | bsd-3-clause | EVE-Tools/element43,EVE-Tools/element43 | ---
+++
@@ -6,7 +6,7 @@
#
# Registration
- url(r'^register/activate/(?P<key>[a-zA-Z0-9]+)/$', 'activate', name='activate_account'),
+ url(r'^register/activate/(?P<key>[a-zA-Z0-9-]+)/$', 'activate', name='activate_account'),
url(r'^register/$', 'register', name='registration'),
# Password... |
57170909979d89c6887fde80510855c2ea4770e9 | django_prometheus/__init__.py | django_prometheus/__init__.py | """Django-Prometheus
https://github.com/korfuri/django-prometheus
"""
# Import all files that define metrics. This has the effect that
# `import django_prometheus` will always instanciate all metric
# objects right away.
import django_prometheus.middleware
import django_prometheus.models
# Import pip_prometheus to e... | """Django-Prometheus
https://github.com/korfuri/django-prometheus
"""
# Import all files that define metrics. This has the effect that
# `import django_prometheus` will always instanciate all metric
# objects right away.
import django_prometheus.middleware
import django_prometheus.models
# Import pip_prometheus to e... | Make the use of pip-prometheus optional. | Make the use of pip-prometheus optional.
| Python | apache-2.0 | obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,korfuri/django-prometheus | ---
+++
@@ -10,6 +10,10 @@
import django_prometheus.models
# Import pip_prometheus to export the pip metrics automatically.
-import pip_prometheus
+try:
+ import pip_prometheus
+except ImportError:
+ # If people don't have pip, don't export anything.
+ pass
default_app_config = 'django_prometheus.apps... |
343fadde748aa66d17d21d79cb481c9c09782466 | search/signals.py | search/signals.py | from django.dispatch import Signal, receiver
from django.core.mail import EmailMultiAlternatives
from search.models import Person
import logging
from django.conf import settings
unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags'])
logger = logging.getLogger('search')
@receiver(unknown_tag_signal)
... | from django.dispatch import Signal, receiver
from django.core.mail import EmailMultiAlternatives
from search.models import Person
import logging
from django.conf import settings
unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags'])
logger = logging.getLogger('search')
@receiver(unknown_tag_signal)
... | Fix unicode issues with new tag | Fix unicode issues with new tag
| Python | agpl-3.0 | ictofnwi/steep,ictofnwi/steep,ictofnwi/steep,ictofnwi/steep | ---
+++
@@ -14,7 +14,7 @@
title = kwargs['title']
unknown_tags = kwargs['tags']
message = "Dear moderator,\n\n" + \
- "{person} created an item '{title}' ".format(person=author.name,
+ u"{person} created an item '{title}' ".format(person=author.name,
... |
9abce17371ac1b2a0e29a90b39ce8560f05bf47e | pastas/version.py | pastas/version.py | # This is the only location where the version will be written and changed.
# Based on https://packaging.python.org/single_source_version/
__version__ = '0.12.0b'
| # This is the only location where the version will be written and changed.
# Based on https://packaging.python.org/single_source_version/
__version__ = '0.12.0'
| Prepare update Master to 0.12.0 | Prepare update Master to 0.12.0
| Python | mit | gwtsa/gwtsa,pastas/pastas,pastas/pasta | ---
+++
@@ -1,3 +1,3 @@
# This is the only location where the version will be written and changed.
# Based on https://packaging.python.org/single_source_version/
-__version__ = '0.12.0b'
+__version__ = '0.12.0' |
55d372b4887bc9461d9e5ea958a5703ed19bdcae | frontend/checkFrontend.py | frontend/checkFrontend.py | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = config file
#
# Author:
# Igor Sfiligoi Jul 17th 2008
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
config_dict={}
try:
execfile(sys.argv[1],config_dict)
... | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = work_dir
#
# Author:
# Igor Sfiligoi
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
try:
work_dir=sys.argv[1]
frontend_pid=glideinFrontendPidLib.get_fr... | Rewrite based on factory one | Rewrite based on factory one
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS | ---
+++
@@ -4,21 +4,19 @@
# Check if a glideinFrontend is running
#
# Arguments:
-# $1 = config file
+# $1 = work_dir
#
# Author:
-# Igor Sfiligoi Jul 17th 2008
+# Igor Sfiligoi
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
-config_dict={... |
9a23ef917dbd22ad30237ca51ed4d5d43b1bfa4d | python/mia_server.py | python/mia_server.py | #!/usr/bin/env python
HOST = ''
PORT = 4080
def mia_server_start():
pass
if __name__ == "__main__":
mia_server_start()
| #!/usr/bin/env python
HOST = ''
PORT = 4080
DEBUG = True
def handle_packet(sock, addr, data):
if data.startswith("REGISTER;"):
response = register_player(data, addr)
elif data.startswith("REGISTER_SPECTATOR"):
response = register_spectator(data, addr)
if response:
if DEBUG: print "Replying '",resp... | Add python mia server UDP loop | Add python mia server UDP loop
| Python | mit | SteffenBauer/mia_elixir,SteffenBauer/mia_elixir | ---
+++
@@ -3,8 +3,33 @@
HOST = ''
PORT = 4080
+DEBUG = True
+
+def handle_packet(sock, addr, data):
+ if data.startswith("REGISTER;"):
+ response = register_player(data, addr)
+ elif data.startswith("REGISTER_SPECTATOR"):
+ response = register_spectator(data, addr)
+
+ if response:
+ if DEBUG: print ... |
ef8452020c95b08fa8aed9840a7e0cb94eaec514 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | Change url of the website | Change url of the website
| Python | agpl-3.0 | xcgd/document_attachment | ---
+++
@@ -15,7 +15,7 @@
changed to work like a one2many field by using the
"domain="[('res_id', '=', id)]" attribute.
""",
- 'website': 'http://www.openerp-experts.com',
+ 'website': 'www.odoo.consulting/',
'depends': [
'base',
'document', |
fae501041857f1e4eea2b5157feb94a3f3c84f18 | pinax/__init__.py | pinax/__init__.py | VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
return version
__version__ = get_versi... | import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PI... | Support development versions using an environment variable | Support development versions using an environment variable
| Python | mit | amarandon/pinax,amarandon/pinax,amarandon/pinax,amarandon/pinax | ---
+++
@@ -1,3 +1,6 @@
+import os
+
+
VERSION = (0, 9, 0, "a", 1) # following PEP 386
@@ -7,6 +10,9 @@
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
+ dev = os.environ.get("PINAX_DEV_N")
+ if dev:
+ ... |
ab3b2e9a681740159897ef8592c4f891df791119 | publisher_test_project/manage.py | publisher_test_project/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python3
import os
import sys
print("sys.real_prefix:", getattr(sys, "real_prefix", "-"))
print("sys.prefix:", sys.prefix)
if __name__ == "__main__":
if "VIRTUAL_ENV" not in os.environ:
raise RuntimeError(" *** ERROR: Virtual env not activated! *** ")
os.environ.setdefault("DJANGO_SETT... | Raise error if virtualenv not activated | Raise error if virtualenv not activated
| Python | bsd-3-clause | wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai | ---
+++
@@ -1,8 +1,15 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
+
import os
import sys
+print("sys.real_prefix:", getattr(sys, "real_prefix", "-"))
+print("sys.prefix:", sys.prefix)
+
if __name__ == "__main__":
+ if "VIRTUAL_ENV" not in os.environ:
+ raise RuntimeError(" *** ERROR: Virtual env ... |
daeda47aa33abad38f8f93ef9dde261809171c9b | podcasts/models.py | podcasts/models.py | from django.db import models
class Podcast(models.Model):
title = models.CharField(max_length=100, blank=True)
link = models.URLField(blank=True)
feed = models.URLField()
description = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.title
def title_or_unna... | from django.db import models
class Podcast(models.Model):
title = models.CharField(max_length=100, blank=True)
link = models.URLField(blank=True)
feed = models.URLField()
description = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.title
def title_or_unna... | Make so an episode link isn't mandatory | Make so an episode link isn't mandatory
| Python | mit | matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik | ---
+++
@@ -16,6 +16,6 @@
class Episode(models.Model):
title = models.CharField(max_length=200)
- link = models.URLField()
+ link = models.URLField(blank=True)
description = models.TextField(blank=True)
podcast = models.ForeignKey(Podcast) |
e49cd7aeaf81ed12490d82b8a65ca93088ec916e | spacy/__init__.py | spacy/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .cli.info import info as cli_info
from .glossary import explain
from .deprecated import resolve_load_name
from .about import __version__
from . import util
def load(name, **overrides):
name = resolve_load_name(name, **overrides)
return util.load_mod... | # coding: utf8
from __future__ import unicode_literals
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from . import util
def load(name, **overrides):
from .deprecated import resolve_load_name
name = resolve_load_name(name, **overrides)
return util.load... | Move import into load to avoid circular imports | Move import into load to avoid circular imports
| Python | mit | aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,honnibal/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaC... | ---
+++
@@ -3,12 +3,12 @@
from .cli.info import info as cli_info
from .glossary import explain
-from .deprecated import resolve_load_name
from .about import __version__
from . import util
def load(name, **overrides):
+ from .deprecated import resolve_load_name
name = resolve_load_name(name, **overr... |
5b1eee618e57cd3cd84df4b819ef69876db55ddf | clock.py | clock.py | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', min... | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', min... | Change interval: 10 -> 20 | Change interval: 10 -> 20
| Python | mit | oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije | ---
+++
@@ -19,7 +19,7 @@
shell=True)
-@scheduler.scheduled_job('interval', minutes=10)
+@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call( |
c54240e6d9f6393370fe94f2cd05476680cf17f2 | pygtfs/__init__.py | pygtfs/__init__.py | from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__
| import warnings
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
try:
from ._version import version as __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
| Allow usage directly from the code (fix the _version import) | Allow usage directly from the code (fix the _version import)
| Python | mit | jarondl/pygtfs | ---
+++
@@ -1,3 +1,10 @@
+import warnings
+
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
-from ._version import version as __version__
+
+try:
+ from ._version import version as __version__
+except ImportError:
+ warnings.warn("pygtfs should be instal... |
215746e2fd7e5f78b6dae031aae6a935ab164dd1 | pyjokes/pyjokes.py | pyjokes/pyjokes.py | from __future__ import absolute_import
import random
import importlib
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
... | from __future__ import absolute_import
import random
from .jokes_en import jokes as jokes_en
from .jokes_de import jokes as jokes_de
from .jokes_es import jokes as jokes_es
all_jokes = {
'en': jokes_en,
'de': jokes_de,
'es': jokes_es,
}
class LanguageNotFoundError(Exception):
pass
class CategoryN... | Use dict not if/else, add exceptions | Use dict not if/else, add exceptions
| Python | bsd-3-clause | borjaayerdi/pyjokes,birdsarah/pyjokes,pyjokes/pyjokes,bennuttall/pyjokes,trojjer/pyjokes,gmarkall/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes | ---
+++
@@ -1,6 +1,25 @@
from __future__ import absolute_import
import random
-import importlib
+
+from .jokes_en import jokes as jokes_en
+from .jokes_de import jokes as jokes_de
+from .jokes_es import jokes as jokes_es
+
+
+all_jokes = {
+ 'en': jokes_en,
+ 'de': jokes_de,
+ 'es': jokes_es,
+}
+
+
+class... |
52a2b6c8ac87678202634806d9a7f570eab5b8bb | mysite/urls.py | mysite/urls.py | from django.conf.urls.defaults import *
import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^search/$', 'mysite.search.views.fetch_bugs'),
(r'^admin/(.*)', admin.site.root),
(r'^static/(?P<path>.*)$', 'djan... | from django.conf.urls.defaults import *
import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^search/$', 'mysite.search.views.fetch_bugs'),
(r'^admin/(.*)', admin.site.root),
(r'^static/(?P<path>.*)$', 'djan... | Make front page be == /search/ | Make front page be == /search/
| Python | agpl-3.0 | willingc/oh-mainline,mzdaniel/oh-mainline,onceuponatimeforever/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,heeraj123/oh-mainline,campbe13/openhatch,waseem18/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,ojengwa/oh-mainline,vipul-sharma2... | ---
+++
@@ -10,4 +10,7 @@
(r'^admin/(.*)', admin.site.root),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
+ (r'^$', 'mysite.search.views.fetch_bugs'),
)
+
+ |
b4fbb4784b61001cc29c311e3b50c3fad3c60ef0 | nipap/setup.py | nipap/setup.py | #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__aut... | #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__aut... | Change installation path for nipap-passwd | Change installation path for nipap-passwd
This really is a "admin tool" and so we put it in /usr/sbin instead!
Fixes #196
| Python | mit | SpriteLink/NIPAP,garberg/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,fredsod/NIPAP,fredsod/NIPAP,bbaja42/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,garberg/NIPAP,plajjan/NIPAP,plajjan/NIPAP,SoundGoof/NIPAP,plajjan/NIPAP,bbaja42/NIPAP,bbaja42... | ---
+++
@@ -21,8 +21,7 @@
requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'],
data_files = [
('/etc/nipap/', ['local_auth.db', 'nipap.conf']),
- ('/usr/bin/', ['nipap-passwd']),
- ('/usr/sbin/', ['nipapd']),
+ ('/usr/sbin/', ['nipapd', 'nipap-passwd']),
('/usr/share/nipap/sql/',... |
2e941cf1f6208b9ac2f6039681c24502b324ab5f | planner/models.py | planner/models.py | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugF... | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugF... | Add Semester str method for admin interface. | Add Semester str method for admin interface.
Fixes #149
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | ---
+++
@@ -20,9 +20,13 @@
return self.name
+@python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
+
+ def __str__(self):
+ return str(self.date)
# XXX: This is locked in for the default value of the initi... |
fd5810c86f5998c2e2a7b96f09e82b40fbe2cc11 | string/first-str-substr-occr.py | string/first-str-substr-occr.py | # Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1
def find_substring(string, substr):
string_len = len(... | # Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1
def find_substring(string, substr):
string_len = len(... | Return -1 if no substring is found | Return -1 if no substring is found
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -15,3 +15,5 @@
else:
j = 0
i += 1
+
+ return -1 |
0994fb6a8c924e907151764f9c1eaa19f2c3aea7 | salt/returners/syslog_return.py | salt/returners/syslog_return.py | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... | Remove redundant text from syslog returner | Remove redundant text from syslog returner
The implicit call to syslog.openlog will already add salt-minion (technically `sys.argv[0]`) to the syslog.syslog call. It's redundant (and not technically correct) to have salt-minion here.
Can also be applied to 2015.8 and develop without issue.
Fixes #27756 | Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -41,7 +41,7 @@
'''
Return data to the local syslog
'''
- syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret)))
+ syslog.syslog(syslog.LOG_INFO, '{0}'.format(json.dumps(ret)))
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument |
c9880fa56a6667d79bfc28fe4091f1cdbf3b2210 | teknologr/registration/views.py | teknologr/registration/views.py | from django.shortcuts import render, redirect
from django.conf import settings
from django.views import View
from members.programmes import DEGREE_PROGRAMME_CHOICES
from registration.forms import RegistrationForm
from registration.mailutils import mailApplicantSubmission
class BaseView(View):
context = {'DEBUG': ... | from django.shortcuts import render, redirect
from django.conf import settings
from django.views import View
from members.programmes import DEGREE_PROGRAMME_CHOICES
from registration.forms import RegistrationForm
from registration.mailutils import mailApplicantSubmission
class BaseView(View):
context = {'DEBUG': ... | Fix serialization issue with form submission | Fix serialization issue with form submission
| Python | mit | Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io | ---
+++
@@ -34,16 +34,18 @@
if form.is_valid():
registration = form.instance
- self.context['name'] = registration.preferred_name or registration.given_names.split(' ')[0]
- self.context['email'] = registration.email
+ next_context = {
+ 'name': ... |
2fc13f58d8deba0f34c1e33ed78884630e8a7804 | pages/tests.py | pages/tests.py | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed correctly
"""
c = Client()
c.login(... | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.l... | Add a create page test | Add a create page test
git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@300 439a9e5f-3f3e-0410-bc46-71226ad0111b
| Python | bsd-3-clause | akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,ba... | ---
+++
@@ -1,4 +1,5 @@
from django.test import TestCase
+
from pages.models import *
from django.test.client import Client
@@ -7,10 +8,20 @@
def test_01_add_page(self):
"""
- Test that the add admin page could be displayed correctly
+ Test that the add admin page could be displayed... |
ed71dc1e9163c5a7a7b0f623ea75393286804138 | dbsettings/utils.py | dbsettings/utils.py | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... | Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals. | Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals.
| Python | bsd-3-clause | johnpaulett/django-dbsettings,nwaxiomatic/django-dbsettings,MiriamSexton/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,nwaxiomatic/django-dbsettings,sciyoshi/django-dbsettings,helber/django-dbsettings,DjangoAdminHackers/django-dbsettings,helber/django-dbsettings,zlorf/django-dbsettings,... | ---
+++
@@ -22,4 +22,4 @@
except:
raise ImproperlyConfigured("%s requires dbsettings." % app_label)
- signals.post_syncdb.connect(install_settings, sender=app)
+ signals.post_syncdb.connect(install_settings, sender=app, weak=False) |
2bf5809b651bc85e922c853d2dab27d35fee85b8 | test/bibliopixel/threads/sub_test.py | test/bibliopixel/threads/sub_test.py | import functools, time, unittest
from bibliopixel.util.threads import sub
WAIT_FOR_SUB = 0.1
def pause(delay=0.01):
time.sleep(delay)
def run(input, output, *arg, **kwds):
pause()
output.put('first')
if arg != (1, 2, 3):
raise ValueError('1 2 3')
if kwds != dict(a=1):
raise V... | import functools, time, unittest
from bibliopixel.util.threads import sub
from .. import mark_tests
WAIT_FOR_SUB = 0.1
def pause(delay=0.01):
time.sleep(delay)
def run(input, output, *arg, **kwds):
pause()
output.put('first')
if arg != (1, 2, 3):
raise ValueError('1 2 3')
if kwds != ... | Disable one test in windows-only | Disable one test in windows-only
| Python | mit | ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel | ---
+++
@@ -1,5 +1,6 @@
import functools, time, unittest
from bibliopixel.util.threads import sub
+from .. import mark_tests
WAIT_FOR_SUB = 0.1
@@ -34,6 +35,7 @@
pause(WAIT_FOR_SUB)
self.assertFalse(s.is_alive())
+ @mark_tests.fails_on_windows
def test_subprocess(self):
sel... |
77136f1c7dc6159a040c17cf5143bea14e9462b3 | housing/listings/forms.py | housing/listings/forms.py | from django import forms
from .models import Listing, HousingUser
class ListingForm(forms.ModelForm):
furnished_details = forms.CharField(widget=forms.Textarea(attrs={
"placeholder": "Example: bed and desk only"}))
additional_lease_terms = forms.CharField(required=False,
widget=forms.Textarea(a... | from django import forms
from .models import Listing, HousingUser
class ListingForm(forms.ModelForm):
furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={
"placeholder": "Example: bed and desk only"}))
additional_lease_terms = forms.CharField(required=False,
widget=... | Update newListing no longer require furnishing detail | Update newListing no longer require furnishing detail
| Python | mit | xyb994/housing,xyb994/housing,xyb994/housing,xyb994/housing | ---
+++
@@ -2,7 +2,7 @@
from .models import Listing, HousingUser
class ListingForm(forms.ModelForm):
- furnished_details = forms.CharField(widget=forms.Textarea(attrs={
+ furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={
"placeholder": "Example: bed and desk only"}))... |
a1bfb35bb5865cc45aded58b7cffab6da7cc0baf | pykeg/settings.py | pykeg/settings.py | # Pykeg main settings file.
# Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in
# common_settings.py.example.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.... | # Pykeg main settings file.
# Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in
# common_settings.py.example.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.... | Add twitter to default apps. | Add twitter to default apps.
| Python | mit | Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server | ---
+++
@@ -11,6 +11,7 @@
'django.contrib.humanize',
'django.contrib.markup',
'pykeg.core',
+ 'pykeg.contrib.twitter',
)
AUTH_PROFILE_MODULE = "core.UserProfile" |
509ca9c2cad65b47e1a2a16a0c169434620b8c74 | mla_game/apps/transcript/management/commands/scrape_archive.py | mla_game/apps/transcript/management/commands/scrape_archive.py | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup arc... | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup arc... | Test for transcript before scraping from PUA | Test for transcript before scraping from PUA
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt | ---
+++
@@ -19,8 +19,11 @@
settings.PUA_SECRET,
)
for collection in client.get_collections():
- logger.info('collection id: ' + str(collection['id']))
+ logger.info('processing collection id: ' + str(collection['id']))
for item_id in collection['item_i... |
eeaa4251234cfbbefc8f24e7cba22d330d98eefc | cloudbaseinit/shell.py | cloudbaseinit/shell.py | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | Make the multithreaded coinitialize only on 64bit | Make the multithreaded coinitialize only on 64bit
Change-Id: I5d44efb634051f00cd3ca54b99ce0dea806543be
| Python | apache-2.0 | alexpilotti/cloudbase-init,ader1990/cloudbase-init,stefan-caraiman/cloudbase-init,cmin764/cloudbase-init,openstack/cloudbase-init,stackforge/cloudbase-init | ---
+++
@@ -12,11 +12,15 @@
# License for the specific language governing permissions and limitations
# under the License.
+import struct
import sys
-import pythoncom
-sys.coinit_flags = pythoncom.COINIT_MULTITHREADED
-pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
+if struct.calcsize("P") == 8... |
56a76b9dc0745d22d9b1eac54348d6109dc3c0e1 | src/funding/urls.py | src/funding/urls.py | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.CurrentView.as_view(), name='funding_current'),
path('teraz/', vi... | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from annoy.utils import banner_exempt
from . import views
urlpatterns = [
path('', banner_exempt(views.CurrentView.as_vi... | Disable banners on funding pages. | Disable banners on funding pages.
| Python | agpl-3.0 | fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury | ---
+++
@@ -2,21 +2,22 @@
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
+from annoy.utils import banner_exempt
from . import views
urlpatterns = [
- path('', views.CurrentView.as_view(), name='funding_current'),
- path('teraz/', views... |
4927a1c29d258b1ab7c70ffecff6904b808480eb | bokeh/validation/warnings.py | bokeh/validation/warnings.py | ''' Define standard warning codes and messages for Bokeh validation checks.
1000 : *MISSING_RENDERERS*
A |Plot| object has no renderers configured (will result in a blank plot).
1001 : *NO_GLYPH_RENDERERS*
A |Plot| object has no glyph renderers (will result in an empty plot frame).
1002 : *EMPTY_LAYOUT*
... | ''' Define standard warning codes and messages for Bokeh validation checks.
1000 : *MISSING_RENDERERS*
A |Plot| object has no renderers configured (will result in a blank plot).
1001 : *NO_GLYPH_RENDERERS*
A |Plot| object has no glyph renderers (will result in an empty plot frame).
1002 : *EMPTY_LAYOUT*
... | Add module level documentation for colon warning | Add module level documentation for colon warning
| Python | bsd-3-clause | ericmjl/bokeh,timsnyder/bokeh,draperjames/bokeh,philippjfr/bokeh,mindriot101/bokeh,aavanian/bokeh,aavanian/bokeh,phobson/bokeh,daodaoliang/bokeh,KasperPRasmussen/bokeh,rothnic/bokeh,dennisobrien/bokeh,phobson/bokeh,DuCorey/bokeh,timsnyder/bokeh,jplourenco/bokeh,ericdill/bokeh,srinathv/bokeh,bokeh/bokeh,srinathv/bokeh,j... | ---
+++
@@ -9,17 +9,20 @@
1002 : *EMPTY_LAYOUT*
A layout model has no children (will result in a blank layout).
+1003 : *COLON_IN_CATEGORY_LABEL*
+ Category label contains colons (will result in a blank layout).
+
9999 : *EXT*
Indicates that a custom warning check has failed.
'''
codes = {
- ... |
d8a46686f12de76381bf9c2cfde0e9482acc2259 | Toolkit/PlayPen/rooster.py | Toolkit/PlayPen/rooster.py | import os
import sys
import math
def main():
# do while len(spot.xds) > 100 (say)
# index, no unit cell / symmetry set
# copy out indexed spots, orientation matrix
# done
# compare list of orientation matrices - how are they related?
# graphical representation?
| import os
import sys
import math
import shutil
def split_spot_file(j):
'''Split the spot file into those which have been indexed (goes to SPOT.j)
and those which have not, which gets returned to SPOT.XDS. Returns number
of unindexed reflections.'''
spot_j = open('SPOT.%d' % j, 'w')
spot_0 = open('... | Make a start on the recursive reindexing | Make a start on the recursive reindexing | Python | bsd-3-clause | xia2/xia2,xia2/xia2 | ---
+++
@@ -1,13 +1,95 @@
import os
import sys
import math
+import shutil
+
+def split_spot_file(j):
+ '''Split the spot file into those which have been indexed (goes to SPOT.j)
+ and those which have not, which gets returned to SPOT.XDS. Returns number
+ of unindexed reflections.'''
+
+ spot_j = open(... |
2e1d1e5914d853a4da55dd0c8ea534df396697a0 | coop_cms/forms/__init__.py | coop_cms/forms/__init__.py | # -*- coding: utf-8 -*-
# This can be imported directly from coop_cms.forms
from coop_cms.forms.articles import ArticleForm, ArticleSettingsForm, NewArticleForm
from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm
__all__ = ['ArticleForm', 'ArticleSettingsForm', 'NewArticleForm', 'NewsletterF... | # -*- coding: utf-8 -*-
# This can be imported directly from coop_cms.forms
from coop_cms.forms.articles import (
ArticleForm, ArticleAdminForm, ArticleSettingsForm, NewArticleForm, BaseArticleAdminForm
)
from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm
__all__ = [
'ArticleForm', ... | Add more forms to the publics | Add more forms to the publics
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms | ---
+++
@@ -1,7 +1,12 @@
# -*- coding: utf-8 -*-
# This can be imported directly from coop_cms.forms
-from coop_cms.forms.articles import ArticleForm, ArticleSettingsForm, NewArticleForm
+from coop_cms.forms.articles import (
+ ArticleForm, ArticleAdminForm, ArticleSettingsForm, NewArticleForm, BaseArticleAdmi... |
e3ae701be163ccff7e2f64721752b0374dffdfc1 | rosie/chamber_of_deputies/tests/test_dataset.py | rosie/chamber_of_deputies/tests/test_dataset.py | import os.path
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
temp_path = mkdtemp()
... | import shutil
import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
self.temp_path = mkdtemp()
fixtures = os.path.join('rosi... | Fix companies path in Chamber of Deputies dataset test | Fix companies path in Chamber of Deputies dataset test
| Python | mit | marcusrehm/serenata-de-amor,datasciencebr/rosie,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor | ---
+++
@@ -1,25 +1,31 @@
-import os.path
+import shutil
+import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
-from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(Te... |
cf60277951c7c4a23fe8672f5c21ed2ee8a7a0ee | birdseye/ipython.py | birdseye/ipython.py | import inspect
import socket
import sys
from io import BytesIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import server, eye
thread_proxies = {}
def stream_proxy(original)... | import inspect
import socket
import sys
from io import BytesIO, StringIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import eye, PY2
from birdseye.server import app
fake_stre... | Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook | Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook
| Python | mit | alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye | ---
+++
@@ -1,14 +1,17 @@
import inspect
import socket
import sys
-from io import BytesIO
+from io import BytesIO, StringIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
-from bird... |
8aeee881bb32935718e767114256179f9c9bf216 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py | import pytest
from django.test import RequestFactory
from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet
from {{ cookiecutter.project_slug }}.users.models import User
pytestmark = pytest.mark.django_db
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
... | import pytest
from django.test import RequestFactory
from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet
from {{ cookiecutter.project_slug }}.users.models import User
pytestmark = pytest.mark.django_db
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
... | Remove email from User API Test | Remove email from User API Test | Python | bsd-3-clause | ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-djang... | ---
+++
@@ -28,7 +28,6 @@
assert response.data == {
"username": user.username,
- "email": user.email,
"name": user.name,
"url": f"http://testserver/api/users/{user.username}/",
} |
8f3fb41b8001c3f2dffc6086e89e782a9a46f79a | draftjs_exporter/constants.py | draftjs_exporter/constants.py | from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
return name
# https://github.com/draft-js-utils/draft-js-utils/blob/master/src... | from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
if name not in self.tuple_list:
raise AttributeError("'Enum' has no ... | Fix Enum returning invalid elements | Fix Enum returning invalid elements
| Python | mit | springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter | ---
+++
@@ -7,6 +7,9 @@
self.tuple_list = tuple_list
def __getattr__(self, name):
+ if name not in self.tuple_list:
+ raise AttributeError("'Enum' has no attribute '{}'".format(name))
+
return name
|
3350ace16ec8148b861985d59a399470655b4421 | cube_viewer/glue_viewer.py | cube_viewer/glue_viewer.py | import numpy as np
from glue.qt.widgets.data_viewer import DataViewer
from .options_widget import IsosurfaceOptionsWidget
from .vtk_widget import QtVTKWidget
class GlueVTKViewer(DataViewer):
LABEL = "VTK Isosurfaces"
def __init__(self, session, parent=None):
super(GlueVTKViewer, self).__init__(sess... | import numpy as np
from glue.qt.widgets.data_viewer import DataViewer
from .options_widget import IsosurfaceOptionsWidget
from .vtk_widget import QtVTKWidget
class GlueVTKViewer(DataViewer):
LABEL = "VTK Isosurfaces"
def __init__(self, session, parent=None):
super(GlueVTKViewer, self).__init__(sess... | Use nanpercentile instead of percentile | Use nanpercentile instead of percentile | Python | bsd-2-clause | astrofrog/cube-viewer | ---
+++
@@ -17,7 +17,7 @@
def add_data(self, data):
self._vtk_widget.set_data(data['PRIMARY'])
- initial_level = "{0:.3g}".format(np.percentile(data['PRIMARY'], 99))
+ initial_level = "{0:.3g}".format(np.nanpercentile(data['PRIMARY'], 99))
self._options_widget.levels = initial_l... |
d0a16cb7d0b4a3a04a0461df455697fd65302c9b | accelerator/migrations/0110_remove_bucket_list_program_role_20220707_1001.py | accelerator/migrations/0110_remove_bucket_list_program_role_20220707_1001.py | from django.db import migrations
def remove_bucket_list_program_roles(apps, schema_editor):
BucketState = apps.get_model('accelerator', 'BucketState')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant')
NodePublishedFor = apps... | from django.db import migrations
def remove_bucket_list_program_roles(apps, schema_editor):
BucketState = apps.get_model('accelerator', 'BucketState')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant')
NodePublishedFor = apps... | Remove program role from bucket list | [AC-9556]: Remove program role from bucket list
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -8,7 +8,7 @@
NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor')
program_role_ids = BucketState.objects.values_list('program_role_id',
- flat=True)
+ flat=True)
Nod... |
87079b55d17edc4cc8bbcb2a7af80adf5799608e | swingtime/urls.py | swingtime/urls.py | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.year_view,
name='swingtime-yearly-view'
... | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'... | Remove whitespace, and also add JSON url | Remove whitespace, and also add JSON url
| Python | mit | jonge-democraten/mezzanine-fullcalendar | ---
+++
@@ -3,26 +3,32 @@
urlpatterns = patterns('',
url(
- r'^(?:calendar/)?$',
- views.today_view,
+ r'^(?:calendar/)?$',
+ views.today_view,
name='swingtime-today'
),
url(
- r'^calendar/(?P<year>\d{4})/$',
- views.year_view,
+ r'^cal... |
e264d00fa37dd1b326f1296badd74fa4ab599a45 | project/runner.py | project/runner.py | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
class CustomTestRunner(DiscoverRunner):
"""
Same as the default Django test runner, except it also runs our node
server as a subprocess so we can render React components.
"""
def setup_test_environment(self, **kwargs... | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
from django.conf import settings
from react.render_server import render_server
TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1')
TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008)
... | Use separate node server when running the tests | Use separate node server when running the tests
| Python | mit | jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015 | ---
+++
@@ -1,5 +1,11 @@
from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
+from django.conf import settings
+from react.render_server import render_server
+
+
+TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1')
+TEST_REACT_SERVER_PORT = getattr(settings... |
bd49d3ab611a8715436987cf549097ed9cbc2a5d | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.3.6.dev0 | Update dsub version to 0.3.6.dev0
PiperOrigin-RevId: 276310514
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.3.5'
+DSUB_VERSION = '0.3.6.dev0' |
84fa71e639bc1b6fda246ddfd321f0f777b86216 | tasks/__init__.py | tasks/__init__.py | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... | Add notifiers to task list | Add notifiers to task list
| Python | apache-2.0 | BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest | ---
+++
@@ -17,6 +17,7 @@
username=options.mq_username,
password=options.mq_password),
include=[
- "tasks.message_tasks"
+ "tasks.message_tasks",
+ "tasks.notifiers",
])
selftest_task_queue.conf.update(**queue_conf) |
6c3d18e8f2a242f9de79679c4cccafbca5066bb6 | runners/serializers.py | runners/serializers.py | from rest_framework import serializers
from .models import Runner, RunnerVersion
class RunnerVersionSerializer(serializers.ModelSerializer):
class Meta(object):
model = RunnerVersion
fields = ('version', 'url')
class RunnerSerializer(serializers.ModelSerializer):
versions = RunnerVersionSeri... | from rest_framework import serializers
from .models import Runner, RunnerVersion
class RunnerVersionSerializer(serializers.ModelSerializer):
class Meta(object):
model = RunnerVersion
fields = ('version', 'architecture', 'url')
class RunnerSerializer(serializers.ModelSerializer):
versions = R... | Add architecture to runner version serializer | Add architecture to runner version serializer
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website | ---
+++
@@ -5,7 +5,7 @@
class RunnerVersionSerializer(serializers.ModelSerializer):
class Meta(object):
model = RunnerVersion
- fields = ('version', 'url')
+ fields = ('version', 'architecture', 'url')
class RunnerSerializer(serializers.ModelSerializer): |
2f635e890414f777fbe3ddde1aea74ab13558313 | llvmlite/tests/test_dylib.py | llvmlite/tests/test_dylib.py | import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def test_bad_library(self)... | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... | Add tests to check loading library. | Add tests to check loading library.
| Python | bsd-2-clause | m-labs/llvmlite,pitrou/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,markdewing/llvmlite,pitrou/llvmlite,numba/llvmlite,markdewing/llvmlite,sklam/llvmlite,sklam/llvmlite,pitrou/llvmlite,numba/llvmlite,ssarangi/llvmlite,markdewing/llvmlite,squisher/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,numba/llvmlite,numba/llvmlite,sq... | ---
+++
@@ -1,25 +1,35 @@
-import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
+from ctypes.util import find_library
+import unittest
-
+@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
c... |
95b4cdae136ea918279a4c8968f756dc15a629ed | buzzmobile/setup.py | buzzmobile/setup.py | #!/usr/bin/env python
#for downloading the packages needed for this project.
from setuptools import setup, find_packages
setup(
name='buzzmobile',
version='0.3',
url='https://github.com/gtagency/buzzmobile',
author='gtagency',
license='MIT',
keywords='car cars self-driving lidar gps ros',
... | #!/usr/bin/env python
#for downloading the packages needed for this project.
from setuptools import setup, find_packages
setup(
name='buzzmobile',
version='0.3',
url='https://github.com/gtagency/buzzmobile',
author='gtagency',
license='MIT',
keywords='car cars self-driving lidar gps ros',
... | Add required dependency for roslaunch | Add required dependency for roslaunch
| Python | mit | gtagency/buzzmobile,gtagency/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile,gtagency/buzzmobile | ---
+++
@@ -22,5 +22,6 @@
'rospkg==1.0.41',
'ds4drv', # requires apt-get install python-dev
'empy==3.3.2', # required to make catkin_make work
+ 'netifaces==0.10.5',
],
) |
77f975b9f19fad319708f19c4602ab4fd7ad8260 | scripts/ben10_build.py | scripts/ben10_build.py | from __future__ import unicode_literals
from aasimar.shared_commands import BuildCommand
from ben10.foundation.decorators import Override
#===================================================================================================
# Ben10BuildCommand
#=========================================================... | from __future__ import unicode_literals
from aasimar.shared_commands import BuildCommand
from ben10.foundation.decorators import Override
#===================================================================================================
# Ben10BuildCommand
#=========================================================... | Fix build issues when sharedscripts10 is not available. | Fix build issues when sharedscripts10 is not available.
By calling project.install with --no-spawn, we can avoid an error that
happened during build:
[ben10] Resource not found "sharedscripts10".
| Python | lgpl-2.1 | Kaniabi/ben10,ESSS/ben10,Kaniabi/ben10,ESSS/ben10 | ---
+++
@@ -14,7 +14,7 @@
@Override(BuildCommand.EvBuild)
def EvBuild(self, args):
self.Clean()
- self.Install()
+ self.Install(no_spawn=True)
self.IsClean()
self.RunTests(
jobs=self.shared_script['hudson_test_jobs'], |
f5922951bcabac81c41fd52e2ed5cd9b67c9a920 | src/gramcore/features/tests/test_descriptors.py | src/gramcore/features/tests/test_descriptors.py | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many valu... | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many valu... | Add comment on HOG calculations | Add comment on HOG calculations
| Python | mit | cpsaltis/pythogram-core | ---
+++
@@ -17,6 +17,8 @@
Based on these the result should include a number of values equal to::
block_possitions^2 * cells_per_block^2 * orientations
+
+ HOG calculations take place in row major order.
"""
pixels_per_cell = 9 |
8aca599083f69fbc4427f608554d4035c7d2dccf | social/apps/pyramid_app/views.py | social/apps/pyramid_app/views.py | from pyramid.view import view_config
from social.utils import module_member
from social.actions import do_auth, do_complete, do_disconnect
from social.apps.pyramid_app.utils import psa, login_required
@view_config(route_name='social.auth', request_method='GET')
@psa('social.complete')
def auth(request):
return d... | from pyramid.view import view_config
from social.utils import module_member
from social.actions import do_auth, do_complete, do_disconnect
from social.apps.pyramid_app.utils import psa, login_required
@view_config(route_name='social.auth', request_method=('GET', 'POST'))
@psa('social.complete')
def auth(request):
... | Allow POST requests for auth method so OpenID forms could use it that way. | Allow POST requests for auth method so OpenID forms could use it that way.
| Python | bsd-3-clause | fearlessspider/python-social-auth,cjltsod/python-social-auth,python-social-auth/social-app-django,tobias47n9e/social-core,python-social-auth/social-core,python-social-auth/social-app-django,python-social-auth/social-storage-sqlalchemy,fearlessspider/python-social-auth,python-social-auth/social-app-cherrypy,cjltsod/pyth... | ---
+++
@@ -5,7 +5,7 @@
from social.apps.pyramid_app.utils import psa, login_required
-@view_config(route_name='social.auth', request_method='GET')
+@view_config(route_name='social.auth', request_method=('GET', 'POST'))
@psa('social.complete')
def auth(request):
return do_auth(request.backend, redirect_na... |
cbdc24aeef9ffbd8e7400ab43112409509b3337d | reviewday/util.py | reviewday/util.py | import os
import shutil
import html_helper
from Cheetah.Template import Template
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
if os.path.exists(out_dir):
print 'WARNING: output directory "%s" already exists' % ... | import os
import html_helper
from Cheetah.Template import Template
from distutils.dir_util import copy_tree
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
copy_tree(report_files_dir, out_dir)
def create_report(name_spa... | Remove warning for existing output directory. | Remove warning for existing output directory.
In our configuration puppet will manage the output directory, so it
is expected behavior for it to exist, removing warning. Also
switching to distutils.dir_util copy_tree since that allows for
copying of required supporting files into an existing output
directory.
Change-... | Python | mit | openstack-infra/reviewday,openstack-infra/reviewday,dprince/reviewday | ---
+++
@@ -1,16 +1,13 @@
import os
-import shutil
import html_helper
from Cheetah.Template import Template
+from distutils.dir_util import copy_tree
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
- if os.path.e... |
4ed64168541993e2ea85e7ea47139550d1daa206 | backdrop/write/config/development_environment_sample.py | backdrop/write/config/development_environment_sample.py | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | Add buckets for collecting pingdom data | Add buckets for collecting pingdom data
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -6,7 +6,9 @@
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
- 'licensing_journey': 'licensing_journey-bearer-token'
+ 'licensing_journey': 'licensing_journey-bearer-token',
+ 'licensing_live_data': 'licensing_live_data_bear... |
653ae451e204905b8295e424ca86c20d60ee686c | settings/__init__.py | settings/__init__.py | import yaml
import utils
with open('settings.yml') as settings_file:
YML = yaml.safe_load(settings_file)
IMAGE = utils.Settings(YML['image'])
SNAP = utils.Settings(YML['snap'])
DROPBOX_TOKEN_FILE = "./dropbox.txt"
WORKING_DIRECTORY = "/home/pi/time-lapse"
IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images"
... | import glob
import yaml
import utils
with open('settings.yml') as settings_file:
YML = yaml.safe_load(settings_file)
IMAGE = utils.Settings(YML['image'])
SNAP = utils.Settings(YML['snap'])
DROPBOX_TOKEN_FILE = "./dropbox.txt"
WORKING_DIRECTORY = "/home/pi/time-lapse"
IMAGES_DIRECTORY = WORKING_DIRECTORY ... | Make a class to manage job settings | Make a class to manage job settings
| Python | mit | projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse | ---
+++
@@ -1,3 +1,4 @@
+import glob
import yaml
import utils
@@ -11,3 +12,39 @@
WORKING_DIRECTORY = "/home/pi/time-lapse"
IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images"
JOBS_DIRECTORY = WORKING_DIRECTORY + "/jobs"
+
+
+class Setting(object):
+
+ def __init__(self, settings_dict):
+ self.__dict__.u... |
7d4b2af132001927ea42b69650b6b45301ee335f | astrobin/management/commands/notify_new_blog_entry.py | astrobin/management/commands/notify_new_blog_entry.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from zinnia.models import Entry
from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.a... | Fix management command to send notification about new blog post. | Fix management command to send notification about new blog post.
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -1,20 +1,20 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
+import persistent_messages
from zinnia.models import Entry
-from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most r... |
0a04752396bdd57a8c197e2c76e5bda92d0bad1a | reddit_meatspace/utils.py | reddit_meatspace/utils.py | import hashlib
from pylons import g
def make_secret_code(meetup, user):
hash = hashlib.md5(g.SECRET)
hash.update(str(meetup._id))
hash.update(str(user._id))
return int(hash.hexdigest()[-8:], 16) % 100
| import hashlib
from pylons import g
def make_secret_code(meetup, user):
hash = hashlib.md5(g.secrets["SECRET"])
hash.update(str(meetup._id))
hash.update(str(user._id))
return int(hash.hexdigest()[-8:], 16) % 100
| Use the zk secret safe for g.SECRET. | Use the zk secret safe for g.SECRET.
| Python | bsd-3-clause | reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace | ---
+++
@@ -4,7 +4,7 @@
def make_secret_code(meetup, user):
- hash = hashlib.md5(g.SECRET)
+ hash = hashlib.md5(g.secrets["SECRET"])
hash.update(str(meetup._id))
hash.update(str(user._id))
return int(hash.hexdigest()[-8:], 16) % 100 |
22ce36b227c40ace101db5d9c4e30575adca5f36 | tests/settings.py | tests/settings.py | import os
from settings import *
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
... | from __future__ import absolute_import
import os
from settings import *
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif d... | Use absolute imports to avoid module naming issues | Use absolute imports to avoid module naming issues
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/infrastructure,Inboxen/Inboxen,Inboxen/Inboxen | ---
+++
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
import os
from settings import *
|
eabab4dcb52a8d63c74bb8b785696bc36b8b25e7 | site_cfg_template.py | site_cfg_template.py | ##
# Template file for site configuration - copy it to site_cfg.py:
# $ cp site_cfg_template.py site_cfg.py
# Force python version (e.g. '2.4'), or left 'auto' for autodetection.
python_version = 'auto'
# Operating system - one of 'posix', 'windows' or None for automatic
# determination.
system = None
# Extra flags ... | ##
# Template file for site configuration - copy it to site_cfg.py:
# $ cp site_cfg_template.py site_cfg.py
# Force python version (e.g. '2.4'), or left 'auto' for autodetection.
python_version = 'auto'
# Operating system - one of 'posix', 'windows' or None for automatic
# determination.
system = None
# Extra flags ... | Revert "Add verbose flag to compiler options (testing)." | Revert "Add verbose flag to compiler options (testing)."
This reverts commit 2406e30851b65cd78981eecd76d966fb17259fa4.
| Python | bsd-3-clause | BubuLK/sfepy,sfepy/sfepy,vlukes/sfepy,vlukes/sfepy,rc/sfepy,rc/sfepy,sfepy/sfepy,vlukes/sfepy,BubuLK/sfepy,sfepy/sfepy,BubuLK/sfepy,rc/sfepy | ---
+++
@@ -11,7 +11,7 @@
# Extra flags added to the flags supplied by distutils to compile C
# extension modules.
-compile_flags = '-g -O2 -v'
+compile_flags = '-g -O2'
# Extra flags added to the flags supplied by distutils to link C
# extension modules. |
8df3076b6315a74e57ee27fe3478d36737be0ff9 | roche/scripts/xml-load.py | roche/scripts/xml-load.py | # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.c... | # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.c... | Load other resources into exist-db | Load other resources into exist-db
| Python | mit | beijingren/roche-website,beijingren/roche-website,beijingren/roche-website,beijingren/roche-website | ---
+++
@@ -30,3 +30,13 @@
for filename in filenames:
with open(dirpath + '/' + filename) as f:
xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True)
+
+#
+# Load resources
+#
+for (dirpath, dirnames, filenames) in walk('resources'):
+ xmldb.createCollection('d... |
63a539ff4a3a832286136c40a74b1a8b3db1a5c0 | falcom/api/uri/api_querier.py | falcom/api/uri/api_querier.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from time import sleep
class APIQuerier:
def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0):
self.uri = uri
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from time import sleep
class APIQuerier:
def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0):
self.uri = uri
... | Rewrite get() to be less repetitive but still stupid | Rewrite get() to be less repetitive but still stupid
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -12,23 +12,24 @@
self.max_tries = max_tries
def get (self, **kwargs):
- try:
- return self.__open_uri(kwargs)
+ class SpecialNull: pass
+ result = SpecialNull
+ i = 1
- except ConnectionError:
- sleep(self.sleep_time)
-
- i =... |
edc88421bec2798d82faeece2df5229888d97db9 | contrib/performance/graph.py | contrib/performance/graph.py |
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
stats, samples = select(
pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time')
da... |
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
fname, bench, param, stat = fname.split(',')
stats, samples = select(
pickle.load(fil... | Make the bench/param/stat a commandline parameter | Make the bench/param/stat a commandline parameter
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver | ---
+++
@@ -12,8 +12,9 @@
data = []
for fname in sys.argv[1:]:
+ fname, bench, param, stat = fname.split(',')
stats, samples = select(
- pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time')
+ pickle.load(file(fname)), bench, param, stat)
data.append(samp... |
a4913289ce0672cfe60bb443db469356f970c353 | wakatime/projects/projectmap.py | wakatime/projects/projectmap.py | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | Make ProjectMap use config section | Make ProjectMap use config section
| Python | bsd-3-clause | wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,queenp/wakatime,gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,Djabbz/wakatime,gandarez/wakatime,wakatime/wakatime,Djabbz/wakatime,prashant... | ---
+++
@@ -23,9 +23,7 @@
class ProjectMap(BaseProject):
def process(self):
- self.config = self._load_config()
if self.config:
- log.debug(self.config)
return True
return False
@@ -35,21 +33,10 @@
def name(self):
for path in self._path_genera... |
f1436f7f5140ea51fd5fc1f231e28f57c69f0cb1 | tutorials/urls.py | tutorials/urls.py | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
] | from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url... | Add markdownx url, Add add-tutrorial url | Add markdownx url, Add add-tutrorial url
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | ---
+++
@@ -1,8 +1,12 @@
from django.conf.urls import include, url
+from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
+ # this not working correctly - s... |
6bdc335ebb8ed009cbc926e681ee6be8f475f323 | reviewboard/reviews/features.py | reviewboard/reviews/features.py | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created d... | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created d... | Mark status updates as stable. | Mark status updates as stable.
This allows people to actually use the feature without turning it on in their
`settings_local.py`.
Reviewed at https://reviews.reviewboard.org/r/8569/
| Python | mit | sgallagher/reviewboard,brennie/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,davidt/reviewboard,reviewboard/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,sgallagher/reviewboard,davidt/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie... | ---
+++
@@ -34,6 +34,7 @@
feature_id = 'reviews.status_updates'
name = _('Status Updates')
+ level = FeatureLevel.STABLE
summary = _('A way for external tools to do checks on a review request '
'and report the results of those checks.')
|
f413f5bc2015843a4e74dd969d56bc54f9dbba4e | deconstrst/__init__.py | deconstrst/__init__.py | # -*- coding: utf-8 -*-
import sys
from sphinxwrapper import build
__author__ = 'Ash Wilson'
__email__ = 'ash.wilson@rackspace.com'
__version__ = '0.1.0'
def main():
sys.exit(build(sys.argv))
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import sys
from deconstrst import build
__author__ = 'Ash Wilson'
__email__ = 'ash.wilson@rackspace.com'
__version__ = '0.1.0'
def main():
sys.exit(build(sys.argv))
if __name__ == '__main__':
main()
| Fix an import that missed the renaming sweep. | Fix an import that missed the renaming sweep.
| Python | apache-2.0 | deconst/preparer-sphinx,ktbartholomew/preparer-sphinx,smashwilson/deconst-preparer-sphinx,deconst/preparer-sphinx,ktbartholomew/preparer-sphinx | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import sys
-from sphinxwrapper import build
+from deconstrst import build
__author__ = 'Ash Wilson'
__email__ = 'ash.wilson@rackspace.com' |
68e4cddb0e66bf75f13c0d9ee0e8064acc2c1cd1 | heliosinstitution/__init__.py | heliosinstitution/__init__.py | """
Script for create/update app permissions after migrations
Author: Shirlei Chaves - shirlei@gmail.com
Version 1.0 - 03/2015
with ideas from here:
http://www.geekrant.org/2014/04/19/programmatically-create-django-security-groups/
and here:
http://devwithpassion.com/felipe/south-django-permissions/
"""
from south.si... | Add initial update permissions after migration | Add initial update permissions after migration
| Python | apache-2.0 | shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server | ---
+++
@@ -0,0 +1,48 @@
+"""
+Script for create/update app permissions after migrations
+Author: Shirlei Chaves - shirlei@gmail.com
+Version 1.0 - 03/2015
+
+with ideas from here:
+http://www.geekrant.org/2014/04/19/programmatically-create-django-security-groups/
+and here:
+http://devwithpassion.com/felipe/south-dj... | |
3aa233e0fcf7dea1e089a4bf03197c31b098b5de | apitest.py | apitest.py | #!/usr/bin/env python3
import time
import machinepark as mp
if __name__ == "__main__":
machine_ids = mp.machines_list()
sample = {'env': {} }
for mid in machine_ids:
sample[mid] = {}
for i in range(0, 10):
start = time.time()
mp.query_sample(machin... | #!/usr/bin/env python3
import time
import machinepark as mp
if __name__ == "__main__":
machine_ids = mp.machines_list()
sample = {'envsensor': {} }
for mid in machine_ids:
sample[mid] = {}
for i in range(0, 10):
start = time.time()
mp.query_sample(... | Adjust the name of environment sensor | Adjust the name of environment sensor
| Python | apache-2.0 | andreynech/iotchallenge,andreynech/iotchallenge | ---
+++
@@ -8,7 +8,7 @@
machine_ids = mp.machines_list()
- sample = {'env': {} }
+ sample = {'envsensor': {} }
for mid in machine_ids:
sample[mid] = {} |
44e64c4f0c0296015fb124cddf87bea2188559fe | stagpy/__main__.py | stagpy/__main__.py | # PYTHON_ARGCOMPLETE_OK
"""The stagpy module is callable"""
from . import config
def main():
"""StagPy entry point"""
args = config.parse_args()
args.func(args)
if __name__ == '__main__':
main()
| # PYTHON_ARGCOMPLETE_OK
"""The stagpy module is callable"""
import signal
import sys
from . import config
def sigint_handler(*_):
"""SIGINT handler"""
print('\nSo long, and thanks for all the fish.')
sys.exit()
def main():
"""StagPy entry point"""
signal.signal(signal.SIGINT, sigint_handler)
... | Handle SIGINT in a clean way | Handle SIGINT in a clean way
| Python | apache-2.0 | StagPython/StagPy | ---
+++
@@ -1,11 +1,20 @@
# PYTHON_ARGCOMPLETE_OK
"""The stagpy module is callable"""
+import signal
+import sys
from . import config
+
+
+def sigint_handler(*_):
+ """SIGINT handler"""
+ print('\nSo long, and thanks for all the fish.')
+ sys.exit()
def main():
"""StagPy entry point"""
+ si... |
e2574515d9879a5aa023df949031370969dc896c | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import six
if six.PY2:
import unittest2 as unittest
else:
import unittest
def main():
# Configure python path
parent = os.path.dirname(os.path.abspath(__file__))
if not parent in sys.path:
sys.path.insert(0, parent)
# Discover tests
os.e... | #!/usr/bin/env python
import os
import sys
import six
if six.PY2:
import unittest2 as unittest
else:
import unittest
def main():
# Configure python path
parent = os.path.dirname(os.path.abspath(__file__))
if not parent in sys.path:
sys.path.insert(0, parent)
# Discover tests
os.e... | Remove extra setup() from rebase. | Remove extra setup() from rebase.
| Python | bsd-3-clause | andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms | ---
+++
@@ -19,11 +19,6 @@
os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings'
unittest.defaultTestLoader.discover('djedi')
- import django
-
- if hasattr(django, "setup"):
- django.setup()
-
# Run tests
import django
if hasattr(django, 'setup'): |
fdf132c0b7cba6bd00f855b54ab354462c924b5c | nn/embedding/bidirectional_embeddings_to_embedding.py | nn/embedding/bidirectional_embeddings_to_embedding.py | import functools
import tensorflow as tf
from ..util import static_shape, funcname_scope
from .embeddings_to_embedding import embeddings_to_embedding
@funcname_scope
def bidirectional_embeddings_to_embedding(child_embeddings,
**kwargs):
child_embeddings_to_embedding = fun... | import functools
import tensorflow as tf
from ..util import static_shape, static_rank, funcname_scope
from .embeddings_to_embedding import embeddings_to_embedding
@funcname_scope
def bidirectional_embeddings_to_embedding(child_embeddings,
**kwargs):
child_embeddings_to_em... | Use tf.reverse function to reverse embedding sequences | Use tf.reverse function to reverse embedding sequences
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | ---
+++
@@ -1,7 +1,7 @@
import functools
import tensorflow as tf
-from ..util import static_shape, funcname_scope
+from ..util import static_shape, static_rank, funcname_scope
from .embeddings_to_embedding import embeddings_to_embedding
@@ -28,9 +28,5 @@
def _reverse_embedding_sequence(embedding_sequenc... |
a576432d045d14308012a4eaa6eaeb12fe004a37 | scarplet.py | scarplet.py | """ Functions for determinig best-fit template parameters by convolution with a
grid """
| """ Functions for determinig best-fit template parameters by convolution with a
grid """
import dem
import WindowedTemplate as wt
import numpy as np
from scipy import signal
def calculate_best_fit_parameters(dem, template_function, **kwargs):
template_args = parse_args(**kwargs)
num_angles = 180/ang_ste... | Add generic grid search function | Add generic grid search function
| Python | mit | rmsare/scarplet,stgl/scarplet | ---
+++
@@ -1,4 +1,34 @@
""" Functions for determinig best-fit template parameters by convolution with a
grid """
+import dem
+import WindowedTemplate as wt
+import numpy as np
+from scipy import signal
+def calculate_best_fit_parameters(dem, template_function, **kwargs):
+
+ template_args = parse_args(*... |
90d6c6ed4f2846ef009ee95217a69cc061623135 | meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py | meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py | from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
modules = list(project.module_se... | from functools import cmp_to_key
from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
... | Sort modules without start dates to the future | Sort modules without start dates to the future
Modules without a start date (phases dates are not set) will be sorted
after every other module or offlineevent.
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -1,3 +1,5 @@
+from functools import cmp_to_key
+
from django import template
from adhocracy4.modules.models import Module
@@ -12,10 +14,19 @@
modules = list(project.module_set.all())
events = list(OfflineEvent.objects.filter(project=project))
res = modules + events
- res_sorted = sort... |
b2f6d9c5fec4316dbceb25bd91cb5831065c1957 | string/compress.py | string/compress.py | # Compress string using counts of repeated characters
def compress_str(str):
output = ""
curr_char = ""
char_count = ""
for i in str:
if curr_char != str[i]:
output = output + curr_char + char_count # add new unique character and its count to our output
curr_char = str[i] # move on to the next character ... | # Compress string using counts of repeated characters
def compress_str(string):
output = ""
char_count = 1
# add first character
output += string[0]
for i in range(len(string)-1): # doesn't do character count for last group of a unique character
if string[i] == string[i+1]:
char_count += 1
else:
outpu... | Rewrite method and add test cases | Rewrite method and add test cases
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -1,15 +1,25 @@
# Compress string using counts of repeated characters
-def compress_str(str):
+def compress_str(string):
output = ""
- curr_char = ""
- char_count = ""
+ char_count = 1
- for i in str:
+ # add first character
+ output += string[0]
- if curr_char != str[i]:
- output = output + cur... |
a61148a71a022b6877af0445f799f3dfa3eb6136 | BinPy/examples/source/algorithms/make_boolean_function_example.py | BinPy/examples/source/algorithms/make_boolean_function_example.py |
# coding: utf-8
### An example to demostrate the usage of make boolean function.
# In[1]:
from __future__ import print_function
from BinPy.algorithms.makebooleanfunction import *
# In[2]:
# Usage of make_boolean() function
logical_expression, gate_form = make_boolean(['A', 'B', 'C'], [1, 4, 7], minterms=True)
... | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# An example to demostrate the usage of make boolean function.
# <codecell>
from __future__ import print_function
from BinPy.algorithms.makebooleanfunction import *
# <codecell>
# Usage of make_boolean() function
logical_expression, gate_f... | Update python sources for algorithms | Update python sources for algorithms
| Python | bsd-3-clause | daj0ker/BinPy,rajathkumarmp/BinPy,yashu-seth/BinPy,BinPy/BinPy,rajathkumarmp/BinPy,BinPy/BinPy,daj0ker/BinPy,yashu-seth/BinPy | ---
+++
@@ -1,45 +1,41 @@
+# -*- coding: utf-8 -*-
+# <nbformat>3.0</nbformat>
-# coding: utf-8
+# <headingcell level=2>
-### An example to demostrate the usage of make boolean function.
+# An example to demostrate the usage of make boolean function.
-# In[1]:
+# <codecell>
from __future__ import print_funct... |
519d1f23682b6815c41c2ac34df775ea2e333eab | jasmin_notifications/views.py | jasmin_notifications/views.py | """
Module defining views for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.views.decorators.http import require_safe
from django import http
from django.shortcuts import redirect
from django.utils import timezone
... | """
Module defining views for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.views.decorators.http import require_safe
from django import http
from django.shortcuts import redirect
from django.utils import timezone
... | Mark all similar notifications as followed when following one | Mark all similar notifications as followed when following one
| Python | mit | cedadev/jasmin-notifications,cedadev/jasmin-notifications | ---
+++
@@ -14,19 +14,6 @@
from .models import Notification, UserNotification
-def _handle_notification(request, notification):
- if not notification.followed_at:
- notification.followed_at = timezone.now()
- notification.save()
- return redirect(notification.link)
-
-@login_required
-def _handle... |
ccdb5001a450859ae9eb85f1c2c90a9a80fa0ce1 | eforge/wiki/urls.py | eforge/wiki/urls.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | Update wiki to be a little more flexible with naming | Update wiki to be a little more flexible with naming
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge | ---
+++
@@ -17,6 +17,6 @@
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
- url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
- url(r'^$', 'wiki_page', name='wiki-home'),
+ url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'),
+ ... |
98393be0011f4e4227e6f5e86db68533af8b78e0 | webserver/profiles/models.py | webserver/profiles/models.py | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
import markdown
import bleach
class UserProfile(models.Model):
user = models.OneToOneField(User)
about_me = ... | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
from django.core.validators import MaxLengthValidator
import markdown
import bleach
class UserProfile(models.Model):
... | Add maximum length validator to about_me | Add maximum length validator to about_me
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver | ---
+++
@@ -3,6 +3,7 @@
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
+from django.core.validators import MaxLengthValidator
import markdown
import bleach
@@ -11,7 +12,7 @@
class UserProfile(models.Model):
user = models.OneToOneField(Use... |
0d37ada90d4648f1e45cc3aa95dace014a26c599 | components/includes/utilities.py | components/includes/utilities.py | import random
import json
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['retu... | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | Clean up, comments, liveness checking, robust data transfer | Clean up, comments, liveness checking, robust data transfer
| Python | bsd-2-clause | mavroudisv/Crux | ---
+++
@@ -1,5 +1,6 @@
import random
import json
+import time
import SocketExtend as SockExt
import config as conf
@@ -46,6 +47,7 @@
break
except Exception as e:
print "ouups"
+ time.sleep(1)
attempted += 1
return success |
f4415c9ba2df6f0cd511986d78e454194017db2e | en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py | en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py | #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (not needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.format(respon... | #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (should not be needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.for... | Make a statement concerning requests 3.x more precise. | en-2018-04-22: Make a statement concerning requests 3.x more precise.
requests 3 has not yet been released, so it may theoretically happen that the
fix will be also needed for requests 3.x.
| Python | bsd-3-clause | s3rvac/blog,s3rvac/blog,s3rvac/blog,s3rvac/blog | ---
+++
@@ -3,7 +3,7 @@
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
-# For requests 2.x (not needed for requests 3.x).
+# For requests 2.x (should not be needed for requests 3.x).
#
import requests |
c129e600b91ac0c35e26847ef5b1df75a1dec695 | fmn/filters/generic.py | fmn/filters/generic.py | # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if f... | # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedms... | Update the documentation title for the user_filter | Update the documentation title for the user_filter | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | ---
+++
@@ -3,7 +3,7 @@
def user_filter(config, message, fasnick=None, *args, **kw):
- """ Filters the messages by the user that performed the action.
+ """ All messages of user
Use this filter to filter out messages that are associated with a
specified user. |
12b3c2e99878a586602410a599d18fdebd0f4a3c | jetcomcrawl/modes/items.py | jetcomcrawl/modes/items.py | from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def wor... | from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def wor... | Handle no results from category page | Handle no results from category page
| Python | mit | tdickman/jetcom-crawl | ---
+++
@@ -22,11 +22,14 @@
try:
soup = BeautifulSoup(html.text, 'html.parser')
- results = []
- for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}):
- url = item.a['href']
- ... |
2515a49f3ceae6de3e3de68bac9ec3f12fc2eba8 | redbot/message/headers/x_pad.py | redbot/message/headers/x_pad.py | #!/usr/bin/env python
from redbot.message import headers
class x_pad(headers.HttpHeader):
canonical_name = "X-Pad"
description = """\
The `%(field_name)s` header is used to "pad" the response header size.
Very old versions of the Netscape browser had a bug whereby a response whose headers were exactly
... | #!/usr/bin/env python
from redbot.message import headers
class x_pad(headers.HttpHeader):
canonical_name = "X-Pad"
description = """\
The `%(field_name)s` header is used to "pad" the response header size.
Very old versions of the Netscape browser had a bug whereby a response whose headers were exactly
... | Update x-pad; it really isn't necessary | Update x-pad; it really isn't necessary
Fixes #229
| Python | mit | mnot/redbot,mnot/redbot,mnot/redbot | ---
+++
@@ -12,7 +12,7 @@
256 or 257 bytes long, the browser would consider the response (e.g., an image) invalid.
Since the affected browsers (specifically, Netscape 2.x, 3.x and 4.0 up to beta 2) are no longer
- widely used, it's probably safe to omit this header."""
+ widely used, it's safe to omit this ... |
fe7e841c166ebc227e00baca4c8a72fb04ce0693 | src/mcedit2/util/directories.py | src/mcedit2/util/directories.py | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(script)
else:
... | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(os.path.dirname(os.path.dirname(sc... | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this) | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
| Python | bsd-3-clause | Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2 | ---
+++
@@ -8,7 +8,7 @@
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
- folder = os.path.dirname(script)
+ folder = os.path.dirname(os.path.dirname(os.path.dirname(script))) # from src/mcedit, ../../
else:
folder... |
72dcd015a001dc86cde96d35e5f25f88904f9715 | reviewboard/hostingsvcs/fake.py | reviewboard/hostingsvcs/fake.py | from __future__ import unicode_literals
from reviewboard.hostingsvcs.service import HostingService
class FakeHostingService(HostingService):
"""A hosting service that is not provided by Review Board.
Fake hosting services are intended to be used to advertise for Beanbag,
Inc.'s Power Pack extension.
... | from __future__ import unicode_literals
from reviewboard.hostingsvcs.service import HostingService
class FakeHostingService(HostingService):
"""A hosting service that is not provided by Review Board.
Fake hosting services are intended to be used to advertise for Beanbag,
Inc.'s Power Pack extension.
... | Fix Bitbucket Server appearing twice in the repository list. | Fix Bitbucket Server appearing twice in the repository list.
When Power Pack is installed, Bitbucket Server appears twice in the
repository form's hosting list. This is because the fake entry was using
the wrong module path for Bitbucket Server. This fixes that to use the
right path, showing only a single entry.
Test... | Python | mit | chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard | ---
+++
@@ -43,7 +43,7 @@
FAKE_HOSTING_SERVICES = {
'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit':
FakeAWSCodeCommitHostingService,
- 'rbpowerpack.hostingsvcs.bitbucketserver.BitbucketServer':
+ 'rbpowerpack.hostingsvcs.bitbucket_server.BitbucketServer':
FakeBitbucketServerHosti... |
2a00e0b25ebbcac58b7e65efbfcd88bd0539c3e7 | metakernel/magics/cd_magic.py | metakernel/magics/cd_magic.py | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic
import os
class CDMagic(Magic):
def line_cd(self, path):
"""
%cd PATH - change current directory of session
This line magic is used to change the director... | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic
import os
class CDMagic(Magic):
def line_cd(self, path):
"""
%cd PATH - change current directory of session
This line magic is used to change the director... | Fix cd magic for ~ paths and add test | Fix cd magic for ~ paths and add test
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -20,6 +20,7 @@
Example:
%cd ..
"""
+ path = os.path.expanduser(path)
try:
os.chdir(path)
retval = os.path.abspath(path) |
21c7232081483c05752e6db3d60692a04d482d24 | dakota/tests/test_dakota_base.py | dakota/tests/test_dakota_base.py | #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
import os
import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Fixtures -------------------------------------------------------------
def setup_mo... | #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Helpers --------------------------------------------------------------
class Concrete(DakotaBase):
"""A s... | Add tests for dakota.dakota_base module | Add tests for dakota.dakota_base module
Make a subclass of DakotaBase to use for testing. Add tests for the
"block" sections used to define an input file.
| Python | mit | csdms/dakota,csdms/dakota | ---
+++
@@ -7,17 +7,23 @@
#
# Mark Piper (mark.piper@colorado.edu)
-import os
-import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase
+# Helpers --------------------------------------------------------------
+
+class Concrete(DakotaBase):
+ """A subclass of DakotaBase used for te... |
170293123c89696bbdcfca0cbc72233ea03f90c8 | real_estate_agency/real_estate_agency/views.py | real_estate_agency/real_estate_agency/views.py | from django.shortcuts import render,render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor
def corporation_benefit_plan(request):
... | from django.shortcuts import render,render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor... | Add form content to the index page. | Add form content to the index page.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency | ---
+++
@@ -2,6 +2,7 @@
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
+from new_buildings.forms import SearchForm
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor
@@ -13,6 +14,7 @@
... |
21b91eeade40d750da12cc42e89ab157911ed403 | src/utils/run_check.py | src/utils/run_check.py | def check_argv(argv):
"""Check if arguments are ok.
When executing, there must be argument switch for test/live.
There also must be filename.
Method returns set(is_correct, filename, is_test)
"""``
python_file_name = argv[0]
usage_msg = "Usage: python %s [-test | -live] filename.txt" % pyth... | def check_argv(argv):
"""Check if arguments are ok.
When executing, there must be argument switch for test/live.
There also must be filename.
Method returns set(is_correct, filename, is_test)
"""
python_file_name = argv[0]
usage_msg = "Usage: python %s [-test | -live] filename.txt" % python... | Remove forgotten comment quotation marks | Remove forgotten comment quotation marks
| Python | mit | ThePavolC/CleanJira | ---
+++
@@ -4,7 +4,7 @@
When executing, there must be argument switch for test/live.
There also must be filename.
Method returns set(is_correct, filename, is_test)
- """``
+ """
python_file_name = argv[0]
usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name
... |
a149c8664ed8f44ab9118a85440d95239362edf2 | src/ansible/tests/test_views.py | src/ansible/tests/test_views.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from ansible.models import Playbook
class PlaybookListViewTest(TestCase):
fixtures = ['initial_data.json']
def test_view_url_exists_at_desired_location(self):
resp = self.client.get('/playbooks/')
self.assertEqual(... | from django.core.urlresolvers import reverse
from django.test import TestCase
from ansible.models import Playbook
class PlaybookListViewTest(TestCase):
fixtures = ['initial_data.json']
def test_view_url_exists_at_desired_location(self):
resp = self.client.get('/playbooks/')
self.assertEqual(... | Test to make sure link to create playbook exists | Test to make sure link to create playbook exists
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | ---
+++
@@ -15,6 +15,10 @@
resp = self.client.get(reverse('ansible:playbook-list'))
self.assertEqual(resp.status_code, 200)
+ def test_view_playbook_list_has_create_playbook_link(self):
+ resp = self.client.get(reverse('ansible:playbook-create'))
+ self.assertEqual(resp.status_cod... |
76981dc76d17b51c73682f84ba94ae4d6329d66d | scripts/wait_for_postgres.py | scripts/wait_for_postgres.py | """Wait up to 30 seconds for postgres to be available.
This is useful when running in docker, as the first time we create a
postgres volume it takes a few seconds to become ready.
"""
import time
from os import environ
import psycopg2
if __name__ == '__main__':
elapsed = 0
while elapsed < 30:
try:
... | """Wait up to 30 seconds for postgres to be available.
This is useful when running in docker, as the first time we create a
postgres volume it takes a few seconds to become ready.
"""
import time
import os
import psycopg2
import dotenv
if __name__ == '__main__':
env_path = os.path.join(
os.path.dirname(... | Fix bug in script that blocks Travis on postgres ready state | Fix bug in script that blocks Travis on postgres ready state
| Python | mit | ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing | ---
+++
@@ -5,18 +5,26 @@
"""
import time
-from os import environ
+import os
import psycopg2
+import dotenv
+
if __name__ == '__main__':
+ env_path = os.path.join(
+ os.path.dirname(os.path.realpath(__file__)),
+ '..', 'environment'
+ )
+
+ dotenv.read_dotenv(env_path)
elapsed = 0
... |
5a4ff0b4da37a97e6ef86074dde63b47ba553ad8 | test/typing.py | test/typing.py | #!/usr/bin/env python
from stella import stella
from random import randint
from test import *
def return_bool(): return True
def return_arg(x): return x
def equality(a,b): return a==b
def test1():
make_eq_test(return_bool, ())
@mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5]))
def test2(arg... | #!/usr/bin/env python
from stella import stella
from random import randint
from test import *
def return_bool(): return True
def return_arg(x): return x
def equality(a,b): return a==b
def test1():
make_eq_test(return_bool, ())
@mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5]))
def test2(arg... | Add a test that automatic type promotions are not allowed. | Add a test that automatic type promotions are not allowed.
| Python | apache-2.0 | squisher/stella,squisher/stella,squisher/stella,squisher/stella | ---
+++
@@ -19,5 +19,10 @@
def test3(args):
make_eq_test(equality, args)
+@mark.parametrize('args', [(False, 1), (42.0, True), (1, 1.0), (randint(0, 10000000), float(randint(-10000 , 1000000)))])
+@mark.xfail()
+def test3fail(args):
+ make_eq_test(equality, args)
+
if __name__ == '__main__':
print(st... |
70098ce0c9db57cb82b97bc9fee8a799fb355e98 | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
def run_once(sel... | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
binary_to_run = ... | Make the sync integration tests self-contained on autotest | Make the sync integration tests self-contained on autotest
In the past, the sync integration tests used to require a password file
stored on every test device in order to do a gaia sign in using
production gaia servers. This caused the tests to be brittle.
As of today, the sync integration tests no longer rely on a p... | Python | bsd-3-clause | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-u... | ---
+++
@@ -1,4 +1,4 @@
-# Copyright (c) 2010 The Chromium Authors. All rights reserved.
+# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -7,9 +7,8 @@
class desktopui_SyncIntegrationTests(chro... |
9fcff13a4438268aa76cf2817bca1086258a083b | src/mr_landmark_mapper.py | src/mr_landmark_mapper.py | #!/usr/bin/env python
import sys
import json
import codecs
import zipimport
importer = zipimport.zipimporter('landmark.mod')
extraction = importer.load_module('extraction')
postprocessing = importer.load_module('postprocessing')
from extraction.Landmark import RuleSet
current_id = None
with codecs.open("lib/rules.... | #!/usr/bin/env python
import sys
import json
import codecs
import zipimport
importer = zipimport.zipimporter('landmark.mod')
extraction = importer.load_module('extraction')
postprocessing = importer.load_module('postprocessing')
from extraction.Landmark import RuleSet
current_id = None
with codecs.open("rules.txt"... | Change mapper to use SequenceFileAsJSONInputBatchFormat | Change mapper to use SequenceFileAsJSONInputBatchFormat
| Python | apache-2.0 | usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction | ---
+++
@@ -13,8 +13,9 @@
current_id = None
-with codecs.open("lib/rules.zip", "r", "utf-8") as myfile:
+with codecs.open("rules.txt", "r", "utf-8") as myfile:
json_str = myfile.read().encode('utf-8')
+#sys.stderr.write("Got rules:" + json_str)
json_object = json.loads(json_str)
rules = RuleSet(json_objec... |
ca43f30998290193290177f4c55c1c8577123974 | arcutils/sessions.py | arcutils/sessions.py | from __future__ import absolute_import
from random import random
import logging
from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import request_started
logger = logging.getLogger(__name__)
def clear_exp... | from __future__ import absolute_import
from random import random
import logging
try:
# Python >= 2.7
import importlib
except ImportError:
# Python < 2.7; will be removed in Django 1.9
from django.utils import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfi... | Make importlib import compatible w/ Django>=1.8 | Make importlib import compatible w/ Django>=1.8
For Django 1.8, this just squelches a DeprecationWarning. For 1.9, this
will stop an ImportError.
| Python | mit | mdj2/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,mdj2/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils | ---
+++
@@ -2,8 +2,14 @@
from random import random
import logging
+try:
+ # Python >= 2.7
+ import importlib
+except ImportError:
+ # Python < 2.7; will be removed in Django 1.9
+ from django.utils import importlib
+
from django.conf import settings
-from django.utils.importlib import import_module
... |
4c00345ec0a66363d3b9d7e423e2fcd19aa2a307 | ditto/core/context_processors.py | ditto/core/context_processors.py | from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled(),
'DITTO_FLICKR_USE_LOCAL_MEDIA':
app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA,
}
| from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled()
}
| Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor | Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor
| Python | mit | philgyford/django-ditto,philgyford/django-ditto,philgyford/django-ditto | ---
+++
@@ -4,8 +4,6 @@
def ditto(request):
return {
- 'enabled_apps': ditto_apps.enabled(),
- 'DITTO_FLICKR_USE_LOCAL_MEDIA':
- app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA,
+ 'enabled_apps': ditto_apps.enabled()
}
|
760a952851664232b11ad95acb8884dda59308a4 | sysrev/widgets.py | sysrev/widgets.py | from django.forms import widgets
from django.utils.safestring import *
# See static/js/querywidget.js
class QueryWidget(widgets.Textarea):
def __init__(self, attrs=None):
default_attrs = {'class': "queryWidget"}
if attrs:
default_attrs.update(attrs)
super(QueryWidget, self).__in... | from django.forms import widgets
from django.utils.safestring import *
# See static/js/querywidget.js
class QueryWidget(widgets.Textarea):
def __init__(self, attrs=None):
default_attrs = {'class': "queryWidget"}
if attrs:
default_attrs.update(attrs)
super(QueryWidget, self).__in... | Add <noscript> message to indicate that only the advanced query editor is available. | Add <noscript> message to indicate that only the advanced query editor is available.
| Python | mit | iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview | ---
+++
@@ -10,7 +10,9 @@
super(QueryWidget, self).__init__(default_attrs)
def script(self):
- return mark_safe("<script src='/static/js/querywidget.js' type='text/javascript' defer></script>")
+ return mark_safe("<noscript>Please enable javascript to use the query editor. Without it ena... |
7f41a424143334a8c8e1ccbd768c911f8e6ffb31 | transform_quandl_xjpx_archive.py | transform_quandl_xjpx_archive.py | # -*- coding: utf-8 -*-
"""
```
# 1.
$ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \
/tmp/quandl-xjpx/
# 2.
$ python transform_quandl_xjpx_archive.py
```
"""
import tarfile
with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f:
f.add('/tmp/quandl-xjpx')
| # -*- coding: utf-8 -*-
"""
```
# 1.
$ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \
/tmp/quandl-xjpx/
# 2.
$ python transform_quandl_xjpx_archive.py
```
"""
import tarfile
import os
with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f:
os.chdir('/tmp/quandl-xjpx')
for fn in os.list... | Fix bug on transform quandl archive | Fix bug on transform quandl archive
| Python | apache-2.0 | magne-max/zipline-ja,magne-max/zipline-ja | ---
+++
@@ -10,7 +10,10 @@
```
"""
import tarfile
+import os
with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f:
- f.add('/tmp/quandl-xjpx')
+ os.chdir('/tmp/quandl-xjpx')
+ for fn in os.listdir('.'):
+ f.add(fn) |
812f1fec796e4c7d86731d5e3e91293fb1b0296b | scripts/europeana-meta.py | scripts/europeana-meta.py | from __future__ import print_function
import sys, os
from re import sub
import zipfile, json
# from pyspark import SparkContext
# from pyspark.sql import SQLContext
# from pyspark.sql import Row
# from pyspark.sql.types import StringType
def getSeries(fname):
with zipfile.ZipFile(fname, 'r') as zf:
names... | from __future__ import print_function
import sys, os
from re import sub
import zipfile, json
# from pyspark import SparkContext
# from pyspark.sql import SQLContext
# from pyspark.sql import Row
# from pyspark.sql.types import StringType
def getSeries(fname):
with zipfile.ZipFile(fname, 'r') as zf:
names... | Use file path as Europeana series name. | Use file path as Europeana series name.
| Python | apache-2.0 | ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim | ---
+++
@@ -13,11 +13,11 @@
with zipfile.ZipFile(fname, 'r') as zf:
names = zf.namelist()
mfile = [f for f in names if f.endswith('.metadata.json')]
- series = fname
+ series = 'europeana/' + sub('^.*newspapers-by-country/', '',
+ sub('[\x80-\xff... |
0ec5aeca33676172f458ec6761282157dcb19635 | tests/test_set_pref.py | tests/test_set_pref.py | # tests.test_set_pref
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)... | # tests.test_set_pref
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)... | Add test for setting preferred search engine | Add test for setting preferred search engine
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -20,3 +20,11 @@
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
+
+
+def test_set_search_engine():
+ """should set preferred search engine"""
+ new_search_engine = 'yahoo'
+ yvs.main('searchEng... |
9d65dbb84126a26e8e6dfe31179087f75134f564 | tests/integration/auth_tests.py | tests/integration/auth_tests.py | from django.test import TestCase
from django.contrib.auth import authenticate, get_user_model
from django.core import mail
User = get_user_model()
class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase):
def test_authenticates_when_passwords_are_different(self):
# Create two users with the same email ... | from django.test import TestCase
from django.contrib.auth import authenticate
from django.core import mail
from oscar.core.compat import get_user_model
User = get_user_model()
class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase):
def test_authenticates_when_passwords_are_different(self):
# Create ... | Load User model from compatibility layer | Load User model from compatibility layer
| Python | bsd-3-clause | jinnykoo/wuyisj.com,josesanch/django-oscar,itbabu/django-oscar,kapt/django-oscar,Jannes123/django-oscar,nickpack/django-oscar,bnprk/django-oscar,marcoantoniooliveira/labweb,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,marcoantoniooliveira/labweb,itbabu/django-oscar,manevant/django-oscar,bschuon/django-oscar,faratr... | ---
+++
@@ -1,6 +1,8 @@
from django.test import TestCase
-from django.contrib.auth import authenticate, get_user_model
+from django.contrib.auth import authenticate
from django.core import mail
+
+from oscar.core.compat import get_user_model
User = get_user_model()
|
7ab7eae4254f8ee62b3a8620982c72b07c2299e4 | tests/__init__.py | tests/__init__.py | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args, **kwargs):
sleep = kwargs.pop('sleep', DEFAULT_SLEEP)
expected_return = kwargs.pop('expected_return', None)
call = kwargs.pop('call', True)
def func():
time.sleep(sleep)
... | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args,
sleep=DEFAULT_SLEEP, expected_return=None, call=True,
**kwargs):
def func():
time.sleep(sleep)
if call:
assert expected_return == callback(*args, ... | Use named kwargs after *args | Use named kwargs after *args
Another Python 3 thing.
| Python | mit | FichteFoll/resumeback | ---
+++
@@ -9,11 +9,9 @@
pass
-def defer(callback, *args, **kwargs):
- sleep = kwargs.pop('sleep', DEFAULT_SLEEP)
- expected_return = kwargs.pop('expected_return', None)
- call = kwargs.pop('call', True)
-
+def defer(callback, *args,
+ sleep=DEFAULT_SLEEP, expected_return=None, call=True,
+... |
a5beccfa3574f4fcb1b6030737b728e65803791f | numpy/array_api/_typing.py | numpy/array_api/_typing.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = [
"Array",
"Device",
"Dtype",
... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = [
"Array",
"Device",
"Dtype",
... | Fix invalid parameter types used in `Dtype` | MAINT: Fix invalid parameter types used in `Dtype`
| Python | bsd-3-clause | anntzer/numpy,charris/numpy,mattip/numpy,endolith/numpy,mhvk/numpy,charris/numpy,mhvk/numpy,jakirkham/numpy,seberg/numpy,endolith/numpy,pdebuyl/numpy,jakirkham/numpy,rgommers/numpy,seberg/numpy,numpy/numpy,rgommers/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,endolith/numpy,mhvk/numpy,seberg/numpy,endolith/numpy,rgo... | ---
+++
@@ -15,10 +15,12 @@
"PyCapsule",
]
-from typing import Any, Literal, Sequence, Type, Union
+import sys
+from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
-from . import (
- Array,
+from . import Array
+from numpy import (
+ dtype,
int8,
int16,
int32,
@@ -36,9... |
6c497109cee9c3fa69ca9be118f8546f7696a937 | tests/conftest.py | tests/conftest.py | """Common fixtures and configurations for this test directory."""
import os
import shutil
import sys
import pytest
@pytest.fixture('module')
def cwd_module_dir():
"""Change current directory to this module's folder to access inputs and write outputs."""
cwd = os.getcwd()
os.chdir(os.path.dirname(__file__... | """Common fixtures and configurations for this test directory."""
import os
import shutil
import sys
import pytest
@pytest.fixture(scope='module')
def cwd_module_dir():
"""Change current directory to this module's folder to access inputs and write outputs."""
cwd = os.getcwd()
os.chdir(os.path.dirname(__... | Fix tests setupt for new pytest | Fix tests setupt for new pytest
| Python | bsd-3-clause | pyecore/pyecoregen | ---
+++
@@ -6,7 +6,7 @@
import pytest
-@pytest.fixture('module')
+@pytest.fixture(scope='module')
def cwd_module_dir():
"""Change current directory to this module's folder to access inputs and write outputs."""
cwd = os.getcwd() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.