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 |
|---|---|---|---|---|---|---|---|---|---|---|
a6fe31d7f687df6934143fd2dda1cd323f3d31fb | uvloop/_patch.py | uvloop/_patch.py | import asyncio
from asyncio import coroutines
def _format_coroutine(coro):
if asyncio.iscoroutine(coro) and not hasattr(coro, 'cr_code'):
# Most likely a Cython coroutine
coro_name = '{}()'.format(coro.__qualname__ or coro.__name__)
if coro.cr_running:
return '{} running'.form... | import asyncio
from asyncio import coroutines
def _format_coroutine(coro):
if asyncio.iscoroutine(coro) \
and not hasattr(coro, 'cr_code') \
and not hasattr(coro, 'gi_code'):
# Most likely a Cython coroutine
coro_name = '{}()'.format(coro.__qualname__ or coro.__name__)
... | Fix patched _format_coroutine to support Cython generators | Fix patched _format_coroutine to support Cython generators
| Python | apache-2.0 | 1st1/uvloop,MagicStack/uvloop,MagicStack/uvloop | ---
+++
@@ -4,10 +4,23 @@
def _format_coroutine(coro):
- if asyncio.iscoroutine(coro) and not hasattr(coro, 'cr_code'):
+ if asyncio.iscoroutine(coro) \
+ and not hasattr(coro, 'cr_code') \
+ and not hasattr(coro, 'gi_code'):
+
# Most likely a Cython coroutine
coro_n... |
452c3c4258c8dce5bd6f9e6799fe24253a800651 | setup.py | setup.py | from distutils.core import setup
import dpy
setup(name = "DistPy",
version = dpy.__version__,
author= "bolin",
author_email = "bolin@cs.stonybrook.edu",
packages = ['dpy', 'dpy.compiler'])
| from distutils.core import setup
import dpy
setup(name = "DistAlgo",
version = dpy.__version__,
author= "bolin",
author_email = "bolin@cs.stonybrook.edu",
packages = ['dpy', 'dpy.compiler'])
| Change project name (back) to "DistAlgo". | Change project name (back) to "DistAlgo".
* setup.py: Change project name to "DistAlgo".
| Python | mit | sghosh1991/distalgo,mayli/DistAlgo,sghosh1991/distalgo,mayli/DistAlgo | ---
+++
@@ -2,7 +2,7 @@
import dpy
-setup(name = "DistPy",
+setup(name = "DistAlgo",
version = dpy.__version__,
author= "bolin",
author_email = "bolin@cs.stonybrook.edu", |
b87c237ef7ec77f3f2224f609cac19f12fe0fa2e | setup.py | setup.py | """Setup module for txrudp."""
import codecs
from os import path
import sys
from setuptools import find_packages, setup
_HERE = path.abspath(path.dirname(__file__))
with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f:
_LONG_DESCRIPTION = f.read()
setup(
name='txrudp',
version='0.1.0'... | """Setup module for txrudp."""
import codecs
from os import path
import sys
from setuptools import setup
_HERE = path.abspath(path.dirname(__file__))
with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f:
_LONG_DESCRIPTION = f.read()
setup(
name='txrudp',
version='0.1.0',
descripti... | Make txrudp the sole distributed package. | Make txrudp the sole distributed package.
| Python | mit | Renelvon/txrudp,OpenBazaar/txrudp,jorik041/txrudp | ---
+++
@@ -4,7 +4,7 @@
from os import path
import sys
-from setuptools import find_packages, setup
+from setuptools import setup
_HERE = path.abspath(path.dirname(__file__))
@@ -34,7 +34,7 @@
'Topic :: System :: Networking'
),
keywords='rudp twisted reliable',
- packages=find_packages(... |
60d2137878b78620444ce533fcf4ee50ba7b8be1 | stack.py | stack.py | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... | Fix peek method to return value instead of object | Fix peek method to return value instead of object
| Python | mit | jwarren116/data-structures-deux | ---
+++
@@ -28,4 +28,4 @@
pass
def peek(self):
- return self.top
+ return self.top.value |
7e15a22ed01b4aa68a73a0e8e10d88d9b3785062 | aiohttp_json_rpc/__init__.py | aiohttp_json_rpc/__init__.py | from .decorators import raw_response, validate # NOQA
from .client import JsonRpcClient # NOQA
from .rpc import JsonRpc # NOQA
from .exceptions import ( # NOQA
RpcGenericServerDefinedError,
RpcInvalidRequestError,
RpcMethodNotFoundError,
RpcInvalidParamsError,
RpcError,
)
| from .decorators import raw_response, validate # NOQA
from .client import JsonRpcClient, JsonRpcClientContext # NOQA
from .rpc import JsonRpc # NOQA
from .exceptions import ( # NOQA
RpcGenericServerDefinedError,
RpcInvalidRequestError,
RpcMethodNotFoundError,
RpcInvalidParamsError,
RpcError,
)
| Add import JsonRpcClientContext in the main module | Add import JsonRpcClientContext in the main module
| Python | apache-2.0 | pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc | ---
+++
@@ -1,5 +1,5 @@
from .decorators import raw_response, validate # NOQA
-from .client import JsonRpcClient # NOQA
+from .client import JsonRpcClient, JsonRpcClientContext # NOQA
from .rpc import JsonRpc # NOQA
from .exceptions import ( # NOQA |
a692c339983ae0252577635751b67324985275dc | background_hang_reporter_job/tracked.py | background_hang_reporter_job/tracked.py | class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotatio... | class AllHangs(object):
title = "All Hangs"
@staticmethod
def matches_hang(_):
return True
class DevtoolsHangs(object):
title = "Devtools Hangs"
@staticmethod
def matches_hang(hang):
#pylint: disable=unused-variable
stack, duration, thread, runnable, process, annotatio... | Fix Activity Stream category title | Fix Activity Stream category title
| Python | mit | squarewave/background-hang-reporter-job,squarewave/background-hang-reporter-job | ---
+++
@@ -16,7 +16,7 @@
for frame, lib in stack)
class ActivityStreamHangs(object):
- title = "Devtools Hangs"
+ title = "Activity Stream Hangs"
@staticmethod
def matches_hang(hang): |
6b3dc6528a8172c4e07dfd63a57d490c8484700d | handroll/composers/atom.py | handroll/composers/atom.py | # Copyright (c) 2014, Matt Layman
import os
import sys
from werkzeug.contrib.atom import AtomFeed
from handroll import logger
from handroll.composers import Composer
class AtomComposer(Composer):
"""Compose an Atom feed from an Atom metadata file (``.atom``).
The ``AtomComposer`` parses the metadata speci... | # Copyright (c) 2014, Matt Layman
import os
import sys
from werkzeug.contrib.atom import AtomFeed
from handroll import logger
from handroll.composers import Composer
class AtomComposer(Composer):
"""Compose an Atom feed from an Atom metadata file (``.atom``).
The ``AtomComposer`` parses the metadata speci... | Fix Travis while the Atom support is incomplete. | Fix Travis while the Atom support is incomplete.
| Python | bsd-2-clause | handroll/handroll | ---
+++
@@ -23,7 +23,7 @@
logger.info('Generating Atom XML for {0} ...'.format(source_file))
# TODO: Determine what the input file will look like (YAML? JSON?).
try:
- feed = AtomFeed('Dummy Title')
+ feed = AtomFeed('Dummy Title', id='temporary')
except Value... |
a23011dbd6500094f1e2632a998395e32739bb45 | app/drivers/mslookup/proteinquant.py | app/drivers/mslookup/proteinquant.py | from app.actions.mslookup import proteinquant as lookups
from app.drivers.mslookup import base
class ProteinQuantLookupDriver(base.LookupDriver):
"""Creates lookup of protein tables that contain quant data"""
lookuptype = 'prottable'
def __init__(self, **kwargs):
super().__init__(**kwargs)
... | from app.actions.mslookup import proteinquant as lookups
from app.drivers.mslookup import base
class ProteinQuantLookupDriver(base.LookupDriver):
"""Creates lookup of protein tables that contain quant data"""
lookuptype = 'prottable'
def __init__(self, **kwargs):
super().__init__(**kwargs)
... | Correct variable name is singular here | Correct variable name is singular here
| Python | mit | glormph/msstitch | ---
+++
@@ -14,7 +14,7 @@
self.psmnrcolpattern = kwargs.get('psmnrcolpattern', None)
self.precursorquantcolpattern = kwargs.get('precursorquantcolpattern',
None)
- self.proteincols = kwargs.get('protcol', None) - 1
+ self.proteincol =... |
56b5b4d49973702bcb95bb36dcd1e35f40b57a1d | hyper/http20/exceptions.py | hyper/http20/exceptions.py | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... | Add exception for streams forcefully reset | Add exception for streams forcefully reset
| Python | mit | Lukasa/hyper,plucury/hyper,fredthomsen/hyper,irvind/hyper,fredthomsen/hyper,lawnmowerlatte/hyper,lawnmowerlatte/hyper,Lukasa/hyper,plucury/hyper,irvind/hyper | ---
+++
@@ -40,3 +40,10 @@
The remote party violated the HTTP/2 protocol.
"""
pass
+
+
+class StreamResetError(HTTP20Error):
+ """
+ A stream was forcefully reset by the remote party.
+ """
+ pass |
91b281a2d8e0938404fa533c7a4ff9f2a251d1b1 | backend/populate_targets.py | backend/populate_targets.py | import django
import os
import yaml
from backend.settings import BASE_DIR
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target
def create_target(target):
t = Target(
endpoint=target['endpoint'],
prefix=target['prefix'],
alpha... | import django
import os
import yaml
from backend.settings import BASE_DIR
from django.db import IntegrityError
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target
def create_target(target):
t = Target(
name=target['name'],
endpoint=... | Add name when creating Target | Add name when creating Target
| Python | mit | dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,esara... | ---
+++
@@ -2,6 +2,7 @@
import os
import yaml
from backend.settings import BASE_DIR
+from django.db import IntegrityError
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
@@ -11,6 +12,7 @@
def create_target(target):
t = Target(
+ name=target['name'],
en... |
a055f97a342f670171f30095cabfd4ba1bfdad17 | images/singleuser/user-config.py | images/singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Fix dictionary access pattern for setting auth tokens | Fix dictionary access pattern for setting auth tokens
| Python | mit | yuvipanda/paws,yuvipanda/paws | ---
+++
@@ -24,7 +24,7 @@
usernames[fam]['*'] = os.environ['USER']
if 'ACCESS_KEY' in os.environ:
# If OAuth integration is available, take it
- authenticate[fam]['*'] = (
+ authenticate.setdefault(fam, {})['*'] = (
os.environ['CLIENT_ID'],
os.environ['CLIENT... |
d05a16474c9eabc7f52d8d9c6811e4d01bea6080 | bongo/settings/travis.py | bongo/settings/travis.py | from bongo.settings.prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432... | from bongo.settings.prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432... | Make test output more verbose so we can figure out what is hanging | Make test output more verbose so we can figure out what is hanging
| Python | mit | BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo | ---
+++
@@ -19,6 +19,6 @@
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
-NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture']
+NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture', '--verbosity=2']
NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests' |
13ffe365680b4dcfb99ce446cc4dffe1587755ff | ipython_notebook_config.py | ipython_notebook_config.py | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | # Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.Notebo... | Use tornado settings, webapp deprecated | Use tornado settings, webapp deprecated
| Python | bsd-3-clause | jupyter/nature-demo,jupyter/nature-demo,jupyter/nature-demo | ---
+++
@@ -12,7 +12,7 @@
# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
-c.NotebookApp.webapp_settings = {
+c.NotebookApp.tornado_settings = {
'headers': {
'X-Frame-Options': 'ALLOW FROM nature.com'
}, |
8f4c8760dd5f6f21b1c59579332a3c81fa58ed13 | buildlet/runner/__init__.py | buildlet/runner/__init__.py | """
Runner classes to execute tasks.
"""
_namemodmap = dict(
SimpleRunner='simple',
IPythonParallelRunner='ipythonparallel',
MultiprocessingRunner='multiprocessingpool',
)
def getrunner(classname):
import sys
module = 'buildlet.runner.{0}'.format(_namemodmap[classname])
__import__(module)
... | """
Runner classes to execute tasks.
"""
_namemodmap = dict(
SimpleRunner='simple',
IPythonParallelRunner='ipythonparallel',
MultiprocessingRunner='multiprocessingpool',
)
def getrunner(classname):
"""
Get a runner class named `classname`.
"""
import sys
module = 'buildlet.runner.{0}'... | Document utility functions in buildlet.runner | Document utility functions in buildlet.runner
| Python | bsd-3-clause | tkf/buildlet | ---
+++
@@ -10,6 +10,9 @@
def getrunner(classname):
+ """
+ Get a runner class named `classname`.
+ """
import sys
module = 'buildlet.runner.{0}'.format(_namemodmap[classname])
__import__(module)
@@ -17,10 +20,20 @@
def listrunner():
+ """
+ Get a list of runner class names (a ... |
62503058850008d7b346d6e6b70943f5e2a1efba | app/taskqueue/celeryconfig.py | app/taskqueue/celeryconfig.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | Set celery task results to expire in 1h | Set celery task results to expire in 1h
| Python | lgpl-2.1 | kernelci/kernelci-backend,kernelci/kernelci-backend | ---
+++
@@ -24,6 +24,7 @@
CELERY_ACCEPT_CONTENT = ["kjson"]
CELERY_RESULT_SERIALIZER = "kjson"
CELERY_TASK_SERIALIZER = "kjson"
+CELERY_TASK_RESULT_EXPIRES = 3600
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True |
bd971fa5e58db992895df4cb421e10f0e74b70bd | swh/web/browse/urls.py | swh/web/browse/urls.py | # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
from django.shortcuts import... | # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
from django.shortcuts import... | Use correct Django HTML template for default view | browse: Use correct Django HTML template for default view
| Python | agpl-3.0 | SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui | ---
+++
@@ -27,7 +27,7 @@
Args:
request: input django http request
"""
- return render(request, 'person.html',
+ return render(request, 'browse.html',
{'heading': 'Browse the Software Heritage archive',
'empty_browse': True})
|
3272067020ed0f2204716ee77d69b475cf0782a0 | numba2/tests/test_classes.py | numba2/tests/test_classes.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from numba2 import jit, int32
#===------------------------------------------------------------------===
# Test code
#===------------------------------------------------------------------===
@jit
class C(object):... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from numba2 import jit, sjit, int32
#===------------------------------------------------------------------===
# Test code
#===------------------------------------------------------------------===
@jit
class C(ob... | Add (failing) test for returning numba objects | Add (failing) test for returning numba objects
| Python | bsd-2-clause | flypy/flypy,flypy/flypy | ---
+++
@@ -3,7 +3,7 @@
import unittest
-from numba2 import jit, int32
+from numba2 import jit, sjit, int32
#===------------------------------------------------------------------===
# Test code
@@ -33,6 +33,10 @@
def call_method(x):
return C(x).method(C(2))
+@jit
+def return_obj(x):
+ return C(x)
... |
c3380306512e194543893442ef9327935e789437 | tests/integration/blueprints/site/user_message/test_address_formatting.py | tests/integration/blueprints/site/user_message/test_address_formatting.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from unittest.mock import patch
import pytest
from byceps.services.user_message import service as user_message_service
def test_recipient_formatting(make_user, site, params):
screen_name, email_address, expected... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from unittest.mock import patch
import pytest
from byceps.services.user_message import service as user_message_service
def test_recipient_formatting(make_user, site, params):
screen_name, email_address, expected... | Rename test user to avoid clash | Rename test user to avoid clash
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -23,7 +23,7 @@
@pytest.fixture(params=[
- ('Alice', 'alice@users.test', 'Alice <alice@users.test>'),
+ ('Alicia', 'alicia@users.test', 'Alicia <alicia@users.test>'),
('<AngleInvestor>', 'angleinvestor@users.test', '"<AngleInvestor>" <angleinvestor@users.test>'),
('-=]YOLO[=-', 'yolo@us... |
97105453db680c2d99becd10f91604339c970591 | linkatos.py | linkatos.py | #! /usr/bin/env python
import os
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
import linkatos.activities as activities
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_clien... | #! /usr/bin/env python
import os
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
import linkatos.activities as activities
# Main
if __name__ == '__main__':
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN... | Move initialisations inside main to avoid running them if not necessary | refactor: Move initialisations inside main to avoid running them if not necessary
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -6,36 +6,36 @@
import linkatos.firebase as fb
import linkatos.activities as activities
-# starterbot environment variables
-BOT_ID = os.environ.get("BOT_ID")
-SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
-
-# instantiate Slack clients
-slack_client = SlackClient(SLACK_BOT_TOKEN)
-
-# firebase en... |
46074e64289995aab5e1129f1eead705a53010b9 | learning_journal/models.py | learning_journal/models.py | from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from sqlalchemy.ext.declarative import declarative_base
import datetime
import psycopg2
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DB... | import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqla... | Add acl method to Entry model | Add acl method to Entry model
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal | ---
+++
@@ -1,3 +1,5 @@
+import datetime
+import psycopg2
from sqlalchemy import (
Column,
DateTime,
@@ -5,16 +7,12 @@
Unicode,
UnicodeText,
)
-
+from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
-import datetime
-import psycopg2
-
from sq... |
c797a3db62b2af1c236527ef95d713b6b0285345 | iati/core/tests/test_resources.py | iati/core/tests/test_resources.py | import pytest
import iati.core.resources
class TestResources(object):
"""A container for tests relating to resources"""
def test_codelist_flow_type(self):
"""Check that the FlowType codelist contains content"""
path = iati.core.resources.path_codelist('FlowType')
content = iati.core.... | import pytest
import iati.core.resources
class TestResources(object):
"""A container for tests relating to resources"""
def test_codelist_flow_type(self):
"""Check that the FlowType codelist contains content"""
path = iati.core.resources.path_codelist('FlowType')
content = iati.core.... | Increase resource size check limits | Increase resource size check limits
This brings the limits to the greatest value with 2sf that is
below the actual value without becoming higher.
| Python | mit | IATI/iati.core,IATI/iati.core | ---
+++
@@ -11,7 +11,7 @@
content = iati.core.resources.load_as_string(path)
- assert 100 < len(content)
+ assert 3200 < len(content)
def test_schema_activity(self):
"""Check that the Activity schema contains content"""
@@ -19,4 +19,4 @@
content = iati.core.resour... |
28c47a5d810490c234b85efb0b0d3b200b716b4e | config.py | config.py | import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = Non... | import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = Non... | Reduce results per page to 30 | Reduce results per page to 30
| Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api | ---
+++
@@ -15,7 +15,7 @@
DM_SEARCH_API_AUTH_TOKENS = None
- DM_SEARCH_PAGE_SIZE = 100
+ DM_SEARCH_PAGE_SIZE = 30
DM_ID_ONLY_SEARCH_PAGE_SIZE_MULTIPLIER = 10
# Logging
DM_LOG_LEVEL = 'DEBUG' |
c59c762be198b9c976d25b093860f1d14e9d2271 | backend/scripts/ddirdenorm.py | backend/scripts/ddirdenorm.py | #!/usr/bin/env python
import rethinkdb as r
conn = r.connect('localhost', 30815, db='materialscommons')
if __name__ == "__main__":
selection = list(r.table('datadirs').run(conn))
for datadir in selection:
print "Updating datadir %s" % (datadir['name'])
ddir = {}
ddir['id'] = datadir['... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | Add options for setting the port. | Add options for setting the port.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,10 +1,16 @@
#!/usr/bin/env python
import rethinkdb as r
+import optparse
-conn = r.connect('localhost', 30815, db='materialscommons')
if __name__ == "__main__":
+ parser = optparse.OptionParser()
+ parser.add_option("-p", "--port", dest="port",
+ help="rethinkdb port"... |
ca908f2e1244af91ecb1c79bb01ec463f6872835 | lib/ansible/playbook/attribute.py | lib/ansible/playbook/attribute.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | Fix indentation to be a multiple of 4 | Fix indentation to be a multiple of 4
| Python | mit | thaim/ansible,thaim/ansible | ---
+++
@@ -23,13 +23,13 @@
def __init__(self, isa=None, private=False, default=None, required=False, listof=None, priority=0, always_post_validate=False):
- self.isa = isa
- self.private = private
- self.default = default
- self.required = required
- self.listof = listof
- ... |
cc6bb949b0f4a3c4b6344b219f8b5bae2081e0a4 | slave/skia_slave_scripts/download_skimage_files.py | slave/skia_slave_scripts/download_skimage_files.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Download the image files needed to run skimage tool. """
from build_step import BuildStep
from utils import gs_utils
from util... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Download the image files needed to run skimage tool. """
from build_step import BuildStep
from utils import gs_utils
from util... | Use posixpath for paths in the cloud. | Use posixpath for paths in the cloud.
Fixes build break on Windows.
R=borenet@google.com
Review URL: https://codereview.chromium.org/18074002
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9792 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... | ---
+++
@@ -8,7 +8,7 @@
from build_step import BuildStep
from utils import gs_utils
from utils import sync_bucket_subdir
-import os
+import posixpath
import sys
class DownloadSKImageFiles(BuildStep):
@@ -23,7 +23,7 @@
dest_gsbase = (self._args.get('dest_gsbase') or
sync_bucket_subdir.D... |
e2959ec01b25c3f447fdd31608b30f19c2dc3599 | engine.py | engine.py | # Use x, y coords for unit positions
# (97, 56) ... (104, 56)
# ... ...
# (97, 49) ... (104, 49)
#
# Algebraic notation for a position is:
# algebraic_pos = chr(x) + chr(y)
def _coord_to_algebraic(coord):
x, y = coord
return chr(x) + chr(y)
def _algebraic_to_coord(algebraic):
x, y = algebrai... | # Use x, y coords for unit positions
# (97, 56) ... (104, 56)
# ... ...
# (97, 49) ... (104, 49)
#
# Algebraic notation for a position is:
# algebraic_pos = chr(x) + chr(y)
def _coord_to_algebraic(coord):
x, y = coord
return chr(x) + chr(y)
def _algebraic_to_coord(algebraic):
x, y = algebrai... | Add _is_pos_on_board() to determine if a position is on the board | Add _is_pos_on_board() to determine if a position is on the board
| Python | mit | EyuelAbebe/gamer,EyuelAbebe/gamer | ---
+++
@@ -15,3 +15,12 @@
def _algebraic_to_coord(algebraic):
x, y = algebraic[0], algebraic[1]
return ord(x), ord(y)
+
+
+def _is_pos_on_board(coord):
+ u"""Return True if coordinate is on the board."""
+ x, y = coord
+ if (97 <= x <= 104) and (49 <= y <= 56):
+ return True
+ else:
+ ... |
3671f6f1e3a2e518255a6a04d0aadf52d5fcca97 | tests/functions_tests/test_dropout.py | tests/functions_tests/test_dropout.py | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype... | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype... | Add unittest for type check during backward in TestDropout | Add unittest for type check during backward in TestDropout
| Python | mit | benob/chainer,truongdq/chainer,ronekko/chainer,sou81821/chainer,t-abe/chainer,anaruse/chainer,kashif/chainer,okuta/chainer,sinhrks/chainer,niboshi/chainer,jnishi/chainer,woodshop/chainer,elviswf/chainer,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,niboshi/chainer,cupy/cupy,1986ks/chainer,jfsa... | ---
+++
@@ -17,6 +17,7 @@
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32)
+ self.gy = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32)
def check_type_forward(self, x_data):
x = chainer.Variable(x_data)
@@ -29,5 +30,19 @@
def test... |
5dcac8299e754a4209f6f4177eb0df8ecea914c1 | namelist.py | namelist.py | #!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.com)
#
# 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.... | #!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.com)
#
# 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.... | Format codepoints according to the Namelist spec. | [tools] Format codepoints according to the Namelist spec.
| Python | apache-2.0 | googlefonts/gftools,googlefonts/gftools | ---
+++
@@ -26,12 +26,12 @@
def main(file_name):
excluded_chars = ["????", "SPACE", "NO-BREAK SPACE"]
font = TTFont(file_name)
- for cmap in font["cmap"].tables:
+ for cmap in font["cmap"].tables:
char_list = sorted(cmap.cmap.items())
for item in char_list:
item_descri... |
8dcbb031aa00afc35900243142d8f49814834d19 | powerline/renderers/ipython.py | powerline/renderers/ipython.py | # vim:fileencoding=utf-8:noet
from powerline.renderers.shell import ShellRenderer
from powerline.theme import Theme
class IpythonRenderer(ShellRenderer):
'''Powerline ipython segment renderer.'''
escape_hl_start = '\x01'
escape_hl_end = '\x02'
def get_segment_info(self, segment_info):
r = self.segment_info.co... | # vim:fileencoding=utf-8:noet
from powerline.renderers.shell import ShellRenderer
from powerline.theme import Theme
class IpythonRenderer(ShellRenderer):
'''Powerline ipython segment renderer.'''
escape_hl_start = '\x01'
escape_hl_end = '\x02'
def get_segment_info(self, segment_info):
r = self.segment_info.co... | Make IPython renderer shutdown properly | Make IPython renderer shutdown properly
| Python | mit | S0lll0s/powerline,IvanAli/powerline,Liangjianghao/powerline,cyrixhero/powerline,blindFS/powerline,bezhermoso/powerline,blindFS/powerline,EricSB/powerline,keelerm84/powerline,QuLogic/powerline,cyrixhero/powerline,darac/powerline,magus424/powerline,cyrixhero/powerline,dragon788/powerline,prvnkumar/powerline,keelerm84/pow... | ---
+++
@@ -25,5 +25,11 @@
match['theme'] = Theme(theme_config=match['config'], top_theme_config=self.theme_config, **self.theme_kwargs)
return match['theme']
+ def shutdown(self):
+ self.theme.shutdown()
+ for match in self.local_themes.values():
+ if 'theme' in match:
+ match['theme'].shutdown()
... |
7cbc6ae58357ef647a007e1b505884e523d924c2 | numba/tests/test_ctypes_call.py | numba/tests/test_ctypes_call.py | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
assert call_ctypes_func(puts, "He... | import os
import ctypes
from numba import *
@autojit(backend='ast', nopython=True)
def call_ctypes_func(func, value):
return func(value)
def test_ctypes_calls():
# Test puts for no segfault
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
c... | Fix ctypes call test for windows | Fix ctypes call test for windows
| Python | bsd-2-clause | sklam/numba,pitrou/numba,GaZ3ll3/numba,numba/numba,jriehl/numba,sklam/numba,IntelLabs/numba,IntelLabs/numba,jriehl/numba,pitrou/numba,shiquanwang/numba,gdementen/numba,stonebig/numba,pombredanne/numba,gmarkall/numba,cpcloud/numba,stonebig/numba,jriehl/numba,ssarangi/numba,gdementen/numba,stuartarchibald/numba,ssarangi/... | ---
+++
@@ -9,11 +9,13 @@
def test_ctypes_calls():
+ # Test puts for no segfault
libc = ctypes.CDLL(ctypes.util.find_library('c'))
puts = libc.puts
puts.argtypes = [ctypes.c_char_p]
- assert call_ctypes_func(puts, "Hello World!")
+ call_ctypes_func(puts, "Hello World!")
+ # Test ceil... |
65050e11fd951968b100640c503c0ca7999283c0 | templates/quantum_conf_template.py | templates/quantum_conf_template.py | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... | Add the new contrail extension to neutron plugin config file | Add the new contrail extension to neutron plugin config file
Change-Id: I2a1e90a2ca31314b7a214943b0f312471b11da9f
| Python | apache-2.0 | Juniper/contrail-provisioning,Juniper/contrail-provisioning | ---
+++
@@ -5,7 +5,7 @@
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
-contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plug... |
687c940a6c83564c14299976755b58c3c3f35dfc | bot/api/telegram.py | bot/api/telegram.py | import requests
from bot.api.domain import ApiObject
class TelegramBotApi:
def __init__(self, auth_token, debug: bool):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
self.debug = debug
def get_me(self):
return self.__send_request("getMe")
def send_message(sel... | import requests
from bot.api.domain import ApiObject
class TelegramBotApi:
def __init__(self, auth_token, debug: bool):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
self.debug = debug
def get_me(self):
return self.__send_request("getMe")
def send_message(sel... | Add timeout to requests so that they do get death-locked | Add timeout to requests so that they do get death-locked
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -18,7 +18,7 @@
return self.__send_request("getUpdates", offset=offset, timeout=timeout)
def __send_request(self, command, **params):
- request = requests.get(self.base_url + command, params=params)
+ request = requests.get(self.base_url + command, params=params, timeout=60)
... |
cadd2539d5468041599d86ffc94e7a39d83c8759 | croquemort/migrations.py | croquemort/migrations.py | from urllib.parse import urlparse
import logbook
from nameko.rpc import rpc
from .logger import LoggingDependency
from .storages import RedisStorage
log = logbook.debug
class MigrationsService(object):
name = 'migrations'
storage = RedisStorage()
logger = LoggingDependency(interval='ms')
@rpc
... | from urllib.parse import urlparse
import logbook
from nameko.rpc import rpc
from .logger import LoggingDependency
from .storages import RedisStorage
log = logbook.debug
class MigrationsService(object):
name = 'migrations'
storage = RedisStorage()
logger = LoggingDependency(interval='ms')
@rpc
... | Fix an access key `url` bug if data is empty | Fix an access key `url` bug if data is empty
| Python | mit | davidbgk/croquemort,opendatateam/croquemort,opendatateam/croquemort,davidbgk/croquemort | ---
+++
@@ -18,7 +18,7 @@
def delete_urls_for(self, domain):
log('Deleting URLs for domain {domain}'.format(domain=domain))
for url_hash, data in self.storage.get_all_urls():
- if urlparse(data['url']).netloc == domain:
+ if data and urlparse(data['url']).netloc == domain:... |
540a589a3d20b4841e9a9c936673cc30a2f0a9ff | csportal/portal/views.py | csportal/portal/views.py | from django.shortcuts import render
def home(request):
return render(request, 'portal/home.html')
| from django.shortcuts import render
def home(request):
return render(request, 'portal/home.html')
def about(request):
return render(request, 'portal/home.html')
| Add an a function(view) about which is going to render about page when it is requested | Add an a function(view) about which is going to render about page when it is requested
| Python | mit | utailab/cs-portal,utailab/cs-portal | ---
+++
@@ -3,3 +3,6 @@
def home(request):
return render(request, 'portal/home.html')
+
+def about(request):
+ return render(request, 'portal/home.html') |
5e86c516927bca9089541fdc3b60616bee8ec117 | scripts/analytics/tabulate_emails.py | scripts/analytics/tabulate_emails.py | # -*- coding: utf-8 -*-
"""Scripts for counting recently added users by email domain; pushes results
to the specified project.
"""
import datetime
import collections
from cStringIO import StringIO
from dateutil.relativedelta import relativedelta
from framework.mongo import database
from website import models
from w... | # -*- coding: utf-8 -*-
"""Scripts for counting recently added users by email domain; pushes results
to the specified project.
"""
import datetime
import collections
from cStringIO import StringIO
from dateutil.relativedelta import relativedelta
from framework.mongo import database
from website import models
from w... | Make user metric criteria consistent. | Make user metric criteria consistent.
[Resolves #1768]
| Python | apache-2.0 | chennan47/osf.io,zachjanicki/osf.io,jolene-esposito/osf.io,haoyuchen1992/osf.io,Nesiehr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,felliott/osf.io,cwisecarver/osf.io,caneruguz/osf.io,GageGaskins/osf.io,pattisdr/osf.io,acshi/osf.io,fabianvf/osf.io,njantrania/osf.io,CenterForOpenScien... | ---
+++
@@ -17,8 +17,8 @@
from scripts.analytics import utils
-NODE_ID = '95nv8'
-USER_ID = 'icpnw'
+NODE_ID = '95nv8' # Daily updates project
+USER_ID = 'icpnw' # Josh
FILE_NAME = 'daily-users.csv'
CONTENT_TYPE = 'text/csv'
TIME_DELTA = relativedelta(days=1)
@@ -35,9 +35,10 @@
def get_emails_since(delta... |
2ed36e3f99d0dfb1f66e141f96a0eec79a81c7a5 | tdb/concatenate.py | tdb/concatenate.py | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--files', nargs='*', default=[], help="tsvs that will be concatenated")
parser.add_argument('-o', '--output', type=str, default="data/titers_complete.tsv")
def concat(files,out):
with open(out, 'w') as o:
for filename in files:
... | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='+', default=[], help="tsvs that will be concatenated")
def concat(files):
for filename in files:
print "Concatenating and annotating %s." % (filename)
if "cdc" in filename.lower():
source = "cdc"
... | Change input method, write to stdout and fix minor issues. | Change input method, write to stdout and fix minor issues.
| Python | agpl-3.0 | blab/nextstrain-db,nextstrain/fauna,blab/nextstrain-db,nextstrain/fauna | ---
+++
@@ -1,36 +1,33 @@
import argparse
parser = argparse.ArgumentParser()
-parser.add_argument('-f', '--files', nargs='*', default=[], help="tsvs that will be concatenated")
-parser.add_argument('-o', '--output', type=str, default="data/titers_complete.tsv")
+parser.add_argument('files', nargs='+', default=[],... |
d5966f60491c408eede66221bc820e4ede93fc0c | pyramid_keystone/__init__.py | pyramid_keystone/__init__.py |
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.',... |
default_settings = [
('auth_url', str, 'http://localhost:5000/v3'),
('region', str, 'RegionOne'),
('user_domain_name', str, 'Default'),
('cacert', str, ''),
]
def parse_settings(settings):
parsed = {}
def populate(name, convert, default):
sname = '%s%s' % ('keystone.',... | Add directive allowing users to use our auth policy | Add directive allowing users to use our auth policy
| Python | isc | bertjwregeer/pyramid_keystone | ---
+++
@@ -38,3 +38,6 @@
registry.settings.update(settings)
config.action('keystone-configure', register)
+
+ config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
+ |
47f46e3237ba2f746193e9074136f805e71bacec | pysteps/cascade/interface.py | pysteps/cascade/interface.py |
from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a cal... | from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
_cascade_methods['fft'] = decomposition.decomposition_fft
_cascade_methods['gaussian'] = bandpass_filters.filter_gaussian
_cascade_methods['uniform'] = bandpass_filters.filter_uniform
def get_method(name):
"""
Return a call... | Raise exception on incorrect argument type | Raise exception on incorrect argument type
| Python | bsd-3-clause | pySTEPS/pysteps | ---
+++
@@ -1,4 +1,3 @@
-
from pysteps.cascade import decomposition, bandpass_filters
_cascade_methods = dict()
@@ -37,7 +36,10 @@
if isinstance(name, str):
name = name.lower()
-
+ else:
+ raise TypeError("Only strings supported for the method's names.\n"
+ + "Avai... |
ef75047fa9bd0d4bc5dd6c263f399f446827daab | radar/lib/models/__init__.py | radar/lib/models/__init__.py | from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.genetics import *
from radar.lib.models.hospitalisa... | from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.family_history import *
from radar.lib.models.genet... | Add family history and pathology client-side | Add family history and pathology client-side
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | ---
+++
@@ -4,6 +4,7 @@
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
+from radar.lib.models.family_history import *
from radar.lib.models.genetics import *
from radar.lib.models.hospitalisations import *
from radar.lib.models.result... |
88a11dc4bffccbdb585c2b09dc3eef0a0d2f6a59 | config/settings_production.py | config/settings_production.py | """
Django settings for pc_datamanger project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
from .settings_basic import *
from .settings import *
DEB... | """
Django settings for pc_datamanger project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
from .settings_basic import *
from .settings import *
DEB... | Configure allowed host for productions setup | Configure allowed host for productions setup
| Python | agpl-3.0 | policycompass/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services,mmilaprat/policycompass-services | ---
+++
@@ -16,8 +16,9 @@
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
- '193.175.133.246',
- 'localhost',
+ "services-stage.policycompass.eu",
+ "services-prod.policycompass.eu",
+ "localhost"
]
with open('/etc/policycompass/secret_key') as f: |
ab32e80f7d5bb92c969a0f0926a120325fad438b | peekaboo.py | peekaboo.py | import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r... | import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r... | Use the list item, not the list. | Use the list item, not the list.
Otherwise you get urls with `[u'1234']` in.
| Python | mit | ghickman/peekaboo | ---
+++
@@ -26,7 +26,7 @@
for notification in notifications:
if not notification['id'] in cache:
- latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:]
+ latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:]... |
956cfc16cee4d4069fdf21f980b881c3fa1864d6 | office365/sharepoint/group.py | office365/sharepoint/group.py | from office365.runtime.client_object import ClientObject
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.sharepoint.principal import Principal
from office365.runtime.resource_path_entry import ResourcePathEntry
class Group(Principal):
"""Represents a collection of users in a S... | from office365.runtime.client_object import ClientObject
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.sharepoint.principal import Principal
from office365.runtime.resource_path_entry import ResourcePathEntry
class Group(Principal):
"""Represents a collection of users in a S... | Fix resource_path of Group resource | Fix resource_path of Group resource
| Python | mit | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client | ---
+++
@@ -15,3 +15,16 @@
return self.properties['Users']
else:
return UserCollection(self.context, ResourcePathEntry(self.context, self.resource_path, "Users"))
+
+ @property
+ def resource_path(self):
+ orig_path = ClientObject.resource_path.fget(self)
+ if se... |
63c43ae652ac0b18aba5f56f70271f95e43815d6 | django/echonest/utils.py | django/echonest/utils.py | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | Fix bug in The Echo Nest API call | Fix bug in The Echo Nest API call
| Python | bsd-3-clause | FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja | ---
+++
@@ -12,7 +12,7 @@
def get_similar_from_api(name):
url = API_URL.expand({'name': name})
- r = requests.get(url)
+ r = requests.get(str(url))
r.raise_for_status()
return SimilarResponse.objects.create(name=name, response=r.json())
|
3471dd3196c134f7aee35aa38370c93915be2197 | example/__init__.py | example/__init__.py |
import webapp2
class IntroHandler(webapp2.RequestHandler):
def get(self):
pass
app = webapp2.WSGIApplication([
('/', IntroHandler),
])
| #
# Copyright 2012 WebFilings, LLC
#
# 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... | Add basic draft of example code. | Add basic draft of example code.
| Python | apache-2.0 | robertkluin/furious,Workiva/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,beaulyddon-wf/furious,Workiva/furious,mattsanders-wf/furious,beaulyddon-wf/furious,mattsanders-wf/furious | ---
+++
@@ -1,11 +1,80 @@
+#
+# Copyright 2012 WebFilings, LLC
+#
+# 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 ... |
0e8cc65317e7c443b4319b028395951185ef80de | filebrowser/urls.py | filebrowser/urls.py | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1'}, name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r... | from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# filebrowser urls
url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
url(r'^upload/', 'filebrowser.view... | Revert URL redirect (didn't work) | Revert URL redirect (didn't work)
| Python | bsd-3-clause | django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli | ---
+++
@@ -4,7 +4,7 @@
urlpatterns = patterns('',
# filebrowser urls
- url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1'}, name="fb_browse"),
+ url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"),
url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"),
... |
32191547567e9ce0cdec954d0079fb18f85b38ce | requests_oauthlib/oauth2_auth.py | requests_oauthlib/oauth2_auth.py | from __future__ import unicode_literals
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
from .utils import is_secure_transport
class OAuth2(object):
"""Adds proof of authorization (OAuth2 token) to the request."""
def __init__(self, client_id=None, client=None, token=None):
... | from __future__ import unicode_literals
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
from oauthlib.oauth2 import is_secure_transport
class OAuth2(object):
"""Adds proof of authorization (OAuth2 token) to the request."""
def __init__(self, client_id=None, client=None, token=None):
... | Use newly exposed oauth2.is_secure_transport instead of duplicate. | Use newly exposed oauth2.is_secure_transport instead of duplicate.
| Python | isc | requests/requests-oauthlib,lucidbard/requests-oauthlib,dongguangming/requests-oauthlib,elafarge/requests-oauthlib,abhi931375/requests-oauthlib,gras100/asks-oauthlib,sigmavirus24/requests-oauthlib,jayvdb/requests-oauthlib,jsfan/requests-oauthlib,jayvdb/requests-oauthlib,singingwolfboy/requests-oauthlib | ---
+++
@@ -1,7 +1,6 @@
from __future__ import unicode_literals
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
-
-from .utils import is_secure_transport
+from oauthlib.oauth2 import is_secure_transport
class OAuth2(object): |
cedbfda6e9c040c6924eae2eff0e9b4e9f3f93f0 | api/core/helpers.py | api/core/helpers.py | import pprint
from django.core.mail import EmailMessage
import log
from rest_framework.reverse import reverse
from sesame.utils import get_query_string
def send_login_email(user, request, *, welcome):
assert user.email, f"User has no email: {user}"
base = reverse('redirector', args=["login"], request=reque... | import pprint
from django.core.mail import EmailMessage
import log
from rest_framework.reverse import reverse
from sesame.utils import get_query_string
def send_login_email(user, request, *, welcome):
assert user.email, f"User has no email: {user}"
base = reverse('redirector', args=["login"], request=reque... | Use Mandrill templates to send emails | Use Mandrill templates to send emails
| Python | mit | citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement | ---
+++
@@ -14,21 +14,28 @@
token = get_query_string(user)
url = base + token
- # TODO: Convert this to an email template
- if welcome:
- subject = "Welcome to Voter Engagement"
- else:
- subject = "Greetings from Voter Engagement"
- body = f"Click here to log in: {url}"
- ema... |
bf4af59b4a9d0637d3743b6b6ff0eaef18dbb902 | flask_restplus/namespace.py | flask_restplus/namespace.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ApiNamespace(object):
def __init__(self, api, name, description=None, endpoint=None, path=None, **kwargs):
self.api = api
self.name = name
self.path = path or ('/' + name)
self.description = description
s... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ApiNamespace(object):
def __init__(self, api, name, description=None, endpoint=None, path=None, **kwargs):
self.api = api
self.name = name
self.path = path or ('/' + name)
self.description = description
s... | Hide resource if doc is False | Hide resource if doc is False | Python | mit | leiserfg/flask-restplus,luminusnetworks/flask-restplus,awiddersheim/flask-restplus,awiddersheim/flask-restplus,fixedd/flask-restplus,luminusnetworks/flask-restplus,fixedd/flask-restplus,leiserfg/flask-restplus | ---
+++
@@ -18,7 +18,7 @@
def route(self, *urls, **kwargs):
def wrapper(cls):
doc = kwargs.pop('doc', None)
- if doc:
+ if doc is not None:
self.api._handle_api_doc(cls, doc)
self.add_resource(cls, *[self.path + url for url in urls], **kwa... |
69ac16b1501f9affa008c68d4b8197b320ae00b8 | cleanup.py | cleanup.py | #!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(ve... | #!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(ve... | Delete images instead of printing | Delete images instead of printing
| Python | mit | dreipol/cleanup-deis-images,dreipol/cleanup-deis-images | ---
+++
@@ -20,7 +20,7 @@
for line in lines:
try:
image_name, version = line.split(' ')
- version_num = float(version.replace('v', ''))
+ version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
... |
c733126501690c7168d757ab9f14a4877e8544da | resolwe/flow/managers/workload_connectors/__init__.py | resolwe/flow/managers/workload_connectors/__init__.py | """.. Ignore pydocstyle D400.
===================
Workload Connectors
===================
The workload management system connectors are used as glue between the
Resolwe Manager and various concrete workload management systems that
might be used by it. Since the only functional requirement is job
submission, they can ... | """.. Ignore pydocstyle D400.
===================
Workload Connectors
===================
The workload management system connectors are used as glue between the
Resolwe Manager and various concrete workload management systems that
might be used by it. Since the only functional requirement is job
submission, they can ... | Add Kubernetes workload connector to documentation | Add Kubernetes workload connector to documentation
| Python | apache-2.0 | genialis/resolwe,genialis/resolwe | ---
+++
@@ -17,5 +17,7 @@
:members:
.. automodule:: resolwe.flow.managers.workload_connectors.slurm
:members:
+.. automodule:: resolwe.flow.managers.workload_connectors.kubernetes
+ :members:
""" |
b6fd1c849402d42bd00467406ae8c5dff42f2d03 | tests/test_style.py | tests/test_style.py | import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
flake8([])
except SystemExit as e:
if e.code != 0:
self.fa... | import logging
import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
logger = logging.getLogger('flake8')
logger.setLevel(logging.ERROR)
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
... | Decrease noise from code-style test | Decrease noise from code-style test
| Python | mit | ministryofjustice/django-moj-irat | ---
+++
@@ -1,9 +1,12 @@
+import logging
import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
+ logger = logging.getLogger('flake8')
+ logger.setLevel(logging.ERROR)
flake8 = pkg_resources.load_entry_point('flake8', 'console_scr... |
dffe54088c9cb66a29a7aa63de269730de8a67d7 | tests/test_utils.py | tests/test_utils.py | import pytest
from .test_views import twenty_name_fixtures
from django.test.client import RequestFactory
from name.views import (
normalize_query,
resolve_q,
resolve_type,
filter_names
)
# FIXME: This is used to silence PEP8 warnings
twenty_name_fixtures = twenty_name_fixtures
@pytest.mark.xfail
def ... | Add tests for some helper functions in views.py. | Add tests for some helper functions in views.py.
| Python | bsd-3-clause | damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name | ---
+++
@@ -0,0 +1,87 @@
+import pytest
+from .test_views import twenty_name_fixtures
+from django.test.client import RequestFactory
+from name.views import (
+ normalize_query,
+ resolve_q,
+ resolve_type,
+ filter_names
+)
+
+# FIXME: This is used to silence PEP8 warnings
+twenty_name_fixtures = twenty_... | |
6518911dad0d22e878d618f9a9a1472de7a7ee1e | config/fuzz_pox_mesh.py | config/fuzz_pox_mesh.py | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controlle... | Use the mock discovery module | Use the mock discovery module
| Python | apache-2.0 | jmiserez/sts,ucb-sts/sts,ucb-sts/sts,jmiserez/sts | ---
+++
@@ -7,7 +7,7 @@
# Use POX as our controller
command_line = ('''./pox.py --verbose sts.syncproto.pox_syncer '''
- '''openflow.discovery forwarding.l2_multi '''
+ '''openflow.mock_discovery forwarding.l2_multi '''
'''sts.util.socket_mux.pox_monkeypatcher '''
... |
97a799965e74f6add2eefab38a4e1a69699092df | students/forms.py | students/forms.py | from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm
from .models import WhitelistedUsername
User = get_user_model()
class ExclusiveRegistrationF... | from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm
from .models import WhitelistedUsername
User = get_user_model()
class ExclusiveRegistrationF... | Add todo note in ExclusiveRegistrationForm. | Add todo note in ExclusiveRegistrationForm.
| Python | mit | muhummadPatel/raspied,muhummadPatel/raspied,muhummadPatel/raspied | ---
+++
@@ -12,6 +12,7 @@
class ExclusiveRegistrationForm(RegistrationForm):
def clean(self):
+ # TODO: try catch KeyError here to avoid empty form error
form_username = self.cleaned_data['username']
try:
# If this runs without raising an exception, then the username is i... |
7a324d85ef76604c919c2c7e2f38fbda17b3d01c | docs/examples/led_travis.py | docs/examples/led_travis.py | from travispy import TravisPy
from gpiozero import LED
from gpiozero.tools import negated
from time import sleep
from signal import pause
def build_passed(repo='RPi-Distro/python-gpiozero', delay=3600):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'
sleep(d... | from travispy import TravisPy
from gpiozero import LED
from gpiozero.tools import negated
from time import sleep
from signal import pause
def build_passed(repo):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'
red = LED(12)
green = LED(16)
green.source = build_pas... | Use source_delay instead of sleep, and tidy up a bit | Use source_delay instead of sleep, and tidy up a bit | Python | bsd-3-clause | RPi-Distro/python-gpiozero,waveform80/gpio-zero,MrHarcombe/python-gpiozero | ---
+++
@@ -4,16 +4,17 @@
from time import sleep
from signal import pause
-def build_passed(repo='RPi-Distro/python-gpiozero', delay=3600):
+def build_passed(repo):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'
- sleep(delay) # Sleep an hour before... |
7011a38826fcde520e4bf07f7089d9d1b75ee8f9 | spec/openpassword/fudge_wrapper.py | spec/openpassword/fudge_wrapper.py | import fudge
import inspect
class MethodNotAvailableInMockedObjectException(Exception):
pass
def getMock(class_to_mock):
return FudgeWrapper(class_to_mock)
class FudgeWrapper(fudge.Fake):
def __init__(self, class_to_mock):
self._class_to_mock = class_to_mock
self._declared_calls = {}
... | import fudge
import inspect
class MethodNotAvailableInMockedObjectException(Exception):
pass
def getMock(class_to_mock):
return FudgeWrapper(class_to_mock)
class FudgeWrapper(fudge.Fake):
def __init__(self, class_to_mock):
self._class_to_mock = class_to_mock
self._declared_calls = {}
... | Fix bug on fudge wrapper | Fix bug on fudge wrapper
| Python | mit | openpassword/blimey,openpassword/blimey | ---
+++
@@ -19,7 +19,7 @@
def provides(self, call_name):
self._check_method_availability_on_mocked_object(call_name)
- super(FudgeWrapper, self).provides(call_name)
+ return super(FudgeWrapper, self).provides(call_name)
def _check_method_availability_on_mocked_object(self, call_na... |
e979aab8ffdd5a2e86be7dd8fcacb5f10953a994 | src/SeleniumLibrary/utils/types.py | src/SeleniumLibrary/utils/types.py | # Copyright 2008-2011 Nokia Networks
# Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors
# Copyright 2016- Robot Framework Foundation
#
# 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 Licens... | # Copyright 2008-2011 Nokia Networks
# Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors
# Copyright 2016- Robot Framework Foundation
#
# 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 Licens... | Remove is_string because it exist in RF 2.9 | Remove is_string because it exist in RF 2.9
| Python | apache-2.0 | robotframework/SeleniumLibrary,emanlove/robotframework-selenium2library,emanlove/robotframework-selenium2library,rtomac/robotframework-selenium2library,emanlove/robotframework-selenium2library,robotframework/SeleniumLibrary,robotframework/SeleniumLibrary,rtomac/robotframework-selenium2library,rtomac/robotframework-sele... | ---
+++
@@ -18,15 +18,7 @@
# Can be removed when library minimum required Robot Framework version is
# greater than 3.0.2. Then Robot Framework is_truthy should also support
# string NONE as Python False.
-
-import sys
-
-
-if sys.version_info[0] == 2:
- def is_string(item):
- return isinstance(item, (st... |
4e243ade9b96c5ea6e68c27593fb578c52c85f1a | huffman.py | huffman.py | class Node:
def __init__(self):
self.name = ''
self.weight = 0
self.code = ''
def initSet(self, name, weight):
self.name = name
self.weight = weight
| class Node:
def __init__(self):
self.name = ''
self.weight = 0
self.code = ''
def initSet(self, name, weight):
self.name = name
self.weight = weight
def setRoot(self, root):
self.root = root
def setLeft(self, left):
self.left = left
def se... | Add functions about setting the parent & children nodes and codes. | Add functions about setting the parent & children nodes and codes.
| Python | mit | hane1818/Algorithm_HW3_huffman_code | ---
+++
@@ -8,3 +8,15 @@
def initSet(self, name, weight):
self.name = name
self.weight = weight
+
+ def setRoot(self, root):
+ self.root = root
+
+ def setLeft(self, left):
+ self.left = left
+
+ def setRight(self, right):
+ self.right = right
+
+ def addCode(se... |
6a5936a3d69c8af1b5878b824dec17c94fd1da95 | masters/master.tryserver.chromium.gpu/master_site_config.py | masters/master.tryserver.chromium.gpu/master_site_config.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class GpuTryServer(Master.Master4):
project_name = 'Chromium GPU Try Server'
master_... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class GpuTryServer(Master.Master4):
project_name = 'Chromium GPU Try Server'
master_... | Fix colliding ports for tryserver.chromium.gpu | Fix colliding ports for tryserver.chromium.gpu
BUG=353434
Review URL: https://codereview.chromium.org/203743004
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@257737 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -8,9 +8,9 @@
class GpuTryServer(Master.Master4):
project_name = 'Chromium GPU Try Server'
- master_port = 8020
- slave_port = 8120
- master_port_alt = 8220
+ master_port = 8021
+ slave_port = 8121
+ master_port_alt = 8221
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'h... |
c984183b7ea92dcd7106151bed43065504358dd0 | tests/__init__.py | tests/__init__.py | import sys
import os
CRAFTAI_MODULE_SRC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path = [CRAFTAI_MODULE_SRC_DIR] + sys.path
| Make sure the local version of the craft ai module is used in tests | Make sure the local version of the craft ai module is used in tests
| Python | bsd-3-clause | craft-ai/craft-ai-client-python,craft-ai/craft-ai-client-python | ---
+++
@@ -0,0 +1,5 @@
+import sys
+import os
+
+CRAFTAI_MODULE_SRC_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+sys.path = [CRAFTAI_MODULE_SRC_DIR] + sys.path | |
d72e13f22eab7bf61b56b1d5fa33b006c5f13299 | tests/cli_test.py | tests/cli_test.py | from pork.cli import CLI
from mock import Mock
class TestCLI:
def it_has_a_data_attribute(self):
assert CLI().data is not None
| from pork.cli import CLI, main
from mock import Mock, patch
from StringIO import StringIO
patch.TEST_PREFIX = 'it'
@patch('pork.cli.Data')
class TestCLI:
def it_has_a_data_attribute(self, Data):
assert CLI().data is not None
def it_sets_keys(self, Data):
cli = CLI()
cli.start(['foo',... | Add test coverage for pork.cli. | Add test coverage for pork.cli.
| Python | mit | jimmycuadra/pork,jimmycuadra/pork | ---
+++
@@ -1,7 +1,47 @@
-from pork.cli import CLI
+from pork.cli import CLI, main
-from mock import Mock
+from mock import Mock, patch
+from StringIO import StringIO
+patch.TEST_PREFIX = 'it'
+
+@patch('pork.cli.Data')
class TestCLI:
- def it_has_a_data_attribute(self):
+ def it_has_a_data_attribute(self,... |
09931cfbba746daf5127b6113187042341e3be3d | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def credentials():
"""Fake set of MWS credentials"""
return {
"access_key": "AAAAAAAAAAAAAAAAAAAA",
"secret_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"account_id": "AAAAAAAAAAAAAA",
}
| import pytest
@pytest.fixture
def access_key():
return "AAAAAAAAAAAAAAAAAAAA"
@pytest.fixture
def secret_key():
return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
@pytest.fixture
def account_id():
return "AAAAAAAAAAAAAA"
@pytest.fixture
def timestamp():
return '2017-08-12T19:40:35Z'
@pytest.fix... | Add more pytest fixtures (access_key, secret_key, account_id, timestamp) | Add more pytest fixtures (access_key, secret_key, account_id, timestamp)
| Python | unlicense | GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws | ---
+++
@@ -2,10 +2,30 @@
@pytest.fixture
-def credentials():
+def access_key():
+ return "AAAAAAAAAAAAAAAAAAAA"
+
+
+@pytest.fixture
+def secret_key():
+ return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+
+
+@pytest.fixture
+def account_id():
+ return "AAAAAAAAAAAAAA"
+
+
+@pytest.fixture
+def timesta... |
17f6d104810f53a3ceac4943f3b80def3917b356 | textx/__init__.py | textx/__init__.py | # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegi... | # flake8: noqa
from textx.metamodel import metamodel_from_file, metamodel_from_str
from textx.model import get_children_of_type, get_parent_of_type, \
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegi... | Remove click dependent import from the main module. | Remove click dependent import from the main module.
This leads to import error when textX is installed without CLI support.
| Python | mit | igordejanovic/textX,igordejanovic/textX,igordejanovic/textX | ---
+++
@@ -4,7 +4,6 @@
get_model, get_metamodel, get_children, get_location, textx_isinstance
from textx.exceptions import TextXError, TextXSyntaxError, \
TextXSemanticError, TextXRegistrationError
-from textx.generators import get_output_filename, gen_file
from textx.registration import (LanguageDesc, G... |
9619ecae61514bf1681425c503c38ccbe17f4b47 | src/commoner/registration/admin.py | src/commoner/registration/admin.py | from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
| from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
fieldsets = (
(None, {
'fields':('last_name', 'first_name', 'email', 'complete', 'transaction_id', 'user'),
'descriptio... | Send welcome emails when registrations are added through the web interface. | Send welcome emails when registrations are added through the web
interface.
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner | ---
+++
@@ -5,4 +5,18 @@
list_filter = ('complete',)
+ fieldsets = (
+ (None, {
+ 'fields':('last_name', 'first_name', 'email', 'complete', 'transaction_id', 'user'),
+ 'description':'Adding a new registration will send a welcome email.'},
+ ),
+ )
+
+ def save_model(self, request, obj, ... |
9d7b7d70402894e07a00356ea8921c098b41ee24 | soapbox/templatetags/soapbox.py | soapbox/templatetags/soapbox.py | from django import template
from ..models import Message
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_messages_for_page(context, url):
if url == context.template.engine.string_if_invalid:
return []
return Message.objects.match(url)
| from django import template
from ..models import Message
register = template.Library()
@register.simple_tag(takes_context=True)
def get_messages_for_page(context, url):
if url == context.template.engine.string_if_invalid:
return []
return Message.objects.match(url)
| Address removal of assignment_tag in Django 2.0 | Address removal of assignment_tag in Django 2.0
| Python | bsd-3-clause | ubernostrum/django-soapbox,ubernostrum/django-soapbox | ---
+++
@@ -6,7 +6,7 @@
register = template.Library()
-@register.assignment_tag(takes_context=True)
+@register.simple_tag(takes_context=True)
def get_messages_for_page(context, url):
if url == context.template.engine.string_if_invalid:
return [] |
3426f160d24f98a897149110bb6b67891e73dcca | tests/test_gen_addons_table.py | tests/test_gen_addons_table.py | import os
import subprocess
import unittest
class TestGenAddonsTable(unittest.TestCase):
def test_1(self):
dirname = os.path.dirname(__file__)
cwd = os.path.join(dirname, 'test_repo')
gen_addons_table = os.path.join(dirname, '..', 'tools',
'gen_addo... | import os
import subprocess
import sys
def test_1():
dirname = os.path.dirname(__file__)
cwd = os.path.join(dirname, 'test_repo')
readme_filename = os.path.join(dirname, 'test_repo', 'README.md')
with open(readme_filename) as f:
readme_before = f.read()
readme_expected_filename = os.path.j... | Make gen_addons_table test generate coverage | Make gen_addons_table test generate coverage
This is done by invoking subprocess with sys.executable,
pytest-cov does the rest.
Also change test style to pytest instead of unittest.
| Python | agpl-3.0 | Yajo/maintainer-tools,Yajo/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,OCA/maintainer-tools,acsone/maintainer-tools,acsone/maintainer-tools,Yajo/maintainer-tools,acsone/maintainer-tools,acsone/maintainers-tools,Yajo/maintainer-tools,acsone/maintainer-tools,acsone/maintainers-tools,ac... | ---
+++
@@ -1,27 +1,27 @@
import os
import subprocess
-import unittest
+import sys
-class TestGenAddonsTable(unittest.TestCase):
-
- def test_1(self):
- dirname = os.path.dirname(__file__)
- cwd = os.path.join(dirname, 'test_repo')
- gen_addons_table = os.path.join(dirname, '..', 'tools'... |
8157ee43f31bd106d00c86ac4a7bc35a79c29e41 | django_payzen/app_settings.py | django_payzen/app_settings.py | """ Default payzen settings.
All settings should be set in the django settings file and not
directly in this file.
We deliberately do not set up default values here in order to
force user to setup explicitely the default behaviour."""
from django.conf import settings
PAYZEN_REQUEST_URL = 'https://secure.payzen.eu/v... | """ Default payzen settings.
All settings should be set in the django settings file and not
directly in this file.
We deliberately do not set up default values here in order to
force user to setup explicitely the default behaviour."""
from django.conf import settings
PAYZEN_REQUEST_URL = 'https://secure.payzen.eu/v... | Set essential payzen settings as mandatory for django_payzen. | Set essential payzen settings as mandatory for django_payzen.
| Python | mit | zehome/django-payzen,bsvetchine/django-payzen,zehome/django-payzen,bsvetchine/django-payzen | ---
+++
@@ -10,8 +10,8 @@
PAYZEN_REQUEST_URL = 'https://secure.payzen.eu/vads-payment/'
VADS_CONTRIB = 'django-payzen v0.9'
-VADS_SITE_ID = getattr(settings, 'VADS_SITE_ID', None)
-CLIENT_CERTIFICATE = getattr(settings, 'VADS_CERTIFICATE', None)
+VADS_SITE_ID = getattr(settings, 'VADS_SITE_ID')
+VADS_CERTIFICATE ... |
b03b71505469f8234dc18fdc653311cd63be252c | dallinger/prolific.py | dallinger/prolific.py | import logging
logger = logging.getLogger(__file__)
class ProlificServiceException(Exception):
"""Some error from Prolific"""
pass
class ProlificService:
"""Wrapper for Prolific REST API"""
def __init__(self, prolific_api_token: str):
self.api_token = prolific_api_token
def create_st... | import logging
logger = logging.getLogger(__file__)
class ProlificServiceException(Exception):
"""Some error from Prolific"""
pass
class ProlificService:
"""Wrapper for Prolific REST API"""
def __init__(self, prolific_api_token: str):
self.api_token = prolific_api_token
def create_st... | Add sketch of bonus payment process | Add sketch of bonus payment process
| Python | mit | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger | ---
+++
@@ -33,4 +33,14 @@
logger.info(f"Would be sending bonus request: {payload}")
# TODO Actually make request, etc.
+ # Set up bonus
+ # response = requests.post(blah)
+
+ # Process bonus previously set up
+ # bonus_id = study_id # ? maybe?
+ # payment_endpo... |
80d1126418af0890a36a4bac9ddf53a2ab40e851 | cpp_coveralls/report.py | cpp_coveralls/report.py | from __future__ import absolute_import
from __future__ import print_function
import requests
import json
URL = 'https://coveralls.io/api/v1/jobs'
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)})
try:
r... | from __future__ import absolute_import
from __future__ import print_function
import requests
import json
import os
URL = os.getenv('COVERALLS_ENDPOINT', 'https://coveralls.io') + "/api/v1/jobs"
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_f... | Support COVERALLS_ENDPOINT for Enterprise usage | Support COVERALLS_ENDPOINT for Enterprise usage | Python | apache-2.0 | eddyxu/cpp-coveralls,eddyxu/cpp-coveralls | ---
+++
@@ -3,9 +3,9 @@
import requests
import json
+import os
-URL = 'https://coveralls.io/api/v1/jobs'
-
+URL = os.getenv('COVERALLS_ENDPOINT', 'https://coveralls.io') + "/api/v1/jobs"
def post_report(coverage):
"""Post coverage report to coveralls.io.""" |
03dc4f221aa9909c8a3074cbef9fd1816e0cc86c | stagecraft/libs/mass_update/data_set_mass_update.py | stagecraft/libs/mass_update/data_set_mass_update.py | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate():
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
model_filter = DataSet.objects
if 'data_type' in query:
data_type = cls._get_model_instance_b... | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate(object):
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
cls(query).update(bearer_token=new_token)
def __init__(self, query_dict):
self.model_filter =... | Refactor query out into instance with delegates the update | Refactor query out into instance with delegates the update
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft | ---
+++
@@ -1,21 +1,26 @@
from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
-class DataSetMassUpdate():
+class DataSetMassUpdate(object):
+
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
- model_filter = DataSet.objects
- if... |
f78e20b05a5d7ede84f80a9be16a6a40a1a7abf8 | ifs/cli.py | ifs/cli.py | import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass... | import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass... | Exit with return code from called script | Exit with return code from called script
| Python | isc | cbednarski/ifs-python,cbednarski/ifs-python | ---
+++
@@ -33,7 +33,9 @@
@cli.command()
@click.argument('application')
def install(application):
- click.echo(lib.install(application))
+ cmd = lib.install(application)
+ click.echo(cmd.output)
+ exit(cmd.returncode)
@cli.command() |
c8ef9e7271796239de2878bbf40a2c2d388427e4 | bayesian_methods_for_hackers/simulate_messages_ch02.py | bayesian_methods_for_hackers/simulate_messages_ch02.py | import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha ... | import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm... | Change of repo name. Update effected paths | Change of repo name. Update effected paths
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -6,9 +6,6 @@
def main():
- matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
- matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))
-
tau = pm.rdiscrete_uniform(0, 80)
print tau
|
4f9ddcd07dbf5a84f183e7a84a8819bde062dbcf | example/_find_fuse_parts.py | example/_find_fuse_parts.py | import sys, os, glob
from os.path import realpath, dirname, join
from traceback import format_exception
PYTHON_MAJOR_MINOR = "%s.%s" % (sys.version_info[0], sys.version_info[1])
ddd = realpath(join(dirname(sys.argv[0]), '..'))
for d in [ddd, '.']:
for p in glob.glob(join(d, 'build', 'lib.*%s' % PYTHON_MAJOR_MIN... | import sys, os, glob
from os.path import realpath, dirname, join
from traceback import format_exception
PYTHON_MAJOR_MINOR = "%s.%s" % (sys.version_info[0], sys.version_info[1])
ddd = realpath(join(dirname(sys.argv[0]), '..'))
for d in [ddd, '.']:
for p in glob.glob(join(d, 'build', 'lib.*%s' % PYTHON_MAJOR_MIN... | Troubleshoot potential sys.path problem with python 3.x | Troubleshoot potential sys.path problem with python 3.x
| Python | lgpl-2.1 | libfuse/python-fuse,libfuse/python-fuse | ---
+++
@@ -9,6 +9,8 @@
for d in [ddd, '.']:
for p in glob.glob(join(d, 'build', 'lib.*%s' % PYTHON_MAJOR_MINOR)):
sys.path.insert(0, p)
+
+print(sys.path)
try:
import fuse |
360ded396e5febbb4871797dd6d676884e24299a | api/setup.py | api/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
import os
from distutils.core import setup
setup(name='humbug',
version=humbug.__version__,
description='Bindings for the Humbug message API',
author='Humbug, Inc.',
author_email='humbug@humbughq.com',
classifiers=[... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
import os
from distutils.core import setup
def recur_expand(target_root, dir):
for root, _, files in os.walk(dir):
paths = [os.path.join(root, f) for f in files]
if len(paths):
yield os.path.join(target_root, root), paths
setup(... | Include folders with subfolders when creating api tarball | Include folders with subfolders when creating api tarball
(imported from commit b9d564a6cc4ee6e2afa0108b6d9f18af039fc8cf)
| Python | apache-2.0 | jeffcao/zulip,vabs22/zulip,verma-varsha/zulip,jphilipsen05/zulip,KJin99/zulip,DazWorrall/zulip,johnny9/zulip,so0k/zulip,suxinde2009/zulip,proliming/zulip,mdavid/zulip,susansls/zulip,zofuthan/zulip,pradiptad/zulip,vikas-parashar/zulip,joshisa/zulip,amallia/zulip,voidException/zulip,esander91/zulip,bssrdf/zulip,calvinlee... | ---
+++
@@ -6,6 +6,12 @@
import glob
import os
from distutils.core import setup
+
+def recur_expand(target_root, dir):
+ for root, _, files in os.walk(dir):
+ paths = [os.path.join(root, f) for f in files]
+ if len(paths):
+ yield os.path.join(target_root, root), paths
setup(name='humbug',
ve... |
b22e96cc1e5daded4841b39d31ebefd1df86f26a | corehq/apps/hqadmin/migrations/0017_hqdeploy_commit.py | corehq/apps/hqadmin/migrations/0017_hqdeploy_commit.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-21 13:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hqadmin', '0016_hqdeploy_ordering'),
]
operations = [
migrations.AddField(... | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hqadmin', '0016_hqdeploy_ordering'),
]
operations = [
migrations.AddField(
model_name='hqdeploy',
name='commit',
field=models.CharField(max_length=255, n... | Remove unnecessary imports based on review | Remove unnecessary imports based on review
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-# Generated by Django 1.11.29 on 2020-07-21 13:42
-from __future__ import unicode_literals
-
from django.db import migrations, models
|
50c6e4a44a2451970c8e6286e1acb74dad78365c | example.py | example.py | import pyrc
import pyrc.utils.hooks as hooks
class GangstaBot(pyrc.Bot):
@hooks.command()
def bling(self, channel, sender):
"will print yo"
self.message(channel, "%s: yo" % sender)
@hooks.command("^repeat\s+(?P<msg>.+)$")
def repeat(self, channel, sender, **kwargs):
"will repeat whatever yo say"
... | import pyrc
import pyrc.utils.hooks as hooks
class GangstaBot(pyrc.Bot):
@hooks.command()
def bling(self, channel, sender):
"will print yo"
self.message(channel, "%s: yo" % sender)
@hooks.command("^repeat\s+(?P<msg>.+)$")
def repeat(self, channel, sender, **kwargs):
"will repeat whatever yo say"
... | Switch off debugging func that got through... | Switch off debugging func that got through...
| Python | mit | sarenji/pyrc | ---
+++
@@ -17,7 +17,6 @@
"""
will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message
"""
- print(args)
self.message(channel, args[0])
@hooks.interval(10000) |
8f4988f5a0873dc818b8ad2c7de3e0f71d544cde | bayohwoolph.py | bayohwoolph.py | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
from discord.ext import commands
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']:
if os.path... | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
from discord.ext import commands
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']:
if os.path... | Change command prefix to $, so that's like a tip. | Change command prefix to $, so that's like a tip.
| Python | agpl-3.0 | freiheit/Bay-Oh-Woolph,dark-echo/Bay-Oh-Woolph | ---
+++
@@ -14,7 +14,7 @@
MAIN = config['MAIN']
description = '''Dark Echo's barkeep'''
-bot = commands.Bot(command_prefix='%', description=description)
+bot = commands.Bot(command_prefix='$', description=description)
@bot.event
@asyncio.coroutine |
4cad1d743f2c70c3ee046b59d98aecb6b5b301d6 | src/event_manager/views/base.py | src/event_manager/views/base.py | from django.shortcuts import render, redirect
from django.http import *
from django.contrib.auth import authenticate, login
def home(request):
return render(request, 'login.html', {})
def login_user(request):
logout(request)
username = ""
password = ""
if request.POST:
username = request.POST.get('username')
... | from django.shortcuts import render, redirect
from django.http import *
from django.contrib.auth import authenticate, login
def home(request):
return render(request, 'login.html', {})
def login_user(request):
logout(request)
username = ""
password = ""
if request.POST:
username = request.POST.get('username')
... | Create shell function for register_user | Create shell function for register_user | Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit | ---
+++
@@ -21,3 +21,7 @@
return HttpResponseRedirect('/e/')
return render(request, 'login.html', {})
+
+
+def register_user(request):
+ pass |
6abd349fa0392cd5518d3f01942289ae0527d8f4 | __init__.py | __init__.py | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... | Add NetworkX version checking to nffg_lib package | Add NetworkX version checking to nffg_lib package
| Python | apache-2.0 | hsnlab/nffg,5GExchange/nffg | ---
+++
@@ -14,7 +14,14 @@
"""
Internal graph-based implementation of Network Function Forwarding Graph
"""
+from networkx.release import get_info, major as nx_major
+
+# Enabled imports directly from nffg_lib package
from nffg import NFFG, NFFGToolBox
+
+if int(nx_major) > 1:
+ raise RuntimeError(
+ "Network... |
7f7e606cc15e24190880d7388d07623be783a384 | src/address_extractor/__init__.py | src/address_extractor/__init__.py | from .__main__ import main
__version__ = '1.0.0'
__title__ = 'address_extractor'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = ''
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2015 Scott Colby'
__all__ = [
'address_extractor'
]
| from .__main__ import main
from .__main__ import parsed_address_to_human
__version__ = '1.0.0'
__title__ = 'address_extractor'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = ''
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2015 Scott Colby'
__all__ = [
'main',
'parsed... | Change importing structure in init | Change importing structure in init
| Python | mit | scolby33/address_extractor | ---
+++
@@ -1,4 +1,5 @@
from .__main__ import main
+from .__main__ import parsed_address_to_human
__version__ = '1.0.0'
@@ -13,5 +14,6 @@
__copyright__ = 'Copyright (c) 2015 Scott Colby'
__all__ = [
- 'address_extractor'
+ 'main',
+ 'parsed_address_to_human'
] |
88776309a601e67c34747bd2eae49452006be017 | zsh/zsh_concat.py | zsh/zsh_concat.py | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... | Read lib dir, before local dir. | Read lib dir, before local dir.
| Python | mit | skk/dotfiles,skk/dotfiles | ---
+++
@@ -45,13 +45,14 @@
outfilename = parent_dir.joinpath("zsh_plugins.zsh")
with open(str(outfilename), 'w') as outbuf:
- for filename in scandir(str(lib_dir)):
- read_and_format_data(filename.path, outbuf)
-
for filename in scandir(str(local_dir)):
filename = ... |
b0df06a29d4a235de86e51f4c6ff860fe5495d12 | run-tests.py | run-tests.py |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
... |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
con... | Test runner: fix line endings, print to stderr | Test runner: fix line endings, print to stderr | Python | mit | divtxt/binder | ---
+++
@@ -15,12 +15,12 @@
if not f.startswith("test_"):
continue
test_file = os.path.join(subdir, f)
- print "FILE:", test_file
+ print >> sys.stderr, "FILE:", test_file
exit_code = os.system(sys.executable + " " + test_file)
total += 1
if exit... |
f1da9bc9aae253779121f2b844e684c4ea4dd15f | seeker/migrations/0001_initial.py | seeker/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | Add related_name to initial migration so it doesn't try to later | Add related_name to initial migration so it doesn't try to later | Python | bsd-2-clause | imsweb/django-seeker,imsweb/django-seeker | ---
+++
@@ -22,7 +22,7 @@
('querystring', models.TextField(blank=True)),
('default', models.BooleanField(default=False)),
('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
- ('user', models.ForeignKey(to=setting... |
d3b526c5079dc61d3bb8a80363c9448de07da331 | fabfile.py | fabfile.py | from fabric.api import *
env.runtime = 'production'
env.hosts = ['chimera.ericholscher.com']
env.user = 'docs'
env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org'
env.virtualenv = '/home/docs/sites/readthedocs.org'
env.rundir = '/home/docs/sites/readthedocs.org/run'
def update_requirements():
... | from fabric.api import *
env.runtime = 'production'
env.hosts = ['chimera.ericholscher.com']
env.user = 'docs'
env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org'
env.virtualenv = '/home/docs/sites/readthedocs.org'
env.rundir = '/home/docs/sites/readthedocs.org/run'
def push():
"Push new c... | Make it easy to do a full deploy with fab | Make it easy to do a full deploy with fab
| Python | mit | cgourlay/readthedocs.org,sunnyzwh/readthedocs.org,attakei/readthedocs-oauth,davidfischer/readthedocs.org,nikolas/readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,techtonik/readthedocs.org,laplaceliu/readthedocs.org,jerel/readthedocs.org,johncosta/private-readthedocs.org,stevepiercy/readthedocs.org,... | ---
+++
@@ -7,20 +7,21 @@
env.virtualenv = '/home/docs/sites/readthedocs.org'
env.rundir = '/home/docs/sites/readthedocs.org/run'
-def update_requirements():
- "Update requirements in the virtualenv."
- run("%s/bin/pip install -r %s/deploy_requirements.txt" % (env.virtualenv, env.code_dir))
-
def push():
... |
bed66179633a86751a938c13b98f5b56c3c1cfc7 | fabfile.py | fabfile.py | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty s... | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty s... | Add graphviz for converting dot to pdf | Add graphviz for converting dot to pdf
| Python | unlicense | spanners/dotfiles | ---
+++
@@ -13,7 +13,8 @@
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
- keepassx xdotool xclip rtorrent diffpdf xfce4 redshift-gtk')
+ keepassxc xdotool xclip rtorrent ... |
e98b9e1da819c571e165c55e222a3aa5a20e709b | mrbelvedereci/build/apps.py | mrbelvedereci/build/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
| from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
def ready(self):
import mrbelvedereci.build.handlers
| Include handlers in build app | Include handlers in build app
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | ---
+++
@@ -5,3 +5,6 @@
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
+
+ def ready(self):
+ import mrbelvedereci.build.handlers |
0ed4b5e2831c649bfb7c31a3fe0716bb02e4a02a | api/settings/staging.py | api/settings/staging.py | from .docker import *
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
ADMINS = (
('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamsupport@HMCTS.NET'),
)
RAVEN_CONFIG = {
'dsn': os.environ["SENTRY_DSN"],
'release': os.environ.get("APP_GIT_COMMIT", "no-git-commit-available")
}
| from .docker import *
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
ADMINS = (
('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamdev@hmcts.net'),
)
RAVEN_CONFIG = {
'dsn': os.environ["SENTRY_DSN"],
'release': os.environ.get("APP_GIT_COMMIT", "no-git-commit-available")
}
| Use dev email or non prod environments | Use dev email or non prod environments
| Python | mit | ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas | ---
+++
@@ -4,7 +4,7 @@
INSTALLED_APPS.append('raven.contrib.django.raven_compat')
ADMINS = (
- ('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamsupport@HMCTS.NET'),
+ ('[STAGING] HMCTS Reform Sustaining Support', 'sustainingteamdev@hmcts.net'),
)
RAVEN_CONFIG = { |
2009a4ef78261fc8dfe96df00321d3fb612f697e | fireplace/cards/wog/hunter.py | fireplace/cards/wog/hunter.py | from ..utils import *
##
# Minions
class OG_179:
"Fiery Bat"
deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1)
class OG_292:
"Forlorn Stalker"
play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e")
OG_292e = buff(+1, +1)
##
# Spells
class OG_045:
"Infest"
play = Buff(FRIENDLY_MINIONS, "OG_045a")
class ... | from ..utils import *
##
# Minions
class OG_179:
"Fiery Bat"
deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1)
class OG_292:
"Forlorn Stalker"
play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e")
OG_292e = buff(+1, +1)
class OG_216:
"Infested Wolf"
deathrattle = Summon(CONTROLLER, "OG_216a") * 2
clas... | Implement Infested Wolf and Princess Huhuran | Implement Infested Wolf and Princess Huhuran
| Python | agpl-3.0 | beheh/fireplace,jleclanche/fireplace,NightKev/fireplace | ---
+++
@@ -14,6 +14,16 @@
play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e")
OG_292e = buff(+1, +1)
+
+
+class OG_216:
+ "Infested Wolf"
+ deathrattle = Summon(CONTROLLER, "OG_216a") * 2
+
+
+class OG_309:
+ "Princess Huhuran"
+ play = Deathrattle(TARGET)
## |
09c3c511687de8888180577fa66f4ca51f4bc237 | taggit_autosuggest_select2/views.py | taggit_autosuggest_select2/views.py | from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson as json
from taggit.models import Tag
MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 20)
def list_tags(request):
"""
Returns a list of JSON objects with a `name` and a `value`... | from django.conf import settings
from django.http import HttpResponse
import json
from taggit.models import Tag
MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 20)
def list_tags(request):
"""
Returns a list of JSON objects with a `name` and a `value` property that
all start lik... | Remove deprecated django json shim | Remove deprecated django json shim
| Python | mit | iris-edu/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,adam-iris/django-taggit-autosuggest-select2,adam-iris/django-taggit-autosuggest-select2,iris-edu/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-... | ---
+++
@@ -1,6 +1,6 @@
from django.conf import settings
from django.http import HttpResponse
-from django.utils import simplejson as json
+import json
from taggit.models import Tag
|
16055821b0f43047db4f32f3a16335732b63aa85 | Cython/__init__.py | Cython/__init__.py | __version__ = "0.13"
# Void cython.* directives (for case insensitive operating systems).
from Cython.Shadow import *
| __version__ = "0.13+"
# Void cython.* directives (for case insensitive operating systems).
from Cython.Shadow import *
| Change version number for dev branch. | Change version number for dev branch.
| Python | apache-2.0 | scoder/cython,slonik-az/cython,rguillebert/CythonCTypesBackend,encukou/cython,encukou/cython,hickford/cython,roxyboy/cython,fabianrost84/cython,mrGeen/cython,madjar/cython,rguillebert/CythonCTypesBackend,madjar/cython,encukou/cython,rguillebert/CythonCTypesBackend,encukou/cython,madjar/cython,c-blake/cython,JelleZijlst... | ---
+++
@@ -1,4 +1,4 @@
-__version__ = "0.13"
+__version__ = "0.13+"
# Void cython.* directives (for case insensitive operating systems).
from Cython.Shadow import * |
a4264c610f33640ac773ca0b12912f3ad972d966 | feedback/admin.py | feedback/admin.py | from django.contrib import admin
# Register your models here.
from .models import Feedback
class FeedbackAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'note', 'archive', 'public')
list_filter = ['created']
search_fields = ['name', 'email', 'note', 'archive', 'public']
admin.site.register(Fee... | from django.contrib import admin
# Register your models here.
from .models import Feedback
class FeedbackAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'note', 'archive', 'public')
list_filter = ['created']
search_fields = ['name', 'email', 'note', 'archive', 'public']
actions = ['to_arch... | Add Admin action to feedbacks | Add Admin action to feedbacks
| Python | mit | n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb,n2o/dpb | ---
+++
@@ -9,4 +9,10 @@
list_filter = ['created']
search_fields = ['name', 'email', 'note', 'archive', 'public']
+ actions = ['to_archive']
+
+ def to_archive(self, request, queryset):
+ queryset.update(archive=True)
+ to_archive.short_description = "Markierte Einträge archivieren"
+
adm... |
03f07ee52136d0794f581946718bd3ab7c53e22c | git-keeper-core/setup.py | git-keeper-core/setup.py | # setup.py for git-keeper-core
from setuptools import setup
setup(
name='git-keeper-core',
version='0.1.0',
description='Core modules for git-keeper-client and git-keeper-server.',
url='https://github.com/git-keeper/git-keeper',
license='GPL 3',
classifiers=[
'Development Status :: 2 -... | # setup.py for git-keeper-core
from setuptools import setup
setup(
name='git-keeper-core',
version='0.1.0',
description='Core modules for git-keeper-client and git-keeper-server.',
url='https://github.com/git-keeper/git-keeper',
license='GPL 3',
classifiers=[
'Development Status :: 2 -... | Remove paramiko requirement from core | Remove paramiko requirement from core
| Python | agpl-3.0 | git-keeper/git-keeper,git-keeper/git-keeper | ---
+++
@@ -20,7 +20,6 @@
'Topic :: Education'
],
packages=['gkeepcore'],
- install_requires=['paramiko'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
) |
b824e4c4a106d73c842a38758addde52d94e976a | ngrams_feature_extractor.py | ngrams_feature_extractor.py | import sklearn
def make_train_pair(filename):
h5 = open_h5_file_read(filename)
title = get_title(h5)
pitches = get_segments_pitches(h5)[:11] # limit: only look at beginning
pitch_diffs = [pitches[i] - pitches[i - 1] for i in xrange(1, len(pitches))]
h5.close()
return {'title': title, 'pitch_di... | import sklearn
from hdf5_getters import *
import os
def make_train_pair(filename):
h5 = open_h5_file_read(filename)
title = get_title(h5)
pitches = get_segments_pitches(h5)[:11] # limit: only look at beginning
pitch_diffs = [pitches[i] - pitches[i - 1] for i in xrange(1, len(pitches))]
h5.close()
... | Add corresponding hdf5 parsing file | Add corresponding hdf5 parsing file
| Python | mit | ajnam12/MusicNLP | ---
+++
@@ -1,5 +1,6 @@
import sklearn
-
+from hdf5_getters import *
+import os
def make_train_pair(filename):
h5 = open_h5_file_read(filename)
@@ -8,6 +9,14 @@
pitch_diffs = [pitches[i] - pitches[i - 1] for i in xrange(1, len(pitches))]
h5.close()
return {'title': title, 'pitch_diffs': pitch_... |
444d97288c0fd80adf4077477336c98bfea140cc | node.py | node.py | class Node(object):
def __init__(self):
# Properties will go here!
| class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
... | Initialize inbound and outbound Nodes of a Node | Initialize inbound and outbound Nodes of a Node
| Python | mit | YabinHu/miniflow | ---
+++
@@ -1,3 +1,9 @@
class Node(object):
def __init__(self):
- # Properties will go here!
+ # Node(s) from which this Node receives values
+ self.inbound_nodes = inbound_nodes
+ # Node(s) to which this Node passes values
+ self.outbound_nodes = []
+ # For each inbound Node here, add this Node... |
6558af15ae2f694b3ea08174e238d3d4de811c95 | warp10/src/main/python/callable.py | warp10/src/main/python/callable.py | #!/usr/bin/env python -u
import cPickle
import sys
import urllib
import base64
#
# Output the maximum number of instances of this 'callable' to spawn
# The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity'
#
print 10
#
# Loop, reading stdin, doing our stuff and outputing to stdout... | #!/usr/bin/env python -u
import cPickle
import sys
import urllib
import base64
#
# Output the maximum number of instances of this 'callable' to spawn
# The absolute maximum is set in the configuration file via 'warpscript.call.maxcapacity'
#
print 10
#
# Loop, reading stdin, doing our stuff and outputing to stdout... | Change default python string name str to mystr as str is a reserved name | Change default python string name str to mystr as str is a reserved name
| Python | apache-2.0 | hbs/warp10-platform,cityzendata/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,StevenLeRoux/warp10-platform,cityzendata/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,StevenLeRoux/warp10-platform,StevenLeRoux/warp10-platform,cityzendata/warp10-platform | ---
+++
@@ -27,8 +27,8 @@
line = line.strip()
line = urllib.unquote(line.decode('utf-8'))
# Remove Base64 encoding
- str = base64.b64decode(line)
- args = cPickle.loads(str)
+ mystr = base64.b64decode(line)
+ args = cPickle.loads(mystr)
#
# Do out stuff |
cc06a15f734a6ed46561a99d1040a08582833a09 | src/puzzle/heuristics/acrostic.py | src/puzzle/heuristics/acrostic.py | from puzzle.heuristics.acrostics import _acrostic_iter
class Acrostic(_acrostic_iter.AcrosticIter):
"""Best available Acrostic solver."""
pass
| from puzzle.heuristics.acrostics import _acrostic_search
class Acrostic(_acrostic_search.AcrosticSearch):
"""Best available Acrostic solver."""
pass
| Use AccrosticSearch (~BFS) instead of AcrosticIter (~DFS). | Use AccrosticSearch (~BFS) instead of AcrosticIter (~DFS).
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge | ---
+++
@@ -1,6 +1,6 @@
-from puzzle.heuristics.acrostics import _acrostic_iter
+from puzzle.heuristics.acrostics import _acrostic_search
-class Acrostic(_acrostic_iter.AcrosticIter):
+class Acrostic(_acrostic_search.AcrosticSearch):
"""Best available Acrostic solver."""
pass |
932d4c19810c26f94b5a1729130f5d459db6831e | tests/pytests/integration/_logging/test_jid_logging.py | tests/pytests/integration/_logging/test_jid_logging.py | import logging
import salt.config
from tests.support.helpers import PRE_PYTEST_SKIP
# Using the PRE_PYTEST_SKIP decorator since this test still fails on some platforms.
# Will investigate later.
@PRE_PYTEST_SKIP
def test_jid_in_logs(caplog, salt_call_cli):
"""
Test JID in log_format
"""
jid_formatte... | import logging
from salt._logging import DFLT_LOG_FMT_JID
from tests.support.helpers import PRE_PYTEST_SKIP
# Using the PRE_PYTEST_SKIP decorator since this test still fails on some platforms.
# Will investigate later.
@PRE_PYTEST_SKIP
def test_jid_in_logs(caplog, salt_call_cli):
"""
Test JID in log_format
... | Fix AttributeError: module 'salt.config' has no attribute '_DFLT_LOG_FMT_JID' | Fix AttributeError: module 'salt.config' has no attribute '_DFLT_LOG_FMT_JID'
```
$ python3 -m pytest -ra tests/pytests/integration/_logging/test_jid_logging.py
_______________________________ test_jid_in_logs _______________________________
@PRE_PYTEST_SKIP
def test_jid_in_logs(caplog, salt_call_cli):
... | Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -1,6 +1,6 @@
import logging
-import salt.config
+from salt._logging import DFLT_LOG_FMT_JID
from tests.support.helpers import PRE_PYTEST_SKIP
# Using the PRE_PYTEST_SKIP decorator since this test still fails on some platforms.
@@ -12,7 +12,7 @@
"""
Test JID in log_format
"""
- jid_... |
773064a61fcd4213196e44d347e304d746b28325 | syft/frameworks/torch/tensors/native.py | syft/frameworks/torch/tensors/native.py | import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
se... | import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = syft.local_worker
def ... | Set local worker as default for SyftTensor owner | Set local worker as default for SyftTensor owner
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -1,6 +1,8 @@
import random
from syft.frameworks.torch.tensors import PointerTensor
+
+import syft
class TorchTensor:
@@ -11,7 +13,7 @@
def __init__(self):
self.id = None
- self.owner = None
+ self.owner = syft.local_worker
def create_pointer(
self, loc... |
debb03975e8b647f27980081371bd9fdad7b292f | solar/solar/system_log/operations.py | solar/solar/system_log/operations.py |
from solar.system_log import data
from dictdiffer import patch
def set_error(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.get(task_uuid)
if item:
item.state = data.STATES.error
sl.update(task_uuid, item)
def move_to_commited(task_uuid, *args, **kwargs):
sl = data.SL()
... |
from solar.system_log import data
from dictdiffer import patch
def set_error(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.get(task_uuid)
if item:
item.state = data.STATES.error
sl.update(item)
def move_to_commited(task_uuid, *args, **kwargs):
sl = data.SL()
item = sl.p... | Fix update of logitem bug in system_log | Fix update of logitem bug in system_log
| Python | apache-2.0 | loles/solar,openstack/solar,loles/solar,pigmej/solar,pigmej/solar,torgartor21/solar,torgartor21/solar,loles/solar,dshulyak/solar,zen/solar,zen/solar,dshulyak/solar,zen/solar,Mirantis/solar,Mirantis/solar,Mirantis/solar,pigmej/solar,Mirantis/solar,CGenie/solar,CGenie/solar,openstack/solar,zen/solar,loles/solar,openstack... | ---
+++
@@ -9,7 +9,7 @@
item = sl.get(task_uuid)
if item:
item.state = data.STATES.error
- sl.update(task_uuid, item)
+ sl.update(item)
def move_to_commited(task_uuid, *args, **kwargs): |
e7e6274ee5fa16cb07e32bebe53532a6a16b7965 | dagrevis_lv/blog/templatetags/tags.py | dagrevis_lv/blog/templatetags/tags.py | from django import template
register = template.Library()
@register.filter
def get_style(tags, priority):
max_priority = max(tags, key=lambda tag: tag["priority"])["priority"]
size = (max_priority / 10.) * priority
return "font-size: {}em;".format(size)
| from django import template
register = template.Library()
@register.filter
def get_style(tags, priority):
max_priority = max(tags, key=lambda tag: tag["priority"])["priority"]
size = 100 / max_priority / priority / 2
return "font-size: {}em;".format(size)
| Fix tag cloud weird size | Fix tag cloud weird size
| Python | mit | daGrevis/daGrevis.lv,daGrevis/daGrevis.lv,daGrevis/daGrevis.lv | ---
+++
@@ -7,5 +7,5 @@
@register.filter
def get_style(tags, priority):
max_priority = max(tags, key=lambda tag: tag["priority"])["priority"]
- size = (max_priority / 10.) * priority
+ size = 100 / max_priority / priority / 2
return "font-size: {}em;".format(size) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.