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 |
|---|---|---|---|---|---|---|---|---|---|---|
dfbebf26f52db94c9fc8e1056c39013d8cdb2656 | name/context_processors.py | name/context_processors.py | def baseurl(request):
"""
Return a BASE_URL template context for the current request
"""
if request.is_secure():
scheme = 'https://'
else:
scheme = 'http://'
return {
'BASE_URL': scheme + request.get_host(),
}
| from name.models import NAME_TYPE_CHOICES
def baseurl(request):
"""
Return a BASE_URL template context for the current request
"""
if request.is_secure():
scheme = 'https://'
else:
scheme = 'http://'
return {
'BASE_URL': scheme + request.get_host(),
}
def name_ty... | Add a new context processor to include the NAME_TYPE_CHOICES in every request context. | Add a new context processor to include the NAME_TYPE_CHOICES in every request context.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name | ---
+++
@@ -1,3 +1,6 @@
+from name.models import NAME_TYPE_CHOICES
+
+
def baseurl(request):
"""
Return a BASE_URL template context for the current request
@@ -10,3 +13,7 @@
return {
'BASE_URL': scheme + request.get_host(),
}
+
+
+def name_types(request):
+ return {'name_types': dict(... |
f33bf5a99b9bb814fe6da6b7713e87014aae5fdf | src/journal/migrations/0035_journal_xsl.py | src/journal/migrations/0035_journal_xsl.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-03 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import journal.models
class Migration(migrations.Migration):
dependencies = [
('journal', '0034_migrate_issue_types'... | Fix migration tree for journal 0035 | Fix migration tree for journal 0035
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -11,6 +11,9 @@
dependencies = [
('journal', '0034_migrate_issue_types'),
+ ('core', '0037_journal_xsl_files'),
+
+
]
operations = [ |
0904d8f5ca4f10b4cc7121e60c35f7560e37019c | boardinghouse/templatetags/boardinghouse.py | boardinghouse/templatetags/boardinghouse.py | from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import get_schema_model
Schema = get_schema_model()
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
... | from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import _get_schema
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(o... | Remove a database access from the template tag. | Remove a database access from the template tag.
| Python | bsd-3-clause | luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse | ---
+++
@@ -1,9 +1,7 @@
from django import template
from ..schema import is_shared_model as _is_shared_model
-from ..schema import get_schema_model
-
-Schema = get_schema_model()
+from ..schema import _get_schema
register = template.Library()
@@ -16,8 +14,8 @@
return obj and _is_shared_model(obj)
@re... |
4b448c704f69b951d19229c85debfdb5a2e122c1 | citeproc/py2compat.py | citeproc/py2compat.py |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import locale
import sys
__all__ = ['PY2']
PY2 = sys.version_info < (3, 0)
if PY2:
__all__ += ['str', 'print', 'open']
from io import open
str = unicode
std_print = print
def print(*o... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import locale
import sys
__all__ = ['PY2']
PY2 = sys.version_info < (3, 0)
if PY2:
__all__ += ['str', 'print', 'open']
from io import open
str = unicode
std_print = print
def print(*o... | Fix Tox/Travis testing on Python 2.7 | Fix Tox/Travis testing on Python 2.7 | Python | bsd-2-clause | jayvdb/citeproc-py | ---
+++
@@ -20,7 +20,7 @@
def print(*objects, **kwargs):
if kwargs.get('file', sys.stdout) == sys.stdout:
objects = (unicode(obj) for obj in objects)
- if not sys.stdout.encoding:
+ if not getattr(sys.stdout, 'encoding', None):
objects = (obj.encode(lo... |
2436f1a00021baa39f3d3dfece1d44a2d3351dfd | bin/create_test_user.py | bin/create_test_user.py | # Create a dummy user for the app store review testing
# This needs to be done every time we switch to a new database
import sys
from dao.user import User
def create_fake_JWT_token(userEmail):
"""
Creates a fake JWT token for the specified user. This has two major benefits.
1. It allows us to finally writ... | # Create a dummy user for the app store review testing
# This needs to be done every time we switch to a new database
import sys
from emission.core.wrapper.user import User
def create_fake_JWT_token(userEmail):
"""
Creates a fake JWT token for the specified user. This has two major benefits.
1. It allows ... | Fix import to match the new directory structure | Fix import to match the new directory structure
| Python | bsd-3-clause | yw374cornell/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,yw374cornell/... | ---
+++
@@ -2,7 +2,7 @@
# This needs to be done every time we switch to a new database
import sys
-from dao.user import User
+from emission.core.wrapper.user import User
def create_fake_JWT_token(userEmail):
""" |
6e3d24b0594434577de6950190f0f103e08a2fbe | Source/Perforce/wb_p4_credential_dialogs.py | Source/Perforce/wb_p4_credential_dialogs.py | '''
====================================================================
Copyright (c) 2018 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
===========================================================... | '''
====================================================================
Copyright (c) 2018 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
===========================================================... | Update the crential dialog for perforce - untested | Update the crential dialog for perforce - untested | Python | apache-2.0 | barry-scott/git-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/git-workbench | ---
+++
@@ -15,37 +15,29 @@
import wb_dialog_bases
class WbP4GetLoginDialog(wb_dialog_bases.WbDialog):
- def __init__( self, app, parent, url, realm ):
+ def __init__( self, app, parent, username ):
super().__init__( parent )
self.setWindowTitle( T_('Perforce Credentials - %s') % (' '.jo... |
2e6267c7b283fd579395fc3faac2b253ddb032fe | src/midonet/auth/keystone.py | src/midonet/auth/keystone.py |
from keystoneclient.v2_0 import client as keystone_client
from datetime import datetime
from datetime import timedelta
class KeystoneAuth:
def __init__(self, uri, username, password, tenant_id=None,
tenant_name=None):
self.uri = uri
self.username = username
self.password... |
from keystoneclient.v2_0 import client as keystone_client
from datetime import datetime
from datetime import timedelta
class KeystoneAuth:
def __init__(self, uri, username, password, tenant_id=None,
tenant_name=None):
self.uri = uri
self.username = username
self.password... | Add public method to get token. | Add public method to get token.
Signed-off-by: Tomoe Sugihara <6015414ca332492cf0bb4dbbac212276d1c110a7@midokura.com>
| Python | apache-2.0 | midonet/python-midonetclient,midonet/python-midonetclient,midokura/python-midonetclient,midokura/python-midonetclient | ---
+++
@@ -22,22 +22,21 @@
if (self.token_expires == None or
self.token_expires - datetime.now() < timedelta(seconds=60*60)):
try:
- self.token = self._generate_token()
+ self.token = self.get_token()
+ self.token_expires = datetime.strp... |
7895b0a39694e88ed1bdd425c69fb747b7531c59 | indico/testing/mocks.py | indico/testing/mocks.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Fix str/int usage in MockConferenceHolder | Fix str/int usage in MockConferenceHolder
| Python | mit | indico/indico,ThiefMaster/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,ind... | ---
+++
@@ -27,15 +27,15 @@
if event.id in cls._events:
__tracebackhide__ = True
raise Exception("Event '{}' already exists".format(event.id))
- cls._events[event.id] = event
+ cls._events[int(event.id)] = event
@classmethod
def remove(cls, event):
- ... |
06b6b2fa0d8f7d8e4ef35068c3aa32cd39ac04c3 | accountant/functional_tests/test_homepage.py | accountant/functional_tests/test_homepage.py | # -*- coding: utf-8 -*-
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the title of the browser contains '18xx Ac... | # -*- coding: utf-8 -*-
import unittest
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
@unittest.skip
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server_url)
# She sees that the tit... | Add FT to test if angular is loaded | Add FT to test if angular is loaded
| Python | mit | XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant | ---
+++
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
+import unittest
from .base import FunctionalTestCase
from .pages import game
class HomePageTest(FunctionalTestCase):
+ @unittest.skip
def test_create_game(self):
# Alice is a user who visits the website
self.browser.get(self.live_server... |
ba3544fc18d5c5e827b1c1777b7811201545a8c5 | boto/pyami/scriptbase.py | boto/pyami/scriptbase.py | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self... | Add the command that failed to the error log and the error email to help debug problems where the error produces no output. | Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
| Python | mit | appneta/boto,dimdung/boto,j-carl/boto,ekalosak/boto,drbild/boto,acourtney2015/boto,bryx-inc/boto,darjus-amzn/boto,ddzialak/boto,alfredodeza/boto,vijaylbais/boto,clouddocx/boto,israelbenatar/boto,alex/boto,podhmo/boto,cyclecomputing/boto,shipci/boto,kouk/boto,jindongh/boto,felix-d/boto,Timus1712/boto,alex/boto,lochiicon... | ---
+++
@@ -30,9 +30,11 @@
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
- boto.log.error(self.last_command.output)
+ boto.log.error('Error running command: "%s". Output: "%s"' % (comma... |
2872d4f34dbcfe4b212ca7c72a7b9ec725cfcc20 | pyQuantuccia/tests/test_get_holiday_date.py | pyQuantuccia/tests/test_get_holiday_date.py | from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
assert(quantuccia.get_holiday_date() is None)
| # from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
# assert(quantuccia.get_holiday_date() is None)
pass
| Comment out the tests so that the diagnostic test can run. | Comment out the tests so that the diagnostic test can run.
| Python | bsd-3-clause | jwg4/pyQuantuccia,jwg4/pyQuantuccia | ---
+++
@@ -1,8 +1,9 @@
-from pyQuantuccia import quantuccia
+# from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
- assert(quantuccia.get_holiday_date() is None)
+ # assert(quantuccia.get_holiday_d... |
d0b56873b40acd3932f450293c363b01b5a709b9 | jinja2_time/__init__.py | jinja2_time/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
from .jinja2_time import TimeExtension
__all__ = ['TimeExtension']
| # -*- coding: utf-8 -*-
from .jinja2_time import TimeExtension
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
__all__ = ['TimeExtension']
| Fix flake8 issue in init | Fix flake8 issue in init
| Python | mit | hackebrot/jinja2-time | ---
+++
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
+
+from .jinja2_time import TimeExtension
__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.1.0'
-from .jinja2_time import TimeExtension
__all__ = ['TimeExtension'] |
810e688e8e896caf5a3c6de1c76a5bc696d918c6 | apps.py | apps.py | import os
import webapp2
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
task_app = webapp2.WSGIApplication([
('/task/index', handlers.IndexTaskHandler),
('/task/torrent', handlers.TorrentTaskHandler),
('/task/update_feeds', handlers.FeedTaskHandler),
('/task/cleanup'... | import os
import webapp2
import logging
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)
task_app = webapp2.WSGIApplication([
('/task/index', handlers.IndexTaskHandler),
('/task/torrent'... | Set logging level depenging on environment | Set logging level depenging on environment
| Python | apache-2.0 | notapresent/rutracker_rss,notapresent/rutracker_rss,notapresent/rutracker_rss | ---
+++
@@ -1,10 +1,13 @@
import os
import webapp2
+import logging
import handlers
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
+loglevel = logging.DEBUG if debug else logging.INFO
+logging.getLogger().setLevel(loglevel)
task_app = webapp2.WSGIApplication([
('/task/index', handler... |
7e5221a65bd644cc86003f67daa3148f22b4a530 | hash_table.py | hash_table.py | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self):
pass
class Hash(object):
def __init__(self, size=1024... | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
cla... | Build out hash item class | Build out hash item class
| Python | mit | jwarren116/data-structures-deux | ---
+++
@@ -8,8 +8,9 @@
class HashItem(object):
- def __init__(self):
- pass
+ def __init__(self, key, value):
+ self.key = key
+ self.value = value
class Hash(object): |
ca8556584876adfea9f9f1f1042ebb2704933f34 | addons/product/__terp__.py | addons/product/__terp__.py | {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support vari... | {
"name" : "Products & Pricelists",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Inventory Control",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : ["product_demo.xml"],
"description": """
This is the base module to manage products and pricelists in Tiny ERP.
Products support vari... | Add product_security.xml file entry in update_xml section | Add product_security.xml file entry in update_xml section
bzr revid: mga@tinyerp.com-c1c968b6c0a6dd356a1ae7bc971a2daa2356a46d | Python | agpl-3.0 | hbrunn/OpenUpgrade,jeasoft/odoo,FlorianLudwig/odoo,colinnewell/odoo,alhashash/odoo,jesramirez/odoo,lsinfo/odoo,rowemoore/odoo,sysadminmatmoz/OCB,JGarcia-Panach/odoo,dariemp/odoo,fgesora/odoo,takis/odoo,kirca/OpenUpgrade,tinkerthaler/odoo,Antiun/odoo,factorlibre/OCB,stonegithubs/odoo,matrixise/odoo,dllsf/odootest,Endika... | ---
+++
@@ -25,7 +25,7 @@
Print product labels with barcodes.
""",
"update_xml" : ["product_data.xml","product_report.xml",
- "product_view.xml", "pricelist_view.xml"],
+ "product_view.xml", "pricelist_view.xml","product_security.xml"],
"active": False,
"installable": True
} |
a3ee55cf4d9182247dcc7a42b0336c467dce9e3e | linter.py | linter.py | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}: {severity}: {message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\... | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}:{column}:{severity}:{id}:{message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+... | Add cppcheck issue id as code field | Add cppcheck issue id as code field | Python | mit | SublimeLinter/SublimeLinter-cppcheck | ---
+++
@@ -4,16 +4,16 @@
class Cppcheck(Linter):
cmd = (
'cppcheck',
- '--template={file}:{line}: {severity}: {message}',
+ '--template={file}:{line}:{column}:{severity}:{id}:{message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
reg... |
336fbbd82a09469a7ac7d0eb850daa6a55f42669 | ctypescrypto/__init__.py | ctypescrypto/__init__.py | """
Interface to some libcrypto functions
"""
from ctypes import CDLL, c_char_p
def config(filename=None):
"""
Loads OpenSSL Config file. If none are specified, loads default
(compiled in) one
"""
libcrypto.OPENSSL_config(filename)
__all__ = ['config']
libcrypto = CDLL("libcrypto.s... | """
Interface to some libcrypto functions
"""
from ctypes import CDLL, c_char_p
from ctypes.util import find_library
import sys
def config(filename=None):
"""
Loads OpenSSL Config file. If none are specified, loads default
(compiled in) one
"""
libcrypto.OPENSSL_config(filename)
__a... | Use find_library to search for openssl libs | Use find_library to search for openssl libs
| Python | mit | vbwagner/ctypescrypto | ---
+++
@@ -5,6 +5,8 @@
from ctypes import CDLL, c_char_p
+from ctypes.util import find_library
+import sys
def config(filename=None):
"""
@@ -15,6 +17,14 @@
__all__ = ['config']
-libcrypto = CDLL("libcrypto.so.1.0.0")
+if sys.platform.startswith('win'):
+ __libname__ = find_library('libeay32')
+... |
024ddea9e3dc5ab2702b08c860e6df8702b3e5e8 | captain_hook/endpoint.py | captain_hook/endpoint.py | from __future__ import absolute_import
from os.path import abspath
from os.path import dirname
from flask import Flask, request
import yaml
import utils.config
from services import find_services
from comms import find_and_load_comms
CONFIG_FOLDER = dirname(dirname(abspath(__file__)))
application = Flask(__name__)
... | from __future__ import absolute_import
from os.path import abspath
from os.path import dirname
from flask import Flask, request
import yaml
import utils.config
from services import find_services
from comms import find_and_load_comms
CONFIG_FOLDER = dirname(dirname(abspath(__file__)))
application = Flask(__name__)
... | Make services only receive their related configs | Make services only receive their related configs
| Python | apache-2.0 | brantje/captain_hook,brantje/telegram-github-bot,brantje/telegram-github-bot,brantje/captain_hook,brantje/telegram-github-bot,brantje/captain_hook | ---
+++
@@ -26,7 +26,7 @@
request,
request.get_json(),
comms,
- config
+ config[service]
).execute()
|
694651b5c143e4ce1fd3de25500909c1a16faf95 | api/podcasts/controller.py | api/podcasts/controller.py | from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts() -> list[PodcastDetails]:... | from typing import List
from django.core.cache import cache
from .models import PodcastProvider
from .remote.interface import PodcastDetails
from .remote.timbre import fetch_podcasts, fetch_podcast
__all__ = ['fetch_cached_podcasts', 'fetch_cached_podcast']
CACHE_KEY = "76_timbre_feeds"
def fetch_cached_podcasts()... | Fix typehint that is invalid in python 3.8 | Fix typehint that is invalid in python 3.8
| Python | mit | urfonline/api,urfonline/api,urfonline/api | ---
+++
@@ -1,3 +1,5 @@
+from typing import List
+
from django.core.cache import cache
from .models import PodcastProvider
@@ -8,7 +10,7 @@
CACHE_KEY = "76_timbre_feeds"
-def fetch_cached_podcasts() -> list[PodcastDetails]:
+def fetch_cached_podcasts() -> List[PodcastDetails]:
cached_feeds = cache.get(C... |
3a7e87be0cc42b47375baec22ffdb978cb21847c | main.py | main.py | #!/usr/bin/env python3
import requests
AUTH_TOKEN = open("config/auth_token").read().strip()
USER_ID = open("config/user_id").read().strip()
BASE_URL = "https://api.telegram.org/bot" + AUTH_TOKEN + "/"
def send_request(command, **params):
requests.get(BASE_URL + command, params=params)
def send_message(chat_... | #!/usr/bin/env python3
import requests
CONFIG_DIR = "config"
class TelegramBotApi:
def __init__(self, auth_token):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
def send_message(self, chat_id, text):
self.__send_request("sendMessage", chat_id=chat_id, text=text)
def... | Create TelegramBotApi and Config classes | Create TelegramBotApi and Config classes
To clean up code
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -2,18 +2,35 @@
import requests
-AUTH_TOKEN = open("config/auth_token").read().strip()
-USER_ID = open("config/user_id").read().strip()
-
-BASE_URL = "https://api.telegram.org/bot" + AUTH_TOKEN + "/"
+CONFIG_DIR = "config"
-def send_request(command, **params):
- requests.get(BASE_URL + command, ... |
46fc845f76cfc244e6dff98a152221f7c3044386 | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
import inspect
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spaw... | from SCons.Script import *
import shlex
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.... | Fix testHarness call for Windows | Fix testHarness call for Windows
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang | ---
+++
@@ -1,5 +1,5 @@
from SCons.Script import *
-import inspect
+import shlex
def run_tests(env):
@@ -22,13 +22,9 @@
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
- path = inspect.getfile(inspect.currentframe())
- home = os.path.dirnam... |
6612978356a9b40e3a4b663c61b8e5ab96316623 | examples/async_server.py | examples/async_server.py | from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
def filter_handler(address, *args):
print(f"{address}: {args}")
dispatcher = Dispatcher()
dispatcher.map("/filter", filter_handler)
ip = "127.0.0.1"
port = 1337
async def loop():
"""Example mai... | import sys
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
def filter_handler(address, *args):
print(f"{address}: {args}")
dispatcher = Dispatcher()
dispatcher.map("/filter", filter_handler)
ip = "127.0.0.1"
port = 1337
async def loop():
"""... | Support Python 3.6 event loops in this example | Support Python 3.6 event loops in this example
| Python | unlicense | attwad/python-osc | ---
+++
@@ -1,3 +1,4 @@
+import sys
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio
@@ -30,4 +31,10 @@
transport.close() # Clean up serve endpoint
-asyncio.run(init_main())
+if sys.version_info >= (3, 7):
+ asyncio.run(init_main())
+else:... |
709e1562e61110ba94ae7581952bc5233ee1035e | main.py | main.py | import argparse
import logging
from create_dataset import *
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
parser.add_argument('--type', help='pickle or lmd... | import argparse
import logging
from create_dataset import *
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
parser.add_argument('-type', help='pickle or lmdb... | Adjust the interface for split function | Adjust the interface for split function
| Python | mit | CorcovadoMing/DataLoader,CorcovadoMing/DataLoader | ---
+++
@@ -6,24 +6,47 @@
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO)
parser = argparse.ArgumentParser(description='Data Loader')
- parser.add_argument('--type', help='pickle or lmdb')
- parser.add_argument('... |
6d03be0c21ac21e9d5ed826c5fe4991fa01743cb | main.py | main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import Tool
import time
from Tieba import Tieba
def main():
print("Local Time:", time.asctime(time.localtime()))
# Read Cookies
cookies = Tool.load_cookies_path(".")
for cookie in cookies:
# Login
user = Tieba(cookie)
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import Tool
import time
from Tieba import Tieba
def main():
print("Local Time:", time.asctime(time.localtime()))
# Read Cookies
cookies = Tool.load_cookies_path(".")
for cookie in cookies:
# Login
user = Tieba(cookie)
# List Likes
... | Change newline character to LF | Change newline character to LF
| Python | apache-2.0 | jiangzc/TiebaSign | |
9dc068f947cbd5ca29b324436496d2d78f55edf7 | src/trajectory/trajectory.py | src/trajectory/trajectory.py | #!/usr/bin/env python
import math
from geometry_msgs.msg import Point
class NegativeTimeException(Exception):
pass
class Trajectory:
def __init__(self):
self.position = Point()
def get_position_at(self, t):
if t < 0:
raise NegativeTimeException()
| #!/usr/bin/env python
import math
from twisted.conch.insults.insults import Vector
from geometry_msgs.msg import Point
class NegativeTimeException(Exception):
pass
class Trajectory:
def __init__(self):
self.position = Point()
def get_position_at(self, t):
if t < 0:
raise Neg... | Implement __abs__ and __sub__ dunder methods | feat: Implement __abs__ and __sub__ dunder methods
Implement methods which are required to apply assertEqual and assertAlmostEqual to points. | Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
import math
+from twisted.conch.insults.insults import Vector
from geometry_msgs.msg import Point
@@ -14,3 +15,14 @@
def get_position_at(self, t):
if t < 0:
raise NegativeTimeException()
+
+def abs_vector(self):
+ return (self.x * self... |
92d2ff8a16b7419123a848f98ec8594694c5203a | lib/python2.6/aquilon/client/depends.py | lib/python2.6/aquilon/client/depends.py | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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... | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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... | Fix imports when using the client on Solaris | Fix imports when using the client on Solaris
Previously the incorrect syntax had been used for inserting an item at
the beginning of sys.path.
Change-Id: I98a1451dd84619a0ba5f5be3dc4163509b867149
Addresses-Issue: Jira/AQUILON-1276
Reviewed-by: Gabor Gombas <3bb8c49439d9d044594e1c6967f991d0b4248a64@morganstanley.com>
| Python | apache-2.0 | stdweird/aquilon,quattor/aquilon,stdweird/aquilon,stdweird/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,quattor/aquilon,quattor/aquilon | ---
+++
@@ -31,4 +31,4 @@
ms.version.addpkg("ctypes", "1.0.2")
# required to move the ctypes path before the core paths
- sys.path[0] = sys.path.pop()
+ sys.path.insert(0, sys.path.pop()) |
1923fdf26f2df092a52318dfcc91825fa10fac40 | mesh.py | mesh.py | #!/usr/bin/env python3
import os
import shutil
import sys
import traceback
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
print('%s $ ' % os.getcwd(), end='', flush=True)
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def r... | #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s $ ' % os.getcwd()
def read_command():
line = input(prompt())
... | Add readline support with vi keybindings | Add readline support with vi keybindings
| Python | mit | mmichie/mesh | ---
+++
@@ -3,21 +3,25 @@
import os
import shutil
import sys
+import readline
import traceback
+
+readline.parse_and_bind('tab: complete')
+readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
- print('%s $ ' % os.getcwd(), end='', flush=True)
+ return '%s... |
bd5223af36fc167ce48bfa5c97f8a3fd79a7995a | camera_selection/scripts/camera_selection.py | camera_selection/scripts/camera_selection.py | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,P... | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,P... | Add camera selection based on desired feed and camera number | Add camera selection based on desired feed and camera number
| Python | mit | vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control | ---
+++
@@ -20,12 +20,15 @@
def callback(self, msg):
+ # Get pin map for relevant feed
feed_pin_map = PIN_MAP_LIST[msg.feed]
- for i, level in enumerate(msg.pin_values):
- if level:
- GPIO.output(feed_pin_map[i], GPIO.HIGH)
+ # Convert selected camera t... |
65ede498c28dc37b96bc1a2d435f5714c9a4eb1e | cms/middleware/media.py | cms/middleware/media.py | from django.forms.widgets import Media
from django.utils.encoding import smart_unicode
from django.conf import settings
from cms.middleware.toolbar import HTML_TYPES
def inster_before_tag(string, tag, insertion):
no_case = string.lower()
index = no_case.find("<%s" % tag.lower())
if index > -1:
star... | from django.forms.widgets import Media
from django.utils.encoding import smart_unicode
from django.conf import settings
from cms.middleware.toolbar import HTML_TYPES
def inster_before_tag(string, tag, insertion):
no_case = string.lower()
index = no_case.find("<%s" % tag.lower())
if index > -1:
star... | Fix forgotten 'request' parameter to hasattr | Fix forgotten 'request' parameter to hasattr
| Python | bsd-3-clause | sephii/django-cms,mkoistinen/django-cms,cyberintruder/django-cms,andyzsf/django-cms,isotoma/django-cms,takeshineshiro/django-cms,SachaMPS/django-cms,sznekol/django-cms,pbs/django-cms,chkir/django-cms,stefanw/django-cms,vad/django-cms,ScholzVolkmer/django-cms,webu/django-cms,VillageAlliance/django-cms,intip/django-cms,c... | ---
+++
@@ -28,7 +28,7 @@
request.placeholder_media = Media()
def process_response(self, request, response):
- if self.inject_media(request, response) and hasattr('placeholder_media'):
+ if self.inject_media(request, response) and hasattr(request,'placeholder_media'):
... |
daac5f26c07045ad162a481d035359dd17227c91 | Lib/test/test_imaplib.py | Lib/test/test_imaplib.py | from test_support import verify,verbose
import imaplib
import time
# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.
timevalues = [2000000000, 2000000000.0, time.localtime(2000000000),
"18... | import imaplib
import time
# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.
timevalues = [2000000000, 2000000000.0, time.localtime(2000000000),
"18-May-2033 05:33:20 +0200"]
for t in tim... | Remove unused imports, clean up trailing whitespace. | Remove unused imports, clean up trailing whitespace.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,3 @@
-from test_support import verify,verbose
import imaplib
import time
@@ -11,4 +10,3 @@
for t in timevalues:
imaplib.Time2Internaldate(t)
- |
6dd523e0d92c39f1a3e4c9be2dac0442535bb88f | changes/backends/jenkins/generic_builder.py | changes/backends/jenkins/generic_builder.py | from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
def get_job_parameters(self, job, ... | from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
def get_job_parameters(self, job, ... | Fix target_id support in JenkinsGenericBuilder | Fix target_id support in JenkinsGenericBuilder
| Python | apache-2.0 | wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes | ---
+++
@@ -7,8 +7,9 @@
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
- def get_job_parameters(self, job, script=None):
- params = super(JenkinsGenericBuilder, self).get_job_parameters(job)
+ def get_job_parameters(self, job, script=... |
7b6c3b4af18746ad02169a93270fc13579c60829 | pycket/targetpycket.py | pycket/targetpycket.py | from pycket.expand import load_json_ast_rpython
from pycket.interpreter import interpret_one
from pycket.error import SchemeException
from rpython.rlib import jit
def main(argv):
jit.set_param(None, "trace_limit", 20000)
# XXX crappy argument handling
try:
index = argv.index("--jit")
except Va... | from pycket.expand import load_json_ast_rpython
from pycket.interpreter import interpret_one
from pycket.error import SchemeException
from rpython.rlib import jit
from rpython.rlib.objectmodel import we_are_translated
def main(argv):
jit.set_param(None, "trace_limit", 20000)
# XXX crappy argument handling
... | Add auto-pdb fallback when not in translated mode for target | Add auto-pdb fallback when not in translated mode for target
| Python | mit | pycket/pycket,pycket/pycket,samth/pycket,krono/pycket,samth/pycket,vishesh/pycket,samth/pycket,magnusmorton/pycket,pycket/pycket,krono/pycket,magnusmorton/pycket,magnusmorton/pycket,krono/pycket,cderici/pycket,cderici/pycket,vishesh/pycket,vishesh/pycket,cderici/pycket | ---
+++
@@ -3,6 +3,8 @@
from pycket.error import SchemeException
from rpython.rlib import jit
+
+from rpython.rlib.objectmodel import we_are_translated
def main(argv):
jit.set_param(None, "trace_limit", 20000)
@@ -36,5 +38,15 @@
return main
if __name__ == '__main__':
- import sys
- main(sys.... |
ad73c91d4e2b2d5faed35420a1393d016af84e40 | tests/test_event_manager/test_attribute.py | tests/test_event_manager/test_attribute.py | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
... | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
... | Add test for attribute instance assertion | Add test for attribute instance assertion
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -9,6 +9,10 @@
class TestAttribute(BaseTest):
+ def test_name_should_not_be_instance(self):
+ with self.assertRaises(AssertionError):
+ Attribute(name='instance')
+
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test' |
b5cab8fe05899891e4508cb686d40d88e3c5b955 | tests/unit/geometry/GenericGeometryTest.py | tests/unit/geometry/GenericGeometryTest.py | import openpnm as op
class GenericGeometryTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)... | import openpnm as op
class GenericGeometryTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)... | Augment unit test for show_hist | Augment unit test for show_hist
| Python | mit | PMEAL/OpenPNM | ---
+++
@@ -15,12 +15,29 @@
mgr.clear()
def test_plot_histogram(self):
+ # Test default args
self.geo.show_hist()
- self.geo.show_hist(props=['pore.diameter', 'pore.volume',
- 'throat.length'])
- self.geo.show_hist(props=['pore.diameter', ... |
2c73d919273b1660af40053afa198a42278c07a9 | tests/qtgui/qdatastream_gui_operators_test.py | tests/qtgui/qdatastream_gui_operators_test.py | # -*- coding: utf-8 -*-
import unittest
import sys
from PySide import QtGui, QtCore
class QAppPresence(unittest.TestCase):
def testQPixmap(self):
ds = QtCore.QDataStream()
p = QtGui.QPixmap()
ds << p
ds >> p
if __name__ == '__main__':
app = QtGui.QApplication([])
unitte... | # -*- coding: utf-8 -*-
import unittest
import sys
from PySide.QtCore import QDataStream, QByteArray, QIODevice, Qt
from PySide.QtGui import QPixmap, QColor
from helper import UsesQApplication
class QPixmapQDatastream(UsesQApplication):
'''QDataStream <<>> QPixmap'''
def setUp(self):
super(QPixmapQ... | Fix QDataStream <</>> QPixmap test | Fix QDataStream <</>> QPixmap test
| Python | lgpl-2.1 | BadSingleton/pyside2,IronManMark20/pyside2,qtproject/pyside-pyside,M4rtinK/pyside-android,gbaty/pyside2,RobinD42/pyside,enthought/pyside,M4rtinK/pyside-bb10,enthought/pyside,enthought/pyside,qtproject/pyside-pyside,enthought/pyside,BadSingleton/pyside2,IronManMark20/pyside2,IronManMark20/pyside2,enthought/pyside,IronMa... | ---
+++
@@ -3,17 +3,33 @@
import unittest
import sys
-from PySide import QtGui, QtCore
+from PySide.QtCore import QDataStream, QByteArray, QIODevice, Qt
+from PySide.QtGui import QPixmap, QColor
+
+from helper import UsesQApplication
+
+class QPixmapQDatastream(UsesQApplication):
+ '''QDataStream <<>> QPixmap'... |
6129a57ab8b7de1a4189706a966b32174182c086 | server.py | server.py | from flask import Flask
# Create Flask application
app = Flask(__name__)
@app.route('/inventory')
def index():
""" Intro page of the inventory API
This method will only return some welcome words.
Returns:
response: welcome words in json format and status 200
Todo:
* Finish the implementations.
... | from flask import Flask
# Create Flask application
app = Flask(__name__)
@app.route('/inventory')
def index():
""" Intro page of the inventory API
This method will only return some welcome words.
Returns:
response: welcome words in json format and status 200
Todo:
* Finish the implementations.
... | Create a GET products method | Create a GET products method
| Python | mit | devops-foxtrot-s17/inventory,devops-foxtrot-s17/inventory | ---
+++
@@ -19,6 +19,24 @@
"""
pass
+@app.route('/inventory/products', methods=['GET'])
+def get_product_list():
+ """ Get info about all products
+
+ This method will get the info about all the products
+
+ Args:
+ no arguments
+
+ Returns:
+ response: product information(product id, loca... |
cc04dc53dd992b14b2f56f50f3efbfde83d5154d | dodo.py | dodo.py | from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
... | from doitpy.pyflakes import Pyflakes
DOIT_CONFIG = {'default_tasks': ['pyflakes', 'test', 'doctest']}
def task_pyflakes():
yield Pyflakes().tasks('*.py')
def task_test():
return {
'actions': ['py.test'],
'file_dep': ['configclass.py', 'test_configclass.py'],
}
def task_doctest():
... | Fix call to "coverage run" | doit: Fix call to "coverage run"
| Python | mit | schettino72/configclass | ---
+++
@@ -22,7 +22,7 @@
def task_coverage():
return {
'actions': [
- 'coverage run --source=configclass.py,test_configclass.py `which py.test`',
+ 'coverage run --source=configclass,test_configclass `which py.test`',
'coverage report --show-missing'],
'verb... |
ee2ecf60ea2fdbfe7f6c4f9ccc7275d534eeeacf | test_proj/urls.py | test_proj/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'do... | try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),... | Support for Django > 1.4 for test proj | Support for Django > 1.4 for test proj
| Python | mit | glic3rinu/django-admin-tools,artscoop/django-admin-tools,artscoop/django-admin-tools,artscoop/django-admin-tools,glic3rinu/django-admin-tools,glic3rinu/django-admin-tools,glic3rinu/django-admin-tools,artscoop/django-admin-tools | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import *
+try:
+ from django.conf.urls import patterns, url, include
+except ImportError: # django < 1.4
+ from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
|
eaa85b0fe69e4ff020cd269007fa1a5c7f864b53 | admin/common_auth/models.py | admin/common_auth/models.py | from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
| from django.db import models
class AdminProfile(models.Model):
user = models.OneToOneField('osf.OSFUser', related_name='admin_profile')
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
class Meta:
# custom permissions ... | Add custom permissions to admin profile for spam, metrics, and prereg | Add custom permissions to admin profile for spam, metrics, and prereg
| Python | apache-2.0 | mattclark/osf.io,crcresearch/osf.io,acshi/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,caneruguz/osf.io,binoculars/osf.io,caneruguz/osf.io,cslzchen/osf.io,felliott/osf.io,crcresearch/osf.io,hmoco/osf.io,baylee-d/osf.io,caseyrollins/osf.io,acshi/osf.io,leb2dg/osf.io,erinspace/osf.io,Johnetordoff/osf.io,chennan47/osf.io,s... | ---
+++
@@ -7,3 +7,14 @@
desk_token = models.CharField(max_length=45, blank=True)
desk_token_secret = models.CharField(max_length=45, blank=True)
+
+
+ class Meta:
+ # custom permissions for use in the OSF Admin App
+ permissions = (
+ ('mark_spam', 'Can mark comments, projects... |
275c39faa02dc0bd4f8b9d9bd2a012eaee12a338 | nose2/tests/functional/test_coverage.py | nose2/tests/functional/test_coverage.py | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | Fix regex matching coverage output | Fix regex matching coverage output
The coverage library now returns the file extensions.
| Python | bsd-2-clause | ojengwa/nose2,ptthiem/nose2,ptthiem/nose2,little-dude/nose2,ojengwa/nose2,little-dude/nose2 | ---
+++
@@ -16,7 +16,7 @@
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
- stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS)
+ stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRun... |
8a509fd2b6bfa5114986df5548132ab41eefff13 | lightstep/util.py | lightstep/util.py | """ Utility functions
"""
import random
import time
from . import constants
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol = 'https://'
else:
protocol = 'http://'... | """ Utility functions
"""
import random
import time
from . import constants
guid_rng = random.Random() # Uses urandom seed
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol =... | Use a private RNG for guids. Avoids potential for trouble w/ the global instance. | Use a private RNG for guids. Avoids potential for trouble w/ the global instance.
| Python | mit | lightstephq/lightstep-tracer-python | ---
+++
@@ -3,6 +3,8 @@
import random
import time
from . import constants
+
+guid_rng = random.Random() # Uses urandom seed
def _service_url_from_hostport(secure, host, port):
"""
@@ -20,7 +22,7 @@
"""
Construct a guid - random 64 bit integer converted to a string.
"""
- return str(rand... |
64db9a503322ce1ee61c64afbdc38f367c3d6627 | guardian/testapp/tests/management_test.py | guardian/testapp/tests/management_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.management import create_anonymous_user
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(Simpl... | from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymo... | Use unit test.TestCase instead of SimpleTestCase | Use unit test.TestCase instead of SimpleTestCase
| Python | bsd-2-clause | calvinpy/django-guardian,vovanbo/django-guardian,loop0/django-guardian,frwickst/django-guardian,thedrow/django-guardian,emperorcezar/django-guardian,alexshin/django-guardian,calvinpy/django-guardian,flisky/django-guardian,vitan/django-guardian,sustainingtechnologies/django-guardian,rfleschenberg/django-guardian,frwicks... | ---
+++
@@ -1,17 +1,19 @@
from __future__ import absolute_import
from __future__ import unicode_literals
-from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
+from guardian.compat import unittest
from guardian.management import create_anonymous_use... |
2e40bccd158d0dd3a8e741704f055dbe7a04e3a5 | heat/db/sqlalchemy/migrate_repo/manage.py | heat/db/sqlalchemy/migrate_repo/manage.py | #!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False')
| #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Add Apache 2.0 license to source file | Add Apache 2.0 license to source file
As per OpenStack licensing guide lines [1]:
[H102 H103] Newly contributed Source Code should be licensed under
the Apache 2.0 license.
[H104] Files with no code shouldn't contain any license header nor
comments, and must be left completely empty.
[1] http://docs.openstack.org/dev... | Python | apache-2.0 | openstack/heat,noironetworks/heat,openstack/heat,noironetworks/heat | ---
+++
@@ -1,4 +1,17 @@
#!/usr/bin/env python
+
+# 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 applic... |
c10badab9b93eb021b1942475c681042292c182c | scrapi/harvesters/boise_state.py | scrapi/harvesters/boise_state.py | '''
Harvester for the ScholarWorks for the SHARE project
Example API call: http://scholarworks.boisestate.edu/do/oai/?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
l... | '''
Harvester for the ScholarWorks for the SHARE project
Example API call: http://scholarworks.boisestate.edu/do/oai/?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
l... | Update longname for Boise state | Update longname for Boise state
| Python | apache-2.0 | CenterForOpenScience/scrapi,CenterForOpenScience/scrapi | ---
+++
@@ -10,7 +10,7 @@
class Boise_stateHarvester(OAIHarvester):
short_name = 'boise_state'
- long_name = 'ScholarWorks'
+ long_name = 'Boise State University ScholarWorks'
url = 'http://scholarworks.boisestate.edu'
base_url = 'http://scholarworks.boisestate.edu/do/oai/' |
ac4f5451baaefd67392d9b908c9ccffc4083a9ad | fluidsynth/fluidsynth.py | fluidsynth/fluidsynth.py | from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_... | from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_... | Change the LD search path | Change the LD search path
| Python | mit | paultag/python-fluidsynth | ---
+++
@@ -18,4 +18,4 @@
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
-C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
+C = ffi.dlopen("libfluidsynth.so.1") |
894060b4e4a59d1626cf2b9d80b5184371d79fb9 | mopidy/mixers/alsa.py | mopidy/mixers/alsa.py | import alsaaudio
from mopidy.mixers import BaseMixer
class AlsaMixer(BaseMixer):
"""
Mixer which uses the Advanced Linux Sound Architecture (ALSA) to control
volume.
"""
def __init__(self, *args, **kwargs):
super(AlsaMixer, self).__init__(*args, **kwargs)
self._mixer = alsaaudio.M... | import alsaaudio
import logging
from mopidy.mixers import BaseMixer
logger = logging.getLogger('mopidy.mixers.alsa')
class AlsaMixer(BaseMixer):
"""
Mixer which uses the Advanced Linux Sound Architecture (ALSA) to control
volume.
"""
def __init__(self, *args, **kwargs):
super(AlsaMixer, ... | Make AlsaMixer work on hosts without a mixer named 'Master' | Make AlsaMixer work on hosts without a mixer named 'Master'
| Python | apache-2.0 | tkem/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,vrs01/mopidy,dbrgn/mopidy,adamcik/mopidy,ali/mopidy,dbrgn/mopidy,hkariti/mopidy,bencevans/mopidy,mopidy/mopidy,swak/mopidy,glogiotatidis/mopidy,priestd09/mopidy,tkem/mopidy,abarisain/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,priestd09/mopidy,jodal/mopidy,hkariti/mopidy,db... | ---
+++
@@ -1,6 +1,9 @@
import alsaaudio
+import logging
from mopidy.mixers import BaseMixer
+
+logger = logging.getLogger('mopidy.mixers.alsa')
class AlsaMixer(BaseMixer):
"""
@@ -10,7 +13,16 @@
def __init__(self, *args, **kwargs):
super(AlsaMixer, self).__init__(*args, **kwargs)
- ... |
4b0c8371bf08ff2d0c3f7c64dd5867d5732d3531 | doc/java/lang.py | doc/java/lang.py | import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._... | import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._... | Fix java.nio.file import in AutoCloseable example | Fix java.nio.file import in AutoCloseable example
| Python | apache-2.0 | originell/jpype,originell/jpype,originell/jpype,originell/jpype,originell/jpype | ---
+++
@@ -25,7 +25,7 @@
.. code-block:: python
- from java.nio.files import Files, Paths
+ from java.nio.file import Files, Paths
with Files.newInputStream(Paths.get("foo")) as fd:
# operate on the input stream
|
ffc3bec9d488135ba2331386cec3279283927217 | bamp/helpers/ui.py | bamp/helpers/ui.py | import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results ar... | import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results ar... | Enable passing str to echo | Enable passing str to echo
| Python | mit | inirudebwoy/bamp | ---
+++
@@ -27,13 +27,16 @@
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
- :type messages: list(str)
+ :type messages: list(str) or str
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
... |
3504b4f3687fdf3ac52d6d7df9306519762900a7 | ndaparser/__init__.py | ndaparser/__init__.py | import ndaparser
if __name__ == "__main__" :
trns = ndaparser.parseLine("T10188000060SCTSZFW3GT3WU1B 1501131501131501121710Viitemaksu +000000000000002800 HAKKERI HEIKKI HOKSAAVA A 00000000000000111012 ")
print(trns)
| import ndaparser
if __name__ == "__main__" :
transactions = [];
with open("./testdata.nda") as f:
for line in f:
transaction = ndaparser.parseLine(line)
if transaction is not None:
transactions.append(transaction)
for transaction in transactions:
pri... | Read testdata from file, print valid transactions | Read testdata from file, print valid transactions
| Python | mit | rambo/asylum,hacklab-fi/asylum,ojousima/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,ojousima/asylum,ojousima/asylum,jautero/asylum,rambo/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,ojousima/asylum,jautero/asylum,jautero/asylum,hacklab-fi/asylum,hacklab-fi/... | ---
+++
@@ -1,5 +1,11 @@
import ndaparser
if __name__ == "__main__" :
- trns = ndaparser.parseLine("T10188000060SCTSZFW3GT3WU1B 1501131501131501121710Viitemaksu +000000000000002800 HAKKERI HEIKKI HOKSAAVA A 00000000000000111012 ")
- print(trns)
+ ... |
087925b336794b71675b31b70f845042e1f635fb | metro_accounts/metro_account.py | metro_accounts/metro_account.py | # -*- coding: utf-8 -*-
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selec... | # -*- coding: utf-8 -*-
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selec... | Add the SQL to update account balance direction field bal_direct | Add the SQL to update account balance direction field bal_direct
| Python | agpl-3.0 | 837278709/metro-openerp,john-wang-metro/metro-openerp,john-wang-metro/metro-openerp,837278709/metro-openerp,837278709/metro-openerp,john-wang-metro/metro-openerp | ---
+++
@@ -12,5 +12,10 @@
('c', 'Credit'),
], 'Balance Direction',)
}
+'''
+Update SQL:
+update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
+update account_account set bal_direct = ... |
82b78ed248f28709b6603315bd673337e4997c4e | pseudorandom.py | pseudorandom.py | #!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
request.headers['Content-Type'] == 'text/plain'):
... | #!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
content_type = request.headers.get('Content-Type', '')
browser = request.headers.get('User-Agent', '').lower()
if browser[:4... | Send text to wget/curl unless html content-type | Send text to wget/curl unless html content-type
| Python | mit | treyhunner/pseudorandom.name,treyhunner/pseudorandom.name | ---
+++
@@ -9,8 +9,9 @@
@app.route("/")
def index():
- if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
- request.headers['Content-Type'] == 'text/plain'):
+ content_type = request.headers.get('Content-Type', '')
+ browser = request.headers.get('User-Agent', '').lower()
+ if b... |
7b9233c157630733da688abb7c0f3fffecddd0e7 | scripts/lib/getUserPath.py | scripts/lib/getUserPath.py | def getUserPath(filename, is_command):
import lib.app, os
# Places quotation marks around the full path, to handle cases where the user-specified path / file name contains spaces
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the ex... | def getUserPath(filename, is_command):
import lib.app, os
# Places quotation marks around the full path, to handle cases where the user-specified path / file name contains spaces
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the ex... | Fix for working directory containing whitespace | Scripts: Fix for working directory containing whitespace
| Python | mpl-2.0 | MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3 | ---
+++
@@ -4,7 +4,7 @@
# However, this should only occur in situations where the output is being interpreted as part of a full command string;
# if the expected output is a stand-alone string, the quotation marks should be omitted
wrapper=''
- if is_command and filename.count(' '):
+ if is_command and (... |
4c4fd3021931e2203088a2ec578eb479a622e2c5 | blogsite/models.py | blogsite/models.py | """Collection of Models used in blogsite."""
from . import db
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
"""
# Columns
id = db.Column(db... | """Collection of Models used in blogsite."""
from . import db
from datetime import datetime
class Post(db.Model):
"""Model representing a blog post.
Attributes
----------
id : SQLAlchemy.Column
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
pub_date :... | Add Category model and expanding Post model. | Add Category model and expanding Post model.
Post model now contains a publish date and a foreign key reference
to the Category model.
| Python | mit | paulaylingdev/blogsite,paulaylingdev/blogsite | ---
+++
@@ -1,5 +1,6 @@
"""Collection of Models used in blogsite."""
from . import db
+from datetime import datetime
class Post(db.Model):
@@ -11,14 +12,24 @@
Autogenerated primary key
title : SQLAlchemy.Column
body : SQLAlchemy.Column
+ pub_date : SQLAlchemy.Column
+ Date and Time... |
d7621f5bf2e1ae30f79d1701fe5e34ee60da1a53 | go/api/go_api/tests/test_client.py | go/api/go_api/tests/test_client.py | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_request(self, mock_req):
client.request('123', 'lorem ipsum', 'GET')
mock_req.assert_cal... | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_re... | Remove a test that is no longer relevant | Remove a test that is no longer relevant
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -9,16 +9,6 @@
class ClientTestCase(TestCase):
- @patch('requests.request')
- def test_request(self, mock_req):
- client.request('123', 'lorem ipsum', 'GET')
-
- mock_req.assert_called_with(
- 'GET',
- settings.GO_API_URL,
- auth=('session_id', '123'... |
f85bcd07f34f817722b6a5af317e9dbfa2667576 | mysite/search/tasks/__init__.py | mysite/search/tasks/__init__.py | from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
run_every = timedelta(days=1)
de... | from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
run_every = timedelta(days=1)
de... | Fix the same typo in GrabLaunchpadBugs | Fix the same typo in GrabLaunchpadBugs
| Python | agpl-3.0 | moijes12/oh-mainline,sudheesh001/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,campbe13/openhatch,campbe13/openhatch,openhatch/oh-mainline,SnappleCap/oh-mainline,nirmeshk/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,heera... | ---
+++
@@ -14,7 +14,7 @@
logger.info("Started to grab lp.net bugs for %s into %s" % (
lp_project, openhatch_proj))
grab_lp_bugs(lp_project=lp_project,
- openhatch_project=openhatch_project)
+ openhatch_project=openhatch_pr... |
279f0b984209f27743791aca9cf3da7941e5d520 | zephyr/lib/minify.py | zephyr/lib/minify.py | from django.conf import settings
from hashlib import sha1
from os import path
from pipeline.compressors import SubProcessCompressor
class ClosureSourceMapCompressor(SubProcessCompressor):
def compress_js(self, js):
# js is the full text of the JavaScript source, and we can't
# easily ... | from django.conf import settings
from hashlib import sha1
from os import path
from pipeline.compressors import SubProcessCompressor
class ClosureSourceMapCompressor(SubProcessCompressor):
def compress_js(self, js):
# js is the full text of the JavaScript source, and we can't
# easily ... | Make it easier to find the source map for app.js | Make it easier to find the source map for app.js
(imported from commit bca27c9838573fb4b74e2d269b253a48702c9e1c)
| Python | apache-2.0 | gigawhitlocks/zulip,hayderimran7/zulip,dhcrzf/zulip,jackrzhang/zulip,MariaFaBella85/zulip,verma-varsha/zulip,esander91/zulip,jonesgithub/zulip,johnnygaddarr/zulip,hackerkid/zulip,joshisa/zulip,Frouk/zulip,arpitpanwar/zulip,qq1012803704/zulip,dawran6/zulip,RobotCaleb/zulip,wavelets/zulip,qq1012803704/zulip,jerryge/zulip... | ---
+++
@@ -11,8 +11,18 @@
# name. So we just pick a unique arbitrary name. This is
# okay because we can figure out from the source map file
# contents which JavaScript files it corresponds to.
- source_map = path.join(settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR,
- ... |
0a5e4194fe06b20b4eaacaa9452403f70076ccd3 | base_solver.py | base_solver.py | #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def run(self):
start_time = datetime.now... | #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
class RunSolverFirst(Exception):
pass
class BaseSolver(object):
task = None
best_solution = None
best_distance = float('inf')
search_time = None
cycles = 0
def __init__(self, task):
self.task = task
def ... | Add run solver first exception type | Add run solver first exception type
| Python | mit | Cosiek/KombiVojager | ---
+++
@@ -2,6 +2,10 @@
# encoding: utf-8
from datetime import datetime
+
+class RunSolverFirst(Exception):
+ pass
+
class BaseSolver(object):
task = None
@@ -27,7 +31,7 @@
def get_summary(self):
if self.best_solution is None:
- return u'Run the solver first'
+ ra... |
1069565b596d3bc13b99bcae4ec831c2228e7946 | PrinterApplication.py | PrinterApplication.py | from Cura.WxApplication import WxApplication
import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
super(PrinterApplication, sel... | from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
super(PrinterApplication, self).run()
| Move WxApplication into its own Wx submodule | Move WxApplication into its own Wx submodule
| Python | agpl-3.0 | lo0ol/Ultimaker-Cura,Curahelper/Cura,senttech/Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,bq/Ultimaker-Cura,fxtentacle/Cura,totalretribution/Cura,derekhe/Cura,ad1217/Cura,ad1217/Cura,derekhe/Cura,Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,markwal/Cura,fieldOfView/Cura,fxtentacle/Cura,hmflash/Cura,quillford/Cura,... | ---
+++
@@ -1,12 +1,8 @@
-from Cura.WxApplication import WxApplication
-
-import wx
+from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
- frame = wx.Frame(None, wx... |
4b10355d256f1a0bf6b7cc8eae1eda4b8794cb09 | indra/sources/omnipath/__init__.py | indra/sources/omnipath/__init__.py | from .api import process_from_web
from .processor import OmniPathProcessor
| """
The OmniPath module accesses biomolecular interaction data from various
curated databases using the OmniPath API (see
https://saezlab.github.io/pypath/html/index.html#webservice) and processes
the returned data into statements using the OmniPathProcessor.
Currently, the following data is collected:
- Modificatio... | Write short blurb about module and its usage | Write short blurb about module and its usage
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,bgyori/indra,sorgerlab/indra | ---
+++
@@ -1,2 +1,18 @@
+"""
+The OmniPath module accesses biomolecular interaction data from various
+curated databases using the OmniPath API (see
+https://saezlab.github.io/pypath/html/index.html#webservice) and processes
+the returned data into statements using the OmniPathProcessor.
+
+Currently, the following ... |
ad74a2d02b109308b79b5629920a23b85748e439 | photutils/conftest.py | photutils/conftest.py | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | Add scikit-image to test header information | Add scikit-image to test header information | Python | bsd-3-clause | larrybradley/photutils,astropy/photutils | ---
+++
@@ -7,3 +7,9 @@
## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
enable_deprecations_as_exceptions()
+
+# Add scikit-image to test header information
+try:
+ PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
+except NameError: # astropy < 1.0
+ pass |
da90ddfd697da5be7e0c01f183e733bbc981fe85 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
| from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return 'Hello World!'
if __name__ == '__main__':
app.run()
| Index action ready with "Hello, World!" message | Index action ready with "Hello, World!" message
| Python | mit | alexander-emelyanov/microblog,alexander-emelyanov/microblog | ---
+++
@@ -4,7 +4,8 @@
@app.route('/')
-def hello_world():
+@app.route('/index')
+def index():
return 'Hello World!'
|
a9892cc1fcb7d2911f6afba52a06a6f1c1ed9b25 | tests/test_wrap_modes.py | tests/test_wrap_modes.py | from hypothesis_auto import auto_pytest_magic
from isort import wrap_modes
auto_pytest_magic(wrap_modes.grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytes... | from hypothesis_auto import auto_pytest_magic
from isort import wrap_modes
auto_pytest_magic(wrap_modes.grid, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.vertical, auto_allow_exceptions_=(ValueError,))
auto_pytest_magic(wrap_modes.hanging_indent, auto_allow_exceptions_=(ValueError,))
auto_pytes... | Increase wrap mode test coverage | Increase wrap mode test coverage
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -13,3 +13,10 @@
auto_pytest_magic(
wrap_modes.vertical_prefix_from_module_import, auto_allow_exceptions_=(ValueError,)
)
+auto_pytest_magic(wrap_modes.vertical_hanging_indent_bracket, auto_allow_exceptions_=(ValueError,))
+
+
+def test_wrap_mode_interface():
+ assert (
+ wrap_modes._wrap_m... |
cf52a25001a3c9883caff70d3eb0318c8418fa76 | test/pyrostest/pub_foo.py | test/pyrostest/pub_foo.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
pub = rospy.Publisher('/pub_val', Int32, queue_size=10)
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
pub.publish(rospy.get_param('foo'))
if __name__ == '__main__':
pub_foo()
| #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
pub = rospy.Publisher('/pub_val', Int32, queue_size=10)
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
pub.publish(rospy.get_param('/foo'))
if __name__ == '__main__':
pub_foo()
| Use absolute path to make the node work. | Use absolute path to make the node work.
| Python | mit | gtagency/pyrostest,gtagency/pyrostest | ---
+++
@@ -9,7 +9,7 @@
def pub_foo():
rospy.init_node('pub_foo', anonymous=True)
while True:
- pub.publish(rospy.get_param('foo'))
+ pub.publish(rospy.get_param('/foo'))
if __name__ == '__main__': |
d54c54d50a17afde8dbaa8116d7475d66f787aad | pdxtrees/settings_production.py | pdxtrees/settings_production.py | """
Based on:
https://devcenter.heroku.com/articles/getting-started-with-django
"""
import settings
DEBUG = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
#DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-P... | """
Based on:
https://devcenter.heroku.com/articles/getting-started-with-django
"""
import settings
DEBUG = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
SECRET_KEY = os.environ.get('SECRET_KEY')
WSGI_APPLICATION = 'pdxtrees.wsgi... | Read secret key from env var explicitly | Read secret key from env var explicitly
| Python | mit | mattblair/pdx-trees-django,mattblair/pdx-trees-django | ---
+++
@@ -12,7 +12,10 @@
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
-#DATABASES['default'] = dj_database_url.config()
+
+SECRET_KEY = os.environ.get('SECRET_KEY')
+
+WSGI_APPLICATION = 'pdxtrees.wsgi_deploy.application'
# Honor the 'X-Forwarded-Proto' header for request.is_sec... |
66a4fc0ce6e5c07540c5e4849b829e6623df6590 | biothings/web/api/es/handlers/small_handlers.py | biothings/web/api/es/handlers/small_handlers.py | """
TODO load balancer check settings
"""
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from elasticsearch.exceptions import ElasticsearchException
from tornado.web import HTTPError
class StatusHandler(BaseESRequestHandler):
'''
Handles requests to check the status of the se... | """
TODO load balancer check settings
"""
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from elasticsearch.exceptions import ElasticsearchException
from tornado.web import HTTPError
class StatusHandler(BaseESRequestHandler):
'''
Handles requests to check the status of the se... | Rename var to comply with pylint | Rename var to comply with pylint
| Python | apache-2.0 | biothings/biothings.api,biothings/biothings.api | ---
+++
@@ -13,10 +13,10 @@
'''
async def head(self):
try:
- r = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
+ res = await self.web_settings.async_es_client.get(**self.web_settings.STATUS_CHECK)
except ElasticsearchException:
... |
da2f01c6fbeba6a0df3d6bb2c6dcf6a6ae659a76 | opentreemap/registration_backend/urls.py | opentreemap/registration_backend/urls.py | from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='regi... | from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/... | Use registration form to prevent duplicate emails | Use registration form to prevent duplicate emails
Fixes #725.
We enforce this both at the database level, and here, using django
registration's ready-made form class.
| Python | agpl-3.0 | clever-crow-consulting/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,... | ---
+++
@@ -2,6 +2,8 @@
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
+
+from registration.forms import RegistrationFormUniqueEmail
from views import RegistrationView, ActivationView
@@ -18,7 +20,7 @@
ActivationView.as_view(),
... |
fdfd26b57abfd471fca36fb1f73f739a6374ddb3 | ScannerServer/nfc_scanner.py | ScannerServer/nfc_scanner.py | import signal
import time
from pirc522 import RFID
loop = True
rfid = RFID()
util = rfid.util()
def end_read(signal, frame):
global loop
print("\nCtrl+C captured, ending read.")
loop = False
rfid.cleanup()
signal.signal(signal.SIGINT, end_read)
print("Scanning...")
while loop:
(not_found, data... | import signal
import time
from pirc522 import RFID
loop = True
rfid = RFID()
util = rfid.util()
def end_read(signal, frame):
global loop
print("\nCtrl+C captured, ending read.")
loop = False
rfid.cleanup()
signal.signal(signal.SIGINT, end_read)
print("Scanning...")
while loop:
(not_found, data... | Discard charcode 254 at end of URL | Discard charcode 254 at end of URL
| Python | mit | straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock | ---
+++
@@ -40,10 +40,13 @@
if num_chars_to_skip > 0:
num_chars_to_skip -= 1
continue
- chars.append(chr(c))
+ if c >= 200:
+ # TODO(ryok): Investigate why 254 comes at the end of URL
+ continue
if c == 0:
done_reading = True
break
+ chars.appen... |
6c3621aa5d3936953da027efde9dd3622da50d38 | virtool/indexes/models.py | virtool/indexes/models.py | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... | from sqlalchemy import Column, Enum, Integer, String
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store new index fil... | Fix incorrect column in IndexFile model | Fix incorrect column in IndexFile model
* Change `reference` to `index`.
* Removed unused import of `enum` | Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -1,5 +1,4 @@
-import enum
-from sqlalchemy import Column, Integer, String, Enum
+from sqlalchemy import Column, Enum, Integer, String
from virtool.pg.utils import Base, SQLEnum
@@ -29,5 +28,5 @@
size = Column(Integer)
def __repr__(self):
- return f"<IndexFile(id={self.id}, name={sel... |
ba2913658e3770ef73d0e7972435def32199cc08 | test.py | test.py | import random
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
def generate_data(size):
""""
x_train = []
y_train = []
for i in range(size):
x = random.randint(0, 100)
y = 2*x
x_train.append(x)
y_train.append(y)
return... | import random
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
def generate_data(size):
""""
x_train = []
y_train = []
for i in range(size):
x = random.randint(0, 100)
y = 2*x
x_train.append(x)
y_train.append(y)
return... | Fix lirear regression model loss calculation | Fix lirear regression model loss calculation
| Python | apache-2.0 | alexkorep/dogs-vs-cats | ---
+++
@@ -17,6 +17,8 @@
import numpy as np
#data = np.random.random((10000, 100))
#labels = np.random.randint(2, size=(10000, 1))
+ #data = np.random.random((10000, 2))
+ #labels = np.sum(data, (1,))
data = np.random.random((10000, 1))
labels = data*2
return data, labels
@@ -25,1... |
de16cdd72c69c232008ad22c2c45a2985d7ac99c | urls.py | urls.py | from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
... | from django.conf.urls.defaults import *
from django.conf import settings
import os
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'routez.travel.views.main_page'),
(r'^iphone$', 'routez.travel.views.iphone'),
... | Fix stoptimes in range function to actually take a full blown address | Fix stoptimes in range function to actually take a full blown address
| Python | agpl-3.0 | wlach/routez,wlach/routez | ---
+++
@@ -15,7 +15,7 @@
(r'^json/routeplan$', 'routez.travel.views.routeplan'),
(r'^stoptimes_for_stop/(\d{4})/(\d+)$',
'routez.stop.views.stoptimes_for_stop'),
- (r'^stoptimes_in_range/(\w+)/(\d+)$',
+ (r'^stoptimes_in_range/([^/]+)/(\d+)$',
'routez.stop.views.stoptimes_in_range')
... |
e1dffa732ab0a2f9468e16c026a392e3d35cdd9c | main.py | main.py | import slackclient
import time
import os
| import slackclient
import time
import os
slackClient = slackClient.SLackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
while True:
print(slackClient.rtm_read())
time.sleep(5)
| Add test of slack rtm read | Add test of slack rtm read
| Python | mit | ollien/Slack-Welcome-Bot | ---
+++
@@ -2,3 +2,9 @@
import time
import os
+slackClient = slackClient.SLackClient(os.environ["SLACK_TOKEN"])
+slackClient.rtm_connect()
+
+while True:
+ print(slackClient.rtm_read())
+ time.sleep(5) |
7d6c60898dd2708df07847253bca86049a33ed78 | SigmaPi/SigmaPi/urls.py | SigmaPi/SigmaPi/urls.py | from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'SigmaPi.views.home', name='home'),
# ur... | import warnings
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
# Turns deprecation warnings into errors
warnings.simplefilter('error', DeprecationWarning)
urlpatterns = [
# Examples:
... | Fix admin URLs; turn deprecation warnings into errors | Fix admin URLs; turn deprecation warnings into errors
| Python | mit | sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web | ---
+++
@@ -1,11 +1,16 @@
+import warnings
+
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
-# Uncomment the next two lines to enable the admin:
from django.contrib import admin
+
admin.autodiscover()
+
+# Turns deprecation warnings into ... |
56c173a9f1bd1f22448a33b044283ad0d7bcf16e | tests/test_views.py | tests/test_views.py | from django.test import LiveServerTestCase
try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
from tusclient import client
class TestUploadView(LiveServerTestCase):
def test_get_is_not_allowed(self):
response = self.client.get(... | try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
from tusclient.client import TusClient
class TestUploadView(object):
def test_get_is_not_allowed(self, client):
response = client.get(reverse('tus_upload'))
assert respo... | Refactor view to use fixtures from `pytest-django`. | Refactor view to use fixtures from `pytest-django`.
| Python | mit | alican/django-tus | ---
+++
@@ -1,22 +1,20 @@
-from django.test import LiveServerTestCase
-
try:
from django.urls import reverse
except ImportError: # django < 1.10
from django.core.urlresolvers import reverse
-from tusclient import client
+from tusclient.client import TusClient
-class TestUploadView(LiveServerTestCas... |
4b3428bca7bf9afd448d8c8da1633756a2e540fe | app/models.py | app/models.py | from app import db
from hashlib import md5
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
d... | from app import db
from hashlib import md5
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
ab... | Add more attributes for User, update db | Add more attributes for User, update db
| Python | mit | ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme,ddayguerrero/blogme | ---
+++
@@ -7,6 +7,8 @@
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
+ about_me = db.Column(db.String(140))
+ last_seen = db.Column(db.DateTime)
def ... |
e165143ff629c193a2e9c31874b66c0925de3c60 | sgpublish/io/maya.py | sgpublish/io/maya.py | from __future__ import absolute_import
from . import base
from maya import cmds
__also_reload__ = ['.base']
class Exporter(base.Exporter):
def get_previous_publish_ids(self):
ids = cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, query=True)
return set(int(x.strip()) for x in ids[0].s... | from __future__ import absolute_import
import os
from . import base
from maya import cmds
__also_reload__ = ['.base']
class Exporter(base.Exporter):
def __init__(self, *args, **kwargs):
super(Exporter, self).__init__(*args, **kwargs)
@property
def filename_hint(self):
return ... | Add more defaults to Maya exporter | Add more defaults to Maya exporter | Python | bsd-3-clause | westernx/sgpublish | ---
+++
@@ -1,4 +1,6 @@
from __future__ import absolute_import
+
+import os
from . import base
@@ -9,6 +11,17 @@
class Exporter(base.Exporter):
+ def __init__(self, *args, **kwargs):
+ super(Exporter, self).__init__(*args, **kwargs)
+
+ @property
+ def filename_hint(self):
+ ... |
429d701cce7ad2cf8fb77f169c4af6f2f27562fd | db_mutex/models.py | db_mutex/models.py | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | Declare app_label in model Meta class to work with Django 1.9 | Declare app_label in model Meta class to work with Django 1.9
Fixes RemovedInDjango19Warning:
Model class db_mutex.models.DBMutex doesn't declare an explicit
app_label and either isn't in an application in INSTALLED_APPS or else
was imported before its application was loaded. This will no longer be
supported in Djan... | Python | mit | minervaproject/django-db-mutex | ---
+++
@@ -13,3 +13,6 @@
"""
lock_id = models.CharField(max_length=255, unique=True)
creation_time = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ app_label = "db_mutex" |
77d4f2bfcab2cb3ca1b8d1736c51018d69fe0940 | rpe/resources/base.py | rpe/resources/base.py | # Copyright 2019 The resource-policy-evaluation-library Authors. 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
#
# Unl... | # Copyright 2019 The resource-policy-evaluation-library Authors. 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
#
# Unl... | Remove generic factory method from Resource | Remove generic factory method from Resource
| Python | apache-2.0 | forseti-security/resource-policy-evaluation-library | ---
+++
@@ -18,32 +18,21 @@
class Resource(ABC):
- @staticmethod
- def factory(platform, **kargs):
- """ Return a resource from the appropriate platform """
- from .gcp import GoogleAPIResource
-
- resource_platform_map = {
- 'gcp': GoogleAPIResource
- }
-
- tr... |
dd472ed80ba374d719f9b1dc56fd3038f6a73dee | examples/benchmark/benchmark_twisted_names.py | examples/benchmark/benchmark_twisted_names.py | """
Benchmark on Twisted Names subsystem.
"""
from twisted.names.dns import DNSDatagramProtocol
from twisted.names.server import DNSServerFactory
from twisted.names import hosts, client
from twisted.internet import reactor
import benchmarking
@benchmarking.deferred(max_seconds=5)
class TwistedNamesBenchmarkCase(ben... | """
Benchmark on Twisted Names subsystem.
"""
from twisted.names.dns import DNSDatagramProtocol
from twisted.names.server import DNSServerFactory
from twisted.names import hosts, client
from twisted.internet import reactor
import benchmarking
@benchmarking.deferred(max_seconds=15)
class TwistedNamesBenchmarkCase(be... | Make benchmark params match Twisted's params. | Make benchmark params match Twisted's params.
| Python | mit | AlekSi/benchmarking-py | ---
+++
@@ -10,7 +10,7 @@
import benchmarking
-@benchmarking.deferred(max_seconds=5)
+@benchmarking.deferred(max_seconds=15)
class TwistedNamesBenchmarkCase(benchmarking.BenchmarkCase):
def setUp(self):
controller = DNSServerFactory([hosts.Resolver()])
@@ -22,7 +22,7 @@
return self._port.... |
9e013b6123e3eefec64e9e479741a16fe4727ad6 | plugins/python/org.eclipse.eclipsemonkey.lang.python.examples/samples/scripts/Views__Web_View.py | plugins/python/org.eclipse.eclipsemonkey.lang.python.examples/samples/scripts/Views__Web_View.py | #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def ch... | #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def changing(se... | Correct sample with new qualified name of the class | Correct sample with new qualified name of the class | Python | epl-1.0 | adaussy/eclipse-monkey-revival,adaussy/eclipse-monkey-revival,adaussy/eclipse-monkey-revival | ---
+++
@@ -5,7 +5,7 @@
#
from org.eclipse.swt.browser import LocationListener
-from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView
+from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListene... |
1db1dfe35a97080286577b78f4708cc9afd82232 | rx/checkedobserver.py | rx/checkedobserver.py | from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
... | from six import add_metaclass
from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 -... | Use extension method for Observer.checked | Use extension method for Observer.checked
| Python | mit | dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY | ---
+++
@@ -1,4 +1,7 @@
+from six import add_metaclass
+
from rx import Observer
+from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
@@ -35,18 +38,18 @@
if self._state == 0:
self._state = 1
+@a... |
f65f18ceec8abf468b1426cf819c806f2d1d7ff8 | auslib/migrate/versions/009_add_rule_alias.py | auslib/migrate/versions/009_add_rule_alias.py | from sqlalchemy import Column, String, MetaData, Table
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
def add_alias(table):
alias = Column('alias', String(50), unique=True)
alias.create(table)
add_alias(Table('rules', metadata, autoload=True))
add_alias(Table('r... | from sqlalchemy import Column, String, MetaData, Table
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
alias = Column("alias", String(50), unique=True)
alias.create(Table("rules", metadata, autoload=True), unique_name="alias_unique")
history_alias = Column("alias", String(50))
... | Fix migration script to make column unique+add index. | Fix migration script to make column unique+add index.
| Python | mpl-2.0 | testbhearsum/balrog,nurav/balrog,aksareen/balrog,testbhearsum/balrog,tieu/balrog,aksareen/balrog,aksareen/balrog,tieu/balrog,nurav/balrog,nurav/balrog,testbhearsum/balrog,tieu/balrog,mozbhearsum/balrog,mozbhearsum/balrog,aksareen/balrog,mozbhearsum/balrog,nurav/balrog,testbhearsum/balrog,mozbhearsum/balrog,tieu/balrog | ---
+++
@@ -4,11 +4,11 @@
def upgrade(migrate_engine):
metadata = MetaData(bind=migrate_engine)
- def add_alias(table):
- alias = Column('alias', String(50), unique=True)
- alias.create(table)
- add_alias(Table('rules', metadata, autoload=True))
- add_alias(Table('rules_history', metada... |
6bdec176a7a43b3e6eb65a2c7e639c09a89d43bc | data_models/data_refinery_models/models.py | data_models/data_refinery_models/models.py | from django.db import models
from django.utils import timezone
class TimeTrackedModel(models.Model):
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.c... | from django.db import models
from django.utils import timezone
class TimeTrackedModel(models.Model):
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.c... | Change a comment to mention the organism taxonomy ID from NCBI. | Change a comment to mention the organism taxonomy ID from NCBI.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | ---
+++
@@ -31,7 +31,7 @@
# This field will denote where in our system the file can be found
internal_location = models.CharField(max_length=256)
- # This will at some be a meaningful integer->organism lookup thing
+ # This will utilize the organism taxonomy ID from NCBI
organism = models.Integ... |
10e040890f5dd1297aa4fa04ce2cf9e9db447d09 | sample/sample/urls.py | sample/sample/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'mini.views.index'),
url(r'^about$', 'mini.views.about'),
# Examples:
# url(r'^$', 'sample.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', 'mini.views.index', name='index'),
url(r'^about$', TemplateView.as_view(template_name='about.html'), name='about'),
# Examples:
# url(... | Use a generic TemplateView for the sample's about page | Use a generic TemplateView for the sample's about page
| Python | bsd-3-clause | tamarackapp/tamarack-collector-py | ---
+++
@@ -1,9 +1,10 @@
from django.conf.urls import patterns, include, url
from django.contrib import admin
+from django.views.generic import TemplateView
urlpatterns = patterns('',
- url(r'^$', 'mini.views.index'),
- url(r'^about$', 'mini.views.about'),
+ url(r'^$', 'mini.views.index', name='index'),... |
3373521f43b0d605bba6cc36b190c064d5a0303e | kytos/core/link.py | kytos/core/link.py | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
... | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoi... | Define Link ID as UUID | Define Link ID as UUID
| Python | mit | kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos | ---
+++
@@ -5,6 +5,8 @@
"""
import json
+
+from uuid import uuid4
from kytos.core.common import GenericEntity
@@ -16,6 +18,7 @@
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
+ self._uuid = uuid4()
supe... |
b6da3311c894ad502b32b1cb96c3b0e0a02b0b85 | blog/views.py | blog/views.py | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list, 5)
page = request.GET.get('... | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list... | Handle blogs with a bad URL slug | Handle blogs with a bad URL slug
| Python | bsd-3-clause | brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3 | ---
+++
@@ -1,4 +1,5 @@
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
+from django.http import Http404
from django.shortcuts import render
from .models import Blog
@@ -23,8 +24,11 @@
})
def post(request, slug):
- # @todo: raise a 404 error if not found
- blog = Blog.objects.get... |
e730c552c0b6095a8962f29a114069fb335d7ec6 | zinnia/urls/shortlink.py | zinnia/urls/shortlink.py | """Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
)
| """Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^e(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
)
| Add a "e" prefix to avoid issue when reaching the ID 46656 | Add a "e" prefix to avoid issue when reaching the ID 46656
| Python | bsd-3-clause | aorzh/django-blog-zinnia,marctc/django-blog-zinnia,marctc/django-blog-zinnia,dapeng0802/django-blog-zinnia,ghachey/django-blog-zinnia,aorzh/django-blog-zinnia,ZuluPro/django-blog-zinnia,1844144/django-blog-zinnia,Maplecroft/django-blog-zinnia,extertioner/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blo... | ---
+++
@@ -7,7 +7,7 @@
urlpatterns = patterns(
'',
- url(r'^(?P<token>[\da-z]+)/$',
+ url(r'^e(?P<token>[\da-z]+)/$',
EntryShortLink.as_view(),
name='entry_shortlink'),
) |
f01c6d22d30e175d120e5ffe10bef93378375ea7 | example/myshop/models/__init__.py | example/myshop/models/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import Ca... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import Ca... | Use __all__ for restricted exports | Use __all__ for restricted exports
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,khchine5/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,awesto/django-shop,jrief/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-sho... | ---
+++
@@ -26,3 +26,6 @@
from shop.models.defaults.delivery import Delivery, DeliveryItem
from shop.models.defaults.order import Order
+
+__all__ = ['ShippingAddress', 'BillingAddress', 'Cart', 'CartItem', 'Customer', 'Order', 'OrderItem',
+ 'Commodity', 'SmartCard', 'SmartPhoneModel', 'SmartPhone', 'Deli... |
e92784a36053e6708a3eb2772f4c5cd4e16cde4a | app/base/templatetags/git.py | app/base/templatetags/git.py | import subprocess
from django.template import Library
register = Library()
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
VERSION = head.stdout.readline().strip()
except:
VERSION = u'unknown'
@register.simple_tag()
def git... | import subprocess
from django.template import Library
register = Library()
GIT_VERSION = None
@register.simple_tag()
def git_version():
global GIT_VERSION
if GIT_VERSION:
return GIT_VERSION
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell... | Make GIT_VERSION on footer more robust | [REFACTOR] Make GIT_VERSION on footer more robust
| Python | mit | internship2016/sovolo,internship2016/sovolo,internship2016/sovolo | ---
+++
@@ -3,15 +3,24 @@
register = Library()
-try:
- head = subprocess.Popen("git rev-parse --short HEAD",
- shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- VERSION = head.stdout.readline().strip()
-except:
- VERSION = u'unknown'
+GIT_VERSION = None
@register.simple_tag()
... |
59dd1dd68792b13ea75b4aaffc68983236d02ad3 | config/urls.py | config/urls.py | """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | Make sure that we pass a CSRF cookie with value | Make sure that we pass a CSRF cookie with value
We need to pass a CSRF cookie when we make a GET request because
otherwise Angular would have no way of grabing the CSRF.
| Python | mit | gopar/OhMyCommand,gopar/OhMyCommand,gopar/OhMyCommand | ---
+++
@@ -16,6 +16,7 @@
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
+from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authtoken import views
@@ -23,7 +24,7 @@
urlpatterns = [
url(r'^admin/', a... |
ec80d534e91e480a40152550db10e8be8e777f43 | pentai/ai/t_all.py | pentai/ai/t_all.py | #!/usr/bin/python
import unittest
import importlib
def iam(m_str):
""" import and add a module """
global all_tests
module = importlib.import_module("pentai.ai.%s" % m_str)
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
all_tests.addTest(suite)
def suite():
global all_tests
... | #!/usr/bin/python
import unittest
import importlib
def iam(m_str):
""" import and add a module """
global all_tests
module = importlib.import_module("pentai.ai.%s" % m_str)
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
all_tests.addTest(suite)
def suite():
global all_tests
... | Disable PF5 tests for now | Disable PF5 tests for now
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | ---
+++
@@ -27,7 +27,7 @@
iam("t_priority_filter_2")
iam("t_priority_filter_3")
iam("t_priority_filter_4")
- iam("t_priority_filter_5")
+ #iam("t_priority_filter_5")
iam("t_utility_filter")
iam("t_search_order_table")
#iam("t_heuristic_filter") |
269670c239339bb26b61e2f9dcf0a4110b80f828 | exec_thread_1.py | exec_thread_1.py | #import spam
import filter_lta
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print THREAD_FILES
def main():
for i in THREAD_FILES:
LTA_FILES = os.chdir(... | #import spam
import filter_lta
import os
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print 'Executing this thread'
os.system('pwd')
def main():
for i in THREAD... | Add code to test running thread | Add code to test running thread
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu | ---
+++
@@ -1,12 +1,13 @@
#import spam
import filter_lta
-
+import os
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
-print THREAD_FILES
+print 'Executing this... |
bea43abce031ab70a1f4e59e5c1e4a00af37a406 | fancypages/assets/forms/fields.py | fancypages/assets/forms/fields.py | from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
default_fields = {
'asset_pk': IntegerField,... | from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
pk_field_name = 'id'
default_fields = {
... | Use default PK field name for Asset form field | Use default PK field name for Asset form field
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages | ---
+++
@@ -8,6 +8,7 @@
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
+ pk_field_name = 'id'
default_fields = {
'asset_pk': IntegerField,
'asset_type': CharField,
@@ -15,7 +16,7 @@
def __init__(self, *args, **kwargs):
kwargs.pop('queryset... |
64d9a15f84257988b371a2d12f1137f7b9f41b02 | python/009_palindrome_number.py | python/009_palindrome_number.py | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if ... | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if ... | Revise 009, add test cases | Revise 009, add test cases
| Python | mit | ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln | ---
+++
@@ -19,15 +19,22 @@
:type x: int
:rtype: bool
"""
- if x<0:
+ if x < 0:
return False
- elif x<10:
+ elif x < 10:
return True
- elif x%10==0:
+ elif x % 10 == 0:
return False
- revx=0
- tmp... |
0d84bed2f1254887c7e352a6b173b7f554dac5f7 | timepiece/context_processors.py | timepiece/context_processors.py | from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
... | from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
... | Check request.user before using it | Check request.user before using it
| Python | mit | josesanch/django-timepiece,josesanch/django-timepiece,dannybrowne86/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,gaga3966/django-timepiece,gaga3966/django-timepiece,BocuStudio/django-timepiece,dannybrowne86/django-timepiece,gaga3966/django-timepiece,josesanch/django-timepiece,dannybrowne86/django... | ---
+++
@@ -20,11 +20,14 @@
def active_entries(request):
- active_entries = timepiece.Entry.objects.filter(
- end_time__isnull=True,
- ).exclude(
- user=request.user,
- ).select_related('user', 'project', 'activity')
+ active_entries = None
+
+ if request.user.is_authenticated():
+ ... |
cb0c4b7af5efc16d1ca5da9722d9e29cae527fec | acme/utils/signals.py | acme/utils/signals.py | # Copyright 2018 DeepMind Technologies Limited. 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 ... | # Copyright 2018 DeepMind Technologies Limited. 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 ... | Fix pytype issue in signal handling code. | Fix pytype issue in signal handling code.
PiperOrigin-RevId: 408605103
Change-Id: If724504629a50d5cb7a099cf0263ba642e95345d
| Python | apache-2.0 | deepmind/acme,deepmind/acme | ---
+++
@@ -21,8 +21,11 @@
def add_handler(signo: signal.Signals, fn: _Handler):
- def _wrapped(signo: signal.Signals, frame: types.FrameType):
+
+ # The function signal.signal expects the handler to take an int rather than a
+ # signal.Signals.
+ def _wrapped(signo: int, frame: types.FrameType):
del si... |
d74fb6c7f9d0bf194b44443a13114ff1d5bb0756 | scrape_PASS_FTN.py | scrape_PASS_FTN.py | """
A script to scrape all the function exports from the PASS_FTN.FOR
By Ian Bell, NIST, January 2018
"""
import os
from generate_header import generate_interface_file, generate_function_dict
if __name__=='__main__':
generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python'... | """
A script to scrape all the function exports from the PASS_FTN.FOR
By Ian Bell, NIST, January 2018
"""
import os
from generate_header import generate_interface_file, generate_function_dict
if __name__=='__main__':
generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python'... | Add a few spaces for easier copy-paste | Add a few spaces for easier copy-paste
| Python | mit | CoolProp/REFPROP-headers,CoolProp/REFPROP-headers,CoolProp/REFPROP-headers,CoolProp/REFPROP-headers | ---
+++
@@ -35,4 +35,4 @@
else:
print(types)
raise ValueError()
- print('#define '+func+'_ARGS '+','.join(types+string_lengths))
+ print(' '*4+'#define '+func+'_ARGS '+','.join(types+string_lengths)) |
1db5fefc1752b71bf11fbf63853f7c93bcc526f5 | tests/macaroon_property_tests.py | tests/macaroon_property_tests.py | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
ascii_text_stategy = strategy(text_type).map(
lambda s: s.encode('ascii', 'ignore')
)... | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampl... | Improve strategies in property tests | Improve strategies in property tests
| Python | mit | matrix-org/pymacaroons,matrix-org/pymacaroons,ecordell/pymacaroons,illicitonion/pymacaroons | ---
+++
@@ -7,14 +7,15 @@
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
+from pymacaroons.utils import convert_to_bytes
-ascii_text_stategy = strategy(text_type).map(
- lambda s: s.encode('ascii', 'ignore')
-)
+ascii_text_strategy = strategy(
+ [sampled_from(map(chr, ... |
6e8f35b83fc563c8349cb3be040c61a0588ca745 | rplugin/python3/LanguageClient/logger.py | rplugin/python3/LanguageClient/logger.py | import logging
logger = logging.getLogger("LanguageClient")
fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S"))
logger.addHandler(fileHandler)
logger.setLevel(logging.WARN)
| import logging
import tempfile
logger = logging.getLogger("LanguageClient")
with tempfile.NamedTemporaryFile(
prefix="LanguageClient-",
suffix=".log", delete=False) as tmp:
tmpname = tmp.name
fileHandler = logging.FileHandler(filename=tmpname)
fileHandler.setFormatter(
logging.Formatter(
... | Use tempfile lib for log file | Use tempfile lib for log file
The fixed name for the log file causes issues for multiple users. The
tempfile library will create temporary files that don't conflict.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... | ---
+++
@@ -1,7 +1,12 @@
import logging
+import tempfile
logger = logging.getLogger("LanguageClient")
-fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
+with tempfile.NamedTemporaryFile(
+ prefix="LanguageClient-",
+ suffix=".log", delete=False) as tmp:
+ tmpname = tmp.name
+... |
1a8f67ec1eaa97aebe25d7d6625a237f8e1ce151 | example/tests/integration/test_includes.py | example/tests/integration/test_includes.py | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.conte... | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.conte... | Fix for test included_data_on_list included types check | Fix for test included_data_on_list included types check
| Python | bsd-2-clause | django-json-api/rest_framework_ember,scottfisk/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-fr... | ---
+++
@@ -11,7 +11,7 @@
included = load_json(response.content).get('included')
assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
- assert [x.get('type') for x in included] == ['comments'], 'List included types are incorrect'
+ assert [x.get('type') f... |
382b8df7a25732ee8384c02d776472a93c18a0ea | vcspull/__about__.py | vcspull/__about__.py | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyrig... | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__docs__ = 'https://vcspull.git-pull.com'
__tracker__ = 'https://github.com/vcs-python/vcspull/issues'
__pypi__ = 'https://... | Add docs / tracker to metadata | Add docs / tracker to metadata
| Python | mit | tony/vcspull,tony/vcspull | ---
+++
@@ -4,7 +4,9 @@
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
+__docs__ = 'https://vcspull.git-pull.com'
+__tracker__ = 'https://github.com/vcs-python/vcspull/issues'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.