commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e98f9fcc8537835b5a00bd0b6a755d7980a197de
template_tests/tests.py
template_tests/tests.py
import re import os from django.test import TestCase from .utils import get_template_dirs re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"') class TestTemplates(TestCase): def assertValidURLs(self, filename): with open(filename) as f: urls = [m.group('url') for m in re...
import re import os from django.test import TestCase from django.utils.text import slugify from .utils import get_template_dirs re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"') class TestTemplatesMeta(type): def __new__(cls, name, bases, attrs): def generate(template): ...
Use a metaclass instead of dirty dict()-mangling.
Use a metaclass instead of dirty dict()-mangling.
Python
bsd-3-clause
lamby/django-template-tests
57560385ef05ba6a2234e43795a037a487f26cfd
djaml/utils.py
djaml/utils.py
import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(l...
import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(l...
Fix submodule attribute check for Django 1.4 compatibility
Fix submodule attribute check for Django 1.4 compatibility
Python
mit
chartjes/djaml
db08b3462fc217cfbf3644051f299ef5bbef3d14
ckanext/stadtzhtheme/tests/test_validation.py
ckanext/stadtzhtheme/tests/test_validation.py
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. ...
import pytest from ckanapi import ValidationError from ckan.tests import helpers, factories from ckantoolkit import config @pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme") @pytest.mark.usefixtures("clean_db", "with_plugins") class TestValidation(object): def test_invalid_url(self): """Test that a...
Update tests to use pytest instead of nose
tests: Update tests to use pytest instead of nose
Python
agpl-3.0
opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme
22992aeeb123b061a9c11d812ac7fad6427453eb
timpani/themes.py
timpani/themes.py
import os import os.path from . import database THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes")) def getCurrentTheme(): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tab...
import os import os.path from . import database THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes")) def getCurrentTheme(): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tab...
Add template support to getCurrentTheme
Add template support to getCurrentTheme
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
335a33465e197c9a2e52ed9de90546e2ca6173ee
tests/test_websocket_subscriber.py
tests/test_websocket_subscriber.py
"""Tests for the WebSocketSubscriber handlers.""" import json import pytest from tornado.web import Application from tornado.websocket import websocket_connect from tornadose.handlers import WebSocketSubscriber import utilities @pytest.fixture def store(): return utilities.TestStore() @pytest.fixture def app...
"""Tests for the WebSocketSubscriber handlers.""" import json from tornado.ioloop import IOLoop from tornado.web import Application from tornado.websocket import websocket_connect from tornado.testing import AsyncHTTPTestCase, gen_test from tornadose.handlers import WebSocketSubscriber import utilities class WebSo...
Fix test case for WebSocketSubscriber
Fix test case for WebSocketSubscriber Switched to unittest-style testing (pytest is a bit too magical especially with the pytest-tornado extension). I may change all tests later to use unittest.
Python
mit
mivade/tornadose
3d2d07294f7b891b7e716911475333c5e34d5c98
tests/unit/test_raw_generichash.py
tests/unit/test_raw_generichash.py
# Import nacl libs import libnacl # Import python libs import unittest class TestGenericHash(unittest.TestCase): ''' Test sign functions ''' def test_keyless_generichash(self): msg1 = b'Are you suggesting coconuts migrate?' msg2 = b'Not at all, they could be carried.' chash1 =...
# Import nacl libs import libnacl # Import python libs import unittest class TestGenericHash(unittest.TestCase): ''' Test sign functions ''' def test_keyless_generichash(self): msg1 = b'Are you suggesting coconuts migrate?' msg2 = b'Not at all, they could be carried.' chash1 =...
Add tests for keyed hashes
Add tests for keyed hashes
Python
apache-2.0
mindw/libnacl,RaetProtocol/libnacl,cachedout/libnacl,johnttan/libnacl,coinkite/libnacl,saltstack/libnacl
44609e0432855506cd977cd39f1a780dfbd9e366
tests/consoles_tests.py
tests/consoles_tests.py
import io import spur from nose.tools import istest, assert_equal from toodlepip.consoles import Console @istest def console_writes_output_to_console(): console, output = _create_local_console() console.run("Action", ["echo", "Go go go!"]) assert b"Go go go!" in output.getvalue() def _create_local_con...
import io import spur from nose.tools import istest, assert_equal from toodlepip.consoles import Console @istest def console_writes_stdout_output_to_console(): console, output = _create_local_console() console.run("Action", ["echo", "Go go go!"]) assert b"Go go go!" in output.getvalue() @istest def co...
Add test for stderr output from console
Add test for stderr output from console
Python
bsd-2-clause
mwilliamson/toodlepip
2f9e058b4ef79f6eecb0292642c85a9e3e2376b0
examples/pipes-repl.py
examples/pipes-repl.py
''' Sample REPL code to integrate with Diesel Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions were handled well and the return value of code was printed. Using exec runs the input in the current context, but exception handling and other features of InteractiveInterpreter are lost. ''' ...
import sys import code import traceback from diesel import Application, Pipe, until QUIT_STR = "quit()\n" DEFAULT_PROMPT = '>>> ' def diesel_repl(): '''Simple REPL for use inside a diesel app''' # Import current_app into locals for use in REPL from diesel.app import current_app print 'Diesel Console'...
Fix REPL and add quit() command
Fix REPL and add quit() command
Python
bsd-3-clause
dieseldev/diesel
85123f01f1e63b4fc7688e13104ee59c6efb263a
proscli/main.py
proscli/main.py
import click import proscli from proscli.utils import default_options def main(): # the program name should always be pros. don't care if it's not... try: cli.main(prog_name='pros') except KeyboardInterrupt: click.echo('Aborted!') pass import prosconductor.providers...
import click import proscli from proscli.utils import default_options def main(): # the program name should always be pros. don't care if it's not... try: cli.main(prog_name='pros') except KeyboardInterrupt: click.echo('Aborted!') pass @click.command('pros', ...
Remove deprecated and broken pros help option
Remove deprecated and broken pros help option
Python
mpl-2.0
purduesigbots/pros-cli,purduesigbots/purdueros-cli
7bc4afdde415ec4176c589fb867ccdee2db5c041
fmn/filters/generic.py
fmn/filters/generic.py
# Generic filters for FMN import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedms...
# Generic filters for FMN import fedmsg import fmn.lib.pkgdb def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: r...
Add first filter relying on pkgdb integration
Add first filter relying on pkgdb integration
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
8d235a76120aadcd555da3d641f509541f525eb8
csunplugged/utils/retrieve_query_parameter.py
csunplugged/utils/retrieve_query_parameter.py
"""Module for retrieving a GET request query parameter.""" from django.http import Http404 def retrieve_query_parameter(request, parameter, valid_options=None): """Retrieve the query parameter. If the parameter cannot be found, or is not found in the list of valid options, then a 404 error is raised. ...
"""Module for retrieving a GET request query parameter.""" from django.http import Http404 def retrieve_query_parameter(request, parameter, valid_options=None): """Retrieve the query parameter. If the parameter cannot be found, or is not found in the list of valid options, then a 404 error is raised. ...
Add function to get list of parameters
Add function to get list of parameters
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
d4adacc41858e224a8508a6da7ea77a30d1f8d9a
utils/data_paths.py
utils/data_paths.py
import os ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data') DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu') DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um') SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submi...
import os ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data') DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu') DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um') SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submi...
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
Python
mit
jvanbrug/netflix,jvanbrug/netflix
091c125f42463b372f0c2c99124578eb8fe13150
2019/aoc2019/day08.py
2019/aoc2019/day08.py
from collections import Counter from typing import Iterable, TextIO import numpy # type: ignore def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]: chunk_size = width * height content = next(data).strip() for pos in range(0, len(content), chunk_size): yield numpy....
from collections import Counter from typing import Iterable, TextIO import numpy # type: ignore def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]: chunk_size = width * height content = next(data).strip() for pos in range(0, len(content), chunk_size): yield numpy....
Fix day 8 to paint front-to-back
Fix day 8 to paint front-to-back
Python
mit
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv...
28ecf02c3d08eae725512e1563cf74f1831bd02d
gears/engines/base.py
gears/engines/base.py
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwarg...
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwarg...
Fix unicode support in ExecEngine
Fix unicode support in ExecEngine
Python
isc
gears/gears,gears/gears,gears/gears
52610add5ae887dcbc06f1435fdff34f182d78c9
go/campaigns/forms.py
go/campaigns/forms.py
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('C', 'Conversation'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign ...
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('D', 'Dialogue'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign woul...
Use dialogue terminology in menu
Use dialogue terminology in menu
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
ee2e1727ece6b591b39752a1d3cd6a87d972226d
github3/search/code.py
github3/search/code.py
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in ...
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in ...
Add a __repr__ for CodeSearchResult
Add a __repr__ for CodeSearchResult
Python
bsd-3-clause
h4ck3rm1k3/github3.py,ueg1990/github3.py,degustaf/github3.py,krxsky/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,agamdua/github3.py,wbrefvem/github3.py,jim-minter/github3.py,icio/github3.py,christophelec/github3.py,balloob/github3.py
48ab19d9f81fc9973249e600f938586182fe6c7b
shop/rest/auth.py
shop/rest/auth.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.template.loader import select_template from rest_framework.serializers import CharField from rest_auth import serializers from shop import settings as shop_settings class PasswordResetSerializer(serializers.Pa...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.template.loader import select_template from rest_framework.serializers import CharField from rest_auth import serializers from shop import settings as shop_settings class PasswordResetSerializer(serializers.Pa...
Fix a failing test for PasswordResetSerializer
Fix a failing test for PasswordResetSerializer It seems that Django's template API changed. This should adjust to that.
Python
bsd-3-clause
awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,jrief/django-shop,rfleschenberg/django-shop,awesto/django-shop,khchine5/django-shop,divio/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,rfleschenberg/django-shop,jrief/django-shop,rfleschenberg/django-s...
a854c1564f581bda5c355d97069d775485a65047
installer/steps/a_setup_virtualenv.py
installer/steps/a_setup_virtualenv.py
import os import re from helper import * import unix_windows section("Preparing virtualenv") # check that virtualenv installed if not executable_exists('virtualenv'): fail("""\ Please install virtualenv! https://github.com/pypa/virtualenv {}""".format(unix_windows.VIRTUALENV_INSTALL_MSG)) # Make sure that no...
import os import re from helper import * import unix_windows section("Preparing virtualenv") # check that virtualenv installed if not executable_exists('virtualenv'): fail("""\ Please install virtualenv! https://github.com/pypa/virtualenv {}""".format(unix_windows.VIRTUALENV_INSTALL_MSG)) # Make sure that no...
Fix python path for windows
Fix python path for windows
Python
mit
appi147/Jarvis,sukeesh/Jarvis,appi147/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis
652bca441489dd49552cbd5945605d51921394f0
snowfloat/settings.py
snowfloat/settings.py
"""Client global settings.""" HOST = 'api.snowfloat.com:443' HTTP_TIMEOUT = 10 HTTP_RETRIES = 3 HTTP_RETRY_INTERVAL = 5 API_KEY = '' API_PRIVATE_KEY = '' try: # pylint: disable=F0401 from settings_prod import * except ImportError: try: # pylint: disable=F0401 from settings_dev import * ...
"""Client global settings.""" import os import ConfigParser HOST = 'api.snowfloat.com:443' HTTP_TIMEOUT = 10 HTTP_RETRIES = 3 HTTP_RETRY_INTERVAL = 5 API_KEY = '' API_PRIVATE_KEY = '' CONFIG = ConfigParser.RawConfigParser() for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"): try: with open...
Read config file in different locations and set global config variables based on that.
Read config file in different locations and set global config variables based on that.
Python
bsd-3-clause
snowfloat/snowfloat-python,snowfloat/snowfloat-python
dbf147b4842edd96842fa384b594265daf0c555e
byceps/util/system.py
byceps/util/system.py
""" byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os import sys CONFIG_VAR_NAME = 'BYCEPS_CONFIG' def get_config_filename_from_env() -> str: """Return the configuration filename set via environment variable. Ra...
""" byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os import sys from ..config import ConfigurationError CONFIG_VAR_NAME = 'BYCEPS_CONFIG' def get_config_filename_from_env() -> str: """Return the configuration filen...
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps
0f8c4cd71bff68860d0a18f8680eda9a690f0959
sqlstr/exception.py
sqlstr/exception.py
''' Exceptions from sqlstr ------------------------- ''' class sqlstrException(Exception): def __init__(self, message): ''' Instanitates a custom sqlstrException :message str: ''' Exception.__init__(self, message)
''' Exceptions from sqlstr ------------------------- ''' class sqlstrException(Exception): def __init__(self, message): ''' Instanitates a custom sqlstrException message -- string. Message describing the exception. ''' Exception.__init__(self, message)
Update docstring with parameter listing
Update docstring with parameter listing
Python
mit
GochoMugo/sql-string-templating
a0a0d120552eeb304ac4b49648a43be5cf83cdcb
piper/core.py
piper/core.py
class Piper(object): """ The main runner. This class loads the configurations, sets up all other components, and finally executes them in whatever order they are supposed to happen in. """ def __init__(self): pass
import logbook class Piper(object): """ The main pipeline runner. This class loads the configurations, sets up all other components, executes them in whatever order they are supposed to happen in, collects data about the state of the pipeline and persists it, and finally tears down the compon...
Add more skeletonisms and documentation for Piper()
Add more skeletonisms and documentation for Piper()
Python
mit
thiderman/piper
0261a0f9a1dde9f9f6167e3630561219e3dca124
statsmodels/datasets/__init__.py
statsmodels/datasets/__init__.py
""" Datasets module """ #__all__ = filter(lambda s:not s.startswith('_'),dir()) import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \ macrodata, nile, randhie, scotland, spector, stackloss, star98, \ strikes, sunspots, fair, heart, statecrime
""" Datasets module """ #__all__ = filter(lambda s:not s.startswith('_'),dir()) from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, macrodata, nile, randhie, scotland, spector, stackloss, star98, strikes, sunspots, fair, heart, statecrime)
Switch to relative imports and fix pep-8
STY: Switch to relative imports and fix pep-8
Python
bsd-3-clause
bsipocz/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,hlin117/statsmodels,musically-ut/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,bert9bert/statsmodels,astocko/statsmodels,jse...
105b5c3d8db38be9a12974e7be807c429e8ad9ad
contentcuration/contentcuration/utils/asynccommand.py
contentcuration/contentcuration/utils/asynccommand.py
from abc import abstractmethod from collections import namedtuple from django.core.management.base import BaseCommand from django.core.management.base import CommandError Progress = namedtuple( 'Progress', [ 'progress', 'total', 'fraction', ] ) class TaskCommand(BaseCommand): ...
import logging as logmodule from abc import abstractmethod from django.core.management.base import BaseCommand logmodule.basicConfig() logging = logmodule.getLogger(__name__) class Progress(): """ A Progress contains the progress of the tasks, the total number of expected tasks/data, and the fraction wh...
Define Progress as a Class and add more comments
Define Progress as a Class and add more comments
Python
mit
fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,DXCanas/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation
e26573b37f6cb12817b35d3ac0d19fa301fd1a99
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
# -*- coding: utf-8 -*- import pytest def pytest_addoption(parser): group = parser.getgroup('{{cookiecutter.plugin_name}}') group.addoption( '--foo', action='store_const', dest='foo', help='alias for --foo' )
# -*- coding: utf-8 -*- import pytest def pytest_addoption(parser): group = parser.getgroup('{{cookiecutter.plugin_name}}') group.addoption( '--foo', action='store_const', dest='foo', help='alias for --foo' ) @pytest.fixture def bar(request): return request.config.op...
Implement a custom fixture for the plugin
Implement a custom fixture for the plugin
Python
mit
pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin
aeebd8a4f2255bff03fbb55f3d7d29d822fbb31b
logaugment/__init__.py
logaugment/__init__.py
import logging class AugmentFilter(logging.Filter): def __init__(self, name='', args=None): super(AugmentFilter, self).__init__(name) self._args = args def filter(self, record): if self._args is not None: data = {} try: if callable(self._args):...
import logging __title__ = 'logaugment' __version__ = '0.0.1' __author__ = 'Simeon Visser' __email__ = 'simeonvisser@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2014 Simeon Visser' class AugmentFilter(logging.Filter): def __init__(self, name='', args=None): super(AugmentFilter, self).__ini...
Add project details to codebase
Add project details to codebase
Python
mit
svisser/logaugment
a9accd5460157e323e8514178d3e7bc9d2fa8667
dn1/kolona_vozil_test.py
dn1/kolona_vozil_test.py
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) if __name__ == '__mai...
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil, Vozilo class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) def test_v...
Update unittests for Task 4
Update unittests for Task 4
Python
mit
nbasic/racunalnistvo-1
05e651b0e606f216a78c61ccfb441ce7ed41d852
reg/compat.py
reg/compat.py
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) d...
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) d...
Exclude from coverage the code pathways that are specific to Python 2.
Exclude from coverage the code pathways that are specific to Python 2.
Python
bsd-3-clause
morepath/reg,taschini/reg
56186c985b87fbbf0a7ea0f04c8b089a13b29fe3
execute_all_tests.py
execute_all_tests.py
#! /bin/python3 """ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be us...
#! /bin/python3 """ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be us...
Test execution: Remove unneeded variable
Test execution: Remove unneeded variable
Python
agpl-3.0
Tanmay28/coala,Tanmay28/coala,meetmangukiya/coala,arush0311/coala,NalinG/coala,Tanmay28/coala,incorrectusername/coala,yashtrivedi96/coala,shreyans800755/coala,sagark123/coala,jayvdb/coala,MariosPanag/coala,Nosferatul/coala,vinc456/coala,damngamerz/coala,MattAllmendinger/coala,ManjiriBirajdar/coala,andreimacavei/coala,r...
39f327bb9e37d6d290eb3f3179f7e79d60b5ab6d
model.py
model.py
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine engine = create_engine('postgresql://wn:wn@localhost:5432/wndb') Base = declarative_base() from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String class Observation(Base): __tablename__ = 'obs' id =...
from sqlalchemy import create_engine engine = create_engine('postgresql://wn:wn@localhost:5432/wndb') from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String, MetaData metadata = MetaData() table = Table('obs', metadata, Column(Integer, primary_key=True), Column('station_name',String), Colum...
Switch from ORM to Core
Switch from ORM to Core
Python
mit
labhack/whiskeynovember,labhack/whiskeynovember,labhack/whiskeynovember
3af2a5b6eda4af972e3a208e727483384f313cb9
octotribble/csv2tex.py
octotribble/csv2tex.py
#!/usr/bin/env python """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", ...
#!/usr/bin/env python """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", ...
Remove index and check filename
Remove index and check filename
Python
mit
jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble
b639e094f0ac9feb008c0d13deb26c55bbb50793
git_gutter_change.py
git_gutter_change.py
import sublime import sublime_plugin try: from GitGutter.view_collection import ViewCollection except ImportError: from view_collection import ViewCollection class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand): def lines_to_blocks(self, lines): blocks = [] last_line = -2 ...
import sublime import sublime_plugin try: from GitGutter.view_collection import ViewCollection except ImportError: from view_collection import ViewCollection class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand): def lines_to_blocks(self, lines): blocks = [] last_line = -2 ...
Make jumping between changes loop back around
Make jumping between changes loop back around
Python
mit
michaelhogg/GitGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,akpersad/GitGutter,akpersad/GitGutter,nateca...
6a7fb1ff05202f60c7036db369926e3056372123
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
import unittest import numpy import chainer.functions as F from chainer import testing def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy # # sqrt @testing.math_function_test(F.Sqrt(), make_data=make_da...
import unittest import numpy import chainer.functions as F from chainer import testing # # sqrt def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy @testing.math_function_test(F.Sqrt(), make_data=make_da...
Simplify test of rsqrt function.
Simplify test of rsqrt function.
Python
mit
chainer/chainer,niboshi/chainer,hvy/chainer,hvy/chainer,anaruse/chainer,ktnyt/chainer,jnishi/chainer,pfnet/chainer,keisuke-umezawa/chainer,cupy/cupy,ysekky/chainer,kashif/chainer,keisuke-umezawa/chainer,ronekko/chainer,niboshi/chainer,wkentaro/chainer,cupy/cupy,kiyukuta/chainer,okuta/chainer,delta2323/chainer,hvy/chain...
63bf9c267ff891f1a2bd1f472a5d77f8df1e0209
tests/iam/test_iam_valid_json.py
tests/iam/test_iam_valid_json.py
"""Test IAM Policy templates are valid JSON.""" import jinja2 from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE...
"""Test IAM Policy templates are valid JSON.""" import json import jinja2 import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2...
Split IAM template tests with paramtrize
test: Split IAM template tests with paramtrize See also: #208
Python
apache-2.0
gogoair/foremast,gogoair/foremast
0ff797d60c2ddc93579e7c486e8ebb77593014d8
apiclient/__init__.py
apiclient/__init__.py
"""Retain apiclient as an alias for googleapiclient.""" import googleapiclient from googleapiclient import channel from googleapiclient import discovery from googleapiclient import errors from googleapiclient import http from googleapiclient import mimeparse from googleapiclient import model from googleapiclient impo...
"""Retain apiclient as an alias for googleapiclient.""" import googleapiclient try: import oauth2client except ImportError: raise RuntimeError( 'Previous version of google-api-python-client detected; due to a ' 'packaging issue, we cannot perform an in-place upgrade. To repair, ' 'remove and rei...
Add another check for a failed googleapiclient upgrade.
Add another check for a failed googleapiclient upgrade. This adds one more check for a failed 1.2 -> 1.3 upgrade, specifically in the `apiclient` import (which was the only import available in 1.2). Even combined with the check in setup.py, this won't catch everything, but it now covers all the most common cases.
Python
apache-2.0
googleapis/google-api-python-client,googleapis/google-api-python-client
e15fb53c0fd63942cafd3a6f11418447df6b6800
siphon/cdmr/tests/test_coveragedataset.py
siphon/cdmr/tests/test_coveragedataset.py
# Copyright (c) 2016 Unidata. # Distributed under the terms of the MIT License. # SPDX-License-Identifier: MIT import warnings from siphon.testing import get_recorder from siphon.cdmr.coveragedataset import CoverageDataset recorder = get_recorder(__file__) # Ignore warnings about CoverageDataset warnings.simplefilte...
# Copyright (c) 2016 Unidata. # Distributed under the terms of the MIT License. # SPDX-License-Identifier: MIT import warnings from siphon.testing import get_recorder from siphon.cdmr.coveragedataset import CoverageDataset recorder = get_recorder(__file__) # Ignore warnings about CoverageDataset warnings.simplefilte...
Add smoketest for convering CoverageDataset to str.
Add smoketest for convering CoverageDataset to str.
Python
bsd-3-clause
dopplershift/siphon,dopplershift/siphon,Unidata/siphon
535ac4c6eae416461e11f33c1a1ef67e92c73914
tests/test_exception_wrapping.py
tests/test_exception_wrapping.py
import safe def test_simple_exception(): class MockReponse(object): def json(self): return {'status': False, 'method': 'synchronize', 'module': 'cluster', 'error': {'message': 'Example error'}} exception = safe.library.raise_from...
import safe class MockResponse(object): def __init__(self, data): self.data = data def json(self): return self.data def test_basic_exception(): error_message = 'Example error' response = MockResponse({ 'status': False, 'method': 'synchronize', 'module': 'clus...
Add a commit failed test
Add a commit failed test
Python
mpl-2.0
sangoma/safepy2,leonardolang/safepy2
d5d359c5ec0f1735e97355839f1a12c6ea45c460
polygamy/pygit2_git.py
polygamy/pygit2_git.py
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmetho...
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmetho...
Add add_remote to pygit2 implementation
Add add_remote to pygit2 implementation
Python
bsd-3-clause
solarnz/polygamy,solarnz/polygamy
5fc65183e40dd1d06bd6ae3e4e7ba0f0a0e2bdd6
alg_check_dag.py
alg_check_dag.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _previsit(): pass def _postvisit(): pass def _dfs_explore(): pass def check_dag(): """Check Directed Acyclic Graph (DAG).""" pass def main(): # DAG. dag_adj_d = { '...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _previsit(): pass def _postvisit(): pass def _dfs_explore(): pass def check_dag(): """Check Directed Acyclic Graph (DAG).""" pass def main(): # Graph adjacency dictionary for D...
Add DAG & non-DAG adjacency dicts
Add DAG & non-DAG adjacency dicts
Python
bsd-2-clause
bowen0701/algorithms_data_structures
4b665bb2e85994e3df0324afacb2453b8f4998a1
contact_map/tests/test_dask_runner.py
contact_map/tests/test_dask_runner.py
# pylint: disable=wildcard-import, missing-docstring, protected-access # pylint: disable=attribute-defined-outside-init, invalid-name, no-self-use # pylint: disable=wrong-import-order, unused-wildcard-import from .utils import * from contact_map.dask_runner import * class TestDaskContactFrequency(object): def te...
# pylint: disable=wildcard-import, missing-docstring, protected-access # pylint: disable=attribute-defined-outside-init, invalid-name, no-self-use # pylint: disable=wrong-import-order, unused-wildcard-import from .utils import * from contact_map.dask_runner import * def dask_setup_test_cluster(distributed, n_workers...
Handle dask TimeoutError exception in tests
Handle dask TimeoutError exception in tests
Python
lgpl-2.1
dwhswenson/contact_map,dwhswenson/contact_map
8c228a79450c49ee1d494ca1e3cf61ea7bcc8177
setup.py
setup.py
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import os import steam class run_tests(Command): description...
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run th...
Set API key directly in test runner
Set API key directly in test runner
Python
isc
miedzinski/steamodd,Lagg/steamodd
5f58d9f73b3b674d1d39ea7027a2e6de6dc8ff44
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='nutshell', packages=['nutshell'], version='0.1.1', description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/p...
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='nutshell', packages=['nutshell'], version='0.1.1', description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/p...
Add requests as installation dependency.
Add requests as installation dependency.
Python
mit
EmilStenstrom/python-nutshell
ce0f4a30cad570557ad67122333041806d411adc
tasks.py
tasks.py
from invoke import Collection from invocations import docs from invocations.checks import blacken from invocations.packaging import release from invocations.pytest import test, coverage ns = Collection(test, coverage, release, blacken, docs) ns.configure({"packaging": {"sign": True}})
from invoke import Collection from invocations import docs from invocations.checks import blacken from invocations.packaging import release from invocations.pytest import test, coverage ns = Collection(test, coverage, release, blacken, docs) ns.configure( {"packaging": {"sign": True, "changelog_file": "docs/chang...
Set changelog_file for invocations release task, which now dry-runs ok
Set changelog_file for invocations release task, which now dry-runs ok
Python
bsd-2-clause
bitprophet/lexicon
35fab0222543a2f32ef395bf6b622bad29533ceb
tests.py
tests.py
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() def test_lazy_init(self): ...
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() self.launcher = Launcher(self...
Create lazy launcher in setUp.
Create lazy launcher in setUp.
Python
mit
GoldenLine/gtlaunch
f7852806c3198d58162b66e18bfd9998ef33b63c
lexos/receivers/stats_receiver.py
lexos/receivers/stats_receiver.py
from lexos.receivers.base_receiver import BaseReceiver class StatsReceiver(BaseReceiver): def __init__(self): """So far there is no frontend option for statistics analysis""" super().__init__() def options_from_front_end(self): """So far there is no frontend option for statistics anal...
from lexos.receivers.base_receiver import BaseReceiver class StatsReceiver(BaseReceiver): def __init__(self): """So far there is no frontend option for statistics analysis""" super().__init__() def options_from_front_end(self): """So far there is no frontend option for statistics anal...
Modify receiver to prevent using in future
Modify receiver to prevent using in future
Python
mit
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
addee67fbf46a795c9de4669c9951c84b6590d98
cartoframes/context/base_context.py
cartoframes/context/base_context.py
from abc import ABCMeta, abstractmethod class BaseContext(): __metaclass__ = ABCMeta @abstractmethod def download(self): pass @abstractmethod def upload(self): pass @abstractmethod def execute_query(self): pass @abstractmethod def execute_long_running_qu...
from abc import ABCMeta, abstractmethod class BaseContext(): __metaclass__ = ABCMeta @abstractmethod def download(self, query, retry_times=0): pass @abstractmethod def upload(self, query, data): pass @abstractmethod def execute_query(self, query, parse_json=True, do_post...
Add params in BaseContext abtract methods
Add params in BaseContext abtract methods
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
b084e02dd2cf7b492c69090b6acd548066c7c34f
pos_picking_state_fix/models/pos_picking.py
pos_picking_state_fix/models/pos_picking.py
# -*- coding: utf-8 -*- # See README file for full copyright and licensing details. from openerp import models, api class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: # ...
# -*- coding: utf-8 -*- # See README file for full copyright and licensing details. import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: su...
Check if quants are moved and pass moves to done to avoid duplication
[FIX] Check if quants are moved and pass moves to done to avoid duplication
Python
agpl-3.0
rgbconsulting/rgb-addons,rgbconsulting/rgb-pos,rgbconsulting/rgb-pos,rgbconsulting/rgb-addons
5b011488b5fcfd17f2029e833b757d24d437908e
document_page_project/__manifest__.py
document_page_project/__manifest__.py
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) - Lois Rilo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "13.0.1.0.1", "development_status": "Production/Stable",...
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) - Lois Rilo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "13.0.1.0.1", "development_status": "Beta", "categor...
Revert to Beta as document_page is Beta
[REV] document_page_project: Revert to Beta as document_page is Beta
Python
agpl-3.0
OCA/knowledge,OCA/knowledge,OCA/knowledge
f40bf1441121c138877e27bd23bcef73cf5c2cef
cisco_olt_http/tests/test_operations.py
cisco_olt_http/tests/test_operations.py
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_...
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) @pytest.fixture def ok_response(data_dir, mocker): response = mocker.Mock(a...
Move ok response creation to pytest fixture
Move ok response creation to pytest fixture
Python
mit
Vnet-as/cisco-olt-http-client,beezz/cisco-olt-http-client
19af4b5c8c849750dd0885ea4fcfb651545b7985
migrations/002_add_month_start.py
migrations/002_add_month_start.py
""" Add _week_start_at field to all documents in all collections """ from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) col...
""" Add _week_start_at field to all documents in all collections """ from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) col...
Remove disallowed fields before resaving on migrations.
Remove disallowed fields before resaving on migrations. - TODO: fix this properly.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
de5c0c9107156a073670d68fcb04e575e08f9b80
sympy/__init__.py
sympy/__init__.py
__version__ = "0.5.0" from sympy.core import * from series import * from simplify import * from solvers import * from matrices import * from geometry import * from polynomials import * from utilities import * #from specfun import * from integrals import * try: from plotting import Plot except ImportError, e: ...
__version__ = "0.5.0" from sympy.core import * from series import * from simplify import * from solvers import * from matrices import * from geometry import * from polynomials import * from utilities import * #from specfun import * from integrals import * try: from plotting import Plot except ImportError, e: ...
Hide ctypes import error until Plot() is called.
Hide ctypes import error until Plot() is called.
Python
bsd-3-clause
kmacinnis/sympy,Curious72/sympy,meghana1995/sympy,MechCoder/sympy,saurabhjn76/sympy,VaibhavAgarwalVA/sympy,Designist/sympy,lidavidm/sympy,skidzo/sympy,beni55/sympy,Davidjohnwilson/sympy,jaimahajan1997/sympy,kmacinnis/sympy,MridulS/sympy,mcdaniel67/sympy,jbbskinny/sympy,pandeyadarsh/sympy,jaimahajan1997/sympy,mattpap/sy...
b82dbd63aedf8a6a6af494b6d6be697a9f4230d5
tests/test_utils.py
tests/test_utils.py
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: ...
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes, expand_axis_label @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pi...
Add unit test for expand_axis_label
Add unit test for expand_axis_label
Python
mit
dwf/fuel,ejls/fuel,udibr/fuel,rizar/fuel,capybaralet/fuel,rizar/fuel,EderSantana/fuel,EderSantana/fuel,orhanf/fuel,aalmah/fuel,mila-udem/fuel,mjwillson/fuel,glewis17/fuel,orhanf/fuel,dhruvparamhans/fuel,hantek/fuel,lamblin/fuel,jbornschein/fuel,dribnet/fuel,markusnagel/fuel,udibr/fuel,harmdevries89/fuel,dribnet/fuel,gl...
3e6f835a88183182b6ebba25c61666735a69fc81
tests/vaultshell.py
tests/vaultshell.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest class VaultShellTests(unittest.TestCase): def test_basic(self): print "test basic. Pass"
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import vault_shell.vault_commandhelper as VaultHelper class VaultShellTests(unittest.TestCase): def test_basic(self): print "test basic. Pass" vaulthelper = VaultHelper.VaultCommandHelper() self.failUnless(vaulthelper is not Non...
Add more tests for the vault commandhelper
Add more tests for the vault commandhelper
Python
apache-2.0
bdastur/vault-shell
8170ad6cdfd2346bc24a3d743663b4866416ca83
Engine.py
Engine.py
#Imports import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window sel...
#Imports import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window sel...
Add functions to add shapes and iterate over each shape to render.
Add functions to add shapes and iterate over each shape to render.
Python
mit
thebillington/pyPhys3D
92adc02daae13f6ef24ae1ec2eafac77ce528a74
setup/timvideos/streaming/list_aws_hosts.py
setup/timvideos/streaming/list_aws_hosts.py
# list_aws_hosts.py # list all active ec2 hosts from boto import ec2 import pw creds = pw.stream['aws'] ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key'] ) reservations = ec2conn.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: if not i.dns_name: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # list_aws_hosts.py # list all active ec2 hosts """ Start / stop by name. Start mission "list_aws_hosts.py start mission" Stop mission "list_aws_hosts.py stop mission" Status mission "list_aws_hosts.py status mission" mission i-b59966c7 **OFF** stopped """ from boto imp...
Update script to start, stop and status by name.
Update script to start, stop and status by name.
Python
mit
EricSchles/veyepar,CarlFK/veyepar,yoe/veyepar,yoe/veyepar,xfxf/veyepar,EricSchles/veyepar,yoe/veyepar,xfxf/veyepar,CarlFK/veyepar,xfxf/veyepar,CarlFK/veyepar,EricSchles/veyepar,CarlFK/veyepar,xfxf/veyepar,xfxf/veyepar,CarlFK/veyepar,yoe/veyepar,yoe/veyepar,EricSchles/veyepar,EricSchles/veyepar
6da69eb8f13dc56cc19d06a09d74005395de8989
fedmsg_meta_umb/tps.py
fedmsg_meta_umb/tps.py
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb is ...
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb is ...
Add missing attributes in TPSProcessor.
Add missing attributes in TPSProcessor. Signed-off-by: shanks <4508bc7244505cbe28c7ec6ff0c99c8246ca3de6@redhat.com>
Python
lgpl-2.1
release-engineering/fedmsg_meta_umb
153ed6a519d6836adb02b934cff44974a7132b6d
flake8/parseDocTest.py
flake8/parseDocTest.py
def parseFailDetails(failDetails): """ Parse the line number of the doctest failure""" import re failDetails = failDetails.split(',') lineNo = -1 if len(failDetails) == 3: match = re.search("line.*?(\d+)", failDetails[1]) if match is None: return lineNo lineNo = i...
def parseFailDetails(failDetails): """ Parse the line number of the doctest failure >>> parseFailDetails("blah") -1 """ import re failDetails = failDetails.split(',') lineNo = -1 if len(failDetails) == 3: match = re.search("line.*?(\d+)", failDetails[1]) if match is None:...
Fix doc test failure parsing
Fix doc test failure parsing
Python
mit
softwaredoug/flake8_doctest
808d089b2b93671ef3d4331007fc1c3da2dea0b5
example/urls.py
example/urls.py
from django.conf.urls import patterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^example/', include('example.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' ...
from django.conf.urls import patterns from rpc4django.views import serve_rpc_request # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^example/', include('example.foo.urls')), # Uncomment the admin/doc...
Use django 1.10 patterns style
Use django 1.10 patterns style
Python
bsd-3-clause
davidfischer/rpc4django,davidfischer/rpc4django,davidfischer/rpc4django
40905893c296e2c812539079925adfd25e39d44f
wger/wsgi.py
wger/wsgi.py
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLIC...
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLIC...
Change location of default settings in WSGI
Change location of default settings in WSGI
Python
agpl-3.0
petervanderdoes/wger,rolandgeider/wger,DeveloperMal/wger,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,wger-project/wger,petervanderdoes/wger,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,DeveloperMal/wger,kjagoo/wger_stark,wger-project/wger,petervanderdoes/wger,rolan...
98fad1af84abe13eb64baad58c8a2faf3cd6cccb
tt_dailyemailblast/tasks.py
tt_dailyemailblast/tasks.py
from celery.task import task from . import models from . import send_backends @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) send_backends.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.Da...
from celery.task import task from . import models from .send_backends import sync @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) sync.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEm...
Fix every single async task was broken
Fix every single async task was broken
Python
apache-2.0
texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast
d33a624fa6aedb93ae43ba1d2c0f6a76d90ff4a6
foldermd5sums.py
foldermd5sums.py
#!/usr/bin/env python """Script to read data files in a directory, compute their md5sums, and output them to a JSON file.""" import json import os import sys import hashlib def get_md5sums(directory): md5sums = [] for filename in os.listdir(directory): md5 = hashlib.md5() with open(os.path.jo...
#!/usr/bin/env python """Script to read data files in a directory, compute their md5sums, and output them to a JSON file.""" import json import os import sys import hashlib def get_relative_filepaths(base_directory): """ Return a list of file paths without the base_directory prefix""" file_list = [] for ...
Allow directory of files to be indexed
ENH: Allow directory of files to be indexed In the Data directory, there may be sub-directories of files that need to be kept separate, but all of them need to be indexed.
Python
apache-2.0
zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks
cbefb84542d9dfddd0f2fdf8bd0cb2fc89d5b824
jupytext/__init__.py
jupytext/__init__.py
"""Read and write Jupyter notebooks as text files""" from .jupytext import readf, writef, writes, reads from .formats import NOTEBOOK_EXTENSIONS, guess_format, get_format_implementation from .version import __version__ try: from .contentsmanager import TextFileContentsManager except ImportError as err: class ...
"""Read and write Jupyter notebooks as text files""" from .jupytext import readf, writef, writes, reads from .formats import NOTEBOOK_EXTENSIONS, guess_format, get_format_implementation from .version import __version__ try: from .contentsmanager import TextFileContentsManager except ImportError as err: class ...
Allow "jupyter nbextension install/enable --py jupytext"
Allow "jupyter nbextension install/enable --py jupytext"
Python
mit
mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext
20d21b851d02bbcf8c6a0f065b9f05f5e0bfc662
geodj/youtube.py
geodj/youtube.py
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderb...
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderb...
Use format=5 in YT search to prevent "embedding disabled"
Use format=5 in YT search to prevent "embedding disabled"
Python
mit
6/GeoDJ,6/GeoDJ
1d6bb5e7ce706c8f54599f98744f3a5d62ce104e
src/config.py
src/config.py
import os import ConfigParser as configparser class Config(object): def __init__(self): self.config = configparser.RawConfigParser() self.configfile = os.path.expanduser('~/.mmetering-clirc') if not os.path.isfile(self.configfile): # setup a new config file self.ini...
import os import ConfigParser as configparser class Config(object): def __init__(self): self.config = configparser.RawConfigParser() self.configfile = os.path.expanduser('~/.mmetering-clirc') if not os.path.isfile(self.configfile): # setup a new config file self.ini...
Replace get_base_dir and set_base_dir with more abstract methods get and set
Replace get_base_dir and set_base_dir with more abstract methods get and set
Python
mit
mmetering/mmetering-cli
e966ddd804eee2f1b053de6f0bbf943d80dccc59
django_elastipymemcache/client.py
django_elastipymemcache/client.py
from pymemcache.client.hash import HashClient class Client(HashClient): def get_many(self, keys, gets=False, *args, **kwargs): # pymemcache's HashClient may returns {'key': False} end = super(Client, self).get_many(keys, gets, args, kwargs) return {key: end[key] for key in end if end[key]...
from pymemcache.client.hash import HashClient class Client(HashClient): def get_many(self, keys, gets=False, *args, **kwargs): # pymemcache's HashClient may returns {'key': False} end = super(Client, self).get_many(keys, gets, args, kwargs) return {key: end.get(key) for key in end if end....
Fix get value more safe
Fix get value more safe
Python
mit
uncovertruth/django-elastipymemcache
60daa277d5c3f1d9ab07ff5beccdaa323996068b
feincmstools/templatetags/feincmstools_tags.py
feincmstools/templatetags/feincmstools_tags.py
import os from django import template register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False ...
import os from django import template from feincms.templatetags.feincms_tags import feincms_render_content register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page ...
Add assignment tag util for rendering chunks to tpl context
Add assignment tag util for rendering chunks to tpl context
Python
bsd-3-clause
ixc/glamkit-feincmstools,ixc/glamkit-feincmstools
1e5102d8bafb3b4d2cb07822129397aa56f30bbe
devicecloud/examples/example_helpers.py
devicecloud/examples/example_helpers.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from devicecloud import DeviceCloud...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from six.moves import input from de...
Handle using the input function in python 2 for getting username for examples
Handle using the input function in python 2 for getting username for examples Previously this used the builtin input function to get the username. In python 3 this is fine, but if python 2 this is equivalent to eval(raw_input(prompt)) and thus tried to evaluate the username as a variable and typically failed.
Python
mpl-2.0
michaelcho/python-devicecloud,michaelcho/python-devicecloud,digidotcom/python-devicecloud,brucetsao/python-devicecloud,ctrlaltdel/python-devicecloud,digidotcom/python-devicecloud,brucetsao/python-devicecloud,ctrlaltdel/python-devicecloud
4a41b33286cf881f0b3aa09c29a4aaa3568b5259
website/stats/plots/mimp.py
website/stats/plots/mimp.py
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_ty...
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_ty...
Convert numpy int to native int for JSON serialization
Convert numpy int to native int for JSON serialization
Python
lgpl-2.1
reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualis...
d7232d855d406a26b2485b5c1fcd587e90fddf39
tests/test_aio.py
tests/test_aio.py
import pytest from ratelimiter import RateLimiter @pytest.mark.asyncio async def test_alock(): rl = RateLimiter(max_calls=10, period=0.01) assert rl._alock is None async with rl: pass alock = rl._alock assert alock async with rl: pass assert rl._alock is alock
import pytest from ratelimiter import RateLimiter @pytest.mark.asyncio async def test_alock(event_loop): rl = RateLimiter(max_calls=10, period=0.01) assert rl._alock is None async with rl: pass alock = rl._alock assert alock async with rl: pass assert rl._alock is aloc...
Fix Runtime warnings on async tests
Fix Runtime warnings on async tests
Python
apache-2.0
RazerM/ratelimiter
d47d56525f85c5fa8b1f6b817a85479b9eb07582
sqlalchemy_utils/functions/__init__.py
sqlalchemy_utils/functions/__init__.py
from .defer_except import defer_except from .mock import create_mock_engine, mock_engine from .render import render_expression, render_statement from .sort_query import sort_query, QuerySorterException from .database import ( database_exists, create_database, drop_database, escape_like, is_auto_assi...
from .defer_except import defer_except from .mock import create_mock_engine, mock_engine from .render import render_expression, render_statement from .sort_query import sort_query, QuerySorterException from .database import ( database_exists, create_database, drop_database, escape_like, is_auto_assi...
Add query_entities to functions module import
Add query_entities to functions module import
Python
bsd-3-clause
joshfriend/sqlalchemy-utils,joshfriend/sqlalchemy-utils,cheungpat/sqlalchemy-utils,marrybird/sqlalchemy-utils,rmoorman/sqlalchemy-utils,spoqa/sqlalchemy-utils,tonyseek/sqlalchemy-utils,tonyseek/sqlalchemy-utils,JackWink/sqlalchemy-utils,konstantinoskostis/sqlalchemy-utils
244a8ef2d3976970f8647e5fdd3979932cebe6d7
webserver/celery.py
webserver/celery.py
from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webserver.settings') app = Celery('webserver') # Using a string here means the worker will n...
from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webserver.settings') app = Celery('webserver') # Using a string here means the worker will n...
Remove debug task from Celery
Remove debug task from Celery
Python
mit
fengthedroid/heroes-of-the-storm-replay-parser,fengthedroid/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser,karlgluck/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser
13ec50a7e2187edb03174ed4a9dbf8767f4c6ad4
version.py
version.py
major = 0 minor=0 patch=0 branch="dev" timestamp=1376412824.91
major = 0 minor=0 patch=8 branch="master" timestamp=1376412892.53
Tag commit for v0.0.8-master generated by gitmake.py
Tag commit for v0.0.8-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
c18884b10f345a8a094a3c4bf589888027d43bd5
examples/django_app/example_app/urls.py
examples/django_app/example_app/urls.py
from django.conf.urls import include, url from django.contrib import admin from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', include(admin.site.urls), name='admin'), url(r'^api/chatterbot/', ChatterBotAp...
from django.conf.urls import url from django.contrib import admin from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', admin.site.urls, name='admin'), url(r'^api/chatterbot/', ChatterBotApiView.as_view(), n...
Remove url inlude for Django 2.0
Remove url inlude for Django 2.0
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
3243f199fb46d2d6f95ae9afd18b1570f9b5f529
astatsscraper/parsing.py
astatsscraper/parsing.py
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[s...
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[s...
Fix up bad last commit
Fix up bad last commit
Python
mit
SingingTree/AStatsScraper,SingingTree/AStatsScraper
cd41fdbdb53008c9701213d4f223bb8df0514ecb
byceps/util/datetime/timezone.py
byceps/util/datetime/timezone.py
""" byceps.util.datetime.timezone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Timezone helpers :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from flask import current_app import pendulum def local_tz_to_utc(dt: datetime): """Convert date...
""" byceps.util.datetime.timezone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Timezone helpers :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from flask import current_app def get_timezone_string() -> str: """Return the configured default timezone as a string.""" re...
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
61fdbe0dba79dc19cda5320a0ad1352facf12d3d
twine/__init__.py
twine/__init__.py
# Copyright 2018 Donald Stufft and individual contributors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
# Copyright 2018 Donald Stufft and individual contributors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
Rework imports and ignore known mypy issues
Rework imports and ignore known mypy issues
Python
apache-2.0
pypa/twine
1bc4507234d87b1ed246501165fa1d8138bf5ca6
cheddar/exceptions.py
cheddar/exceptions.py
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): self.status_code = status_code
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): super(NotFoundError, self).__init__() self.status_code = status_code
Fix for pypy compatibility: must super's __init__
Fix for pypy compatibility: must super's __init__
Python
apache-2.0
jessemyers/cheddar,jessemyers/cheddar
ac9cd5ff007ee131e97f70c49c763f79f06ebf5a
green/test/test_integration.py
green/test/test_integration.py
import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(s...
import copy import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): ...
Include the entire existing environment for integration tests subprocesses
Include the entire existing environment for integration tests subprocesses
Python
mit
CleanCut/green,CleanCut/green
290a1f7a2c6860ec57bdb74b9c97207e93e611f0
visualize_data.py
visualize_data.py
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') args =...
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') parser....
Add option to visualize data in reverse
Add option to visualize data in reverse
Python
mit
alexlee-gk/visual_dynamics
bf6d6cdaf946af7ce8d1aa6831e7da9b47fef54f
user_deletion/managers.py
user_deletion/managers.py
from dateutil.relativedelta import relativedelta from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_de...
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" user_deletion_config = apps.get_app_config('user_deletion') ...
Put import back on top
Put import back on top
Python
bsd-2-clause
incuna/django-user-deletion
6a767780253ef981e78b00bb9937e9aaa0f9d1b8
motobot/core_plugins/network_handlers.py
motobot/core_plugins/network_handlers.py
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.id...
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.id...
Add sleep after nickserv identify
Add sleep after nickserv identify
Python
mit
Motoko11/MotoBot
c2d3c2c471dfb504626509a34256eb2d9898cfa2
rest_framework_nested/viewsets.py
rest_framework_nested/viewsets.py
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_...
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() serializer_class = self.get_serializer_cla...
Fix to use get_serializer_class method instead of serializer_class
Fix to use get_serializer_class method instead of serializer_class
Python
apache-2.0
alanjds/drf-nested-routers
3b7328dd7d9d235bf32b3cfb836b49e50b70be77
oz/plugins/redis_sessions/__init__.py
oz/plugins/redis_sessions/__init__.py
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(o...
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(o...
Allow for non-ascii characters in password_hash
Allow for non-ascii characters in password_hash
Python
bsd-3-clause
dailymuse/oz,dailymuse/oz,dailymuse/oz
442f21bfde16f72d4480fa7fd9dea2eac741a857
src/analyses/views.py
src/analyses/views.py
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines i...
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines i...
Include analysis detail view URL in message
Include analysis detail view URL in message
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
2bc95d90db15160f9c4869c03f9dadb6cd8d56fa
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
Add another proxy server example string
Add another proxy server example string
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
8fff587b9fd7e2cd0ca4d45e869345cbfb248045
troposphere/workspaces.py
troposphere/workspaces.py
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), ...
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryI...
Add encryption properties to Workspace
Add encryption properties to Workspace
Python
bsd-2-clause
7digital/troposphere,dmm92/troposphere,horacio3/troposphere,ikben/troposphere,alonsodomin/troposphere,pas256/troposphere,cloudtools/troposphere,dmm92/troposphere,ikben/troposphere,Yipit/troposphere,cloudtools/troposphere,johnctitus/troposphere,amosshapira/troposphere,johnctitus/troposphere,pas256/troposphere,alonsodomi...
b4e106271f96b083644b27d313ad80c240fcb0a5
gapipy/resources/booking/booking.py
gapipy/resources/booking/booking.py
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name =...
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class B...
Add agency chain to Booking
Add agency chain to Booking
Python
mit
gadventures/gapipy
0f0e0e91db679f18ad9dc7568047b76e447ac589
stock_inventory_chatter/__openerp__.py
stock_inventory_chatter/__openerp__.py
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '9.0.1.0.0', 'author': "Eficent, " "Odoo Community Assoc...
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2018 initOS GmbH # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '8.0.1.0.0', 'author': "Eficent, " ...
Change of the module version
Change of the module version
Python
agpl-3.0
kmee/stock-logistics-warehouse,acsone/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse
5d33de3868df4549621763db07267ef59fb94eb8
dataset/models/tf/losses/core.py
dataset/models/tf/losses/core.py
""" Contains base tf losses """ import tensorflow as tf def softmax_cross_entropy(labels, logits, *args, **kwargs): """ Multi-class CE which takes plain or one-hot labels Parameters ---------- labels : tf.Tensor logits : tf.Tensor args other positional parameters from `tf.losses.sof...
""" Contains base tf losses """ import tensorflow as tf def softmax_cross_entropy(labels, logits, *args, **kwargs): """ Multi-class CE which takes plain or one-hot labels Parameters ---------- labels : tf.Tensor logits : tf.Tensor args other positional parameters from `tf.losses.sof...
Fix ohe type in ce
Fix ohe type in ce
Python
apache-2.0
analysiscenter/dataset
aef238386c71d52def424c8f47a103bd25f12e26
server/proposal/migrations/0034_fix_updated.py
server/proposal/migrations/0034_fix_updated.py
import django.contrib.gis.db.models.fields from django.db import migrations from django.contrib.gis.db.models import Max def fix_updated(apps, _): Proposal = apps.get_model("proposal", "Proposal") proposals = Proposal.objects.annotate(published=Max("documents__published")) for proposal in proposals: ...
import django.contrib.gis.db.models.fields from django.db import migrations from django.contrib.gis.db.models import Max def fix_updated(apps, _): Proposal = apps.get_model("proposal", "Proposal") proposals = Proposal.objects.annotate(published=Max("documents__published")) for proposal in proposals: ...
Make fix_updated migration (sort of) reversible
Make fix_updated migration (sort of) reversible
Python
mit
cityofsomerville/citydash,cityofsomerville/citydash,codeforboston/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise,codeforboston/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/citydash,cityofsomerville/cornerwise,cityofsomerville/cornerwise,cityofsomerville/cornerwise
6e526a173de970f2cc8f7cd62823a257786e348e
category/urls.py
category/urls.py
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='...
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'), url(r'...
Add the missing category-detail urlconf to not to break bookmarked users
Add the missing category-detail urlconf to not to break bookmarked users
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
077ad3e5227c3ad9831a6c94c14cd640f7e933d9
carusele/models.py
carusele/models.py
from django.db import models class News (models.Model): """ News model represent detail description and content of each carusele element. """ title = models.CharField(max_length=400) description = models.TextField(default="") content = models.TextField() pubdate = models.DateTimeField(...
from django.core.urlresolvers import reverse from django.db import models class News (models.Model): """ News model represent detail description and content of each carusele element. """ title = models.CharField(max_length=400) description = models.TextField(default="") content = models.Te...
Use reverse function for urls in carusele app
Use reverse function for urls in carusele app
Python
apache-2.0
SarFootball/backend,SarFootball/backend,SarFootball/backend
4aba708916984c61cc7f5fd205d66e8f64634589
main/widgets.py
main/widgets.py
from django_filters.widgets import RangeWidget class CustomRangeWidget(RangeWidget): def __init__(self, widget, attrs=None): attrs_start = {'placeholder': 'От', **(attrs or {})} attrs_stop = {'placeholder': 'До', **(attrs or {})} widgets = (widget(attrs_start), widget(attrs_stop)) ...
from django_filters.widgets import RangeWidget class CustomRangeWidget(RangeWidget): def __init__(self, widget, attrs={}): attrs_start = {'placeholder': 'От'} attrs_start.update(attrs) attrs_stop = {'placeholder': 'До'} attrs_stop.update(attrs) super(RangeWidget, self).__in...
Make compatible with python 3.4
Make compatible with python 3.4
Python
agpl-3.0
Davidyuk/witcoin,Davidyuk/witcoin
94d66121368906b52fa8a9f214813b7b798c2b5b
lib/custom_data/settings_manager.py
lib/custom_data/settings_manager.py
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH Filepath for the settings file. """ SETTINGS_PATH = 'settings.xml'
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH (String): The file path for the settings file. SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ SETTINGS_PATH = 'settings.xml' SETTINGS_SCHEMA_PATH = 'set...
Add constant for settings schema file path
Add constant for settings schema file path
Python
unlicense
MarquisLP/Sidewalk-Champion
60ea2738b39b38bdc1f25594a759aace0f520501
web/manage.py
web/manage.py
from flask.ext.script import Manager from app import get_app from create_db import drop_all_tables, create_barebones_data, create_all_data, create_server app = get_app('config.DockerConfiguration') manager = Manager(app) manager.command(drop_all_tables) manager.command(create_barebones_data) manager.command(create_...
from flask.ext.script import Manager from app import get_app from create_db import drop_all_tables, create_barebones_data, create_all_data, create_server app = get_app('config.DockerConfiguration') manager = Manager(app) manager.command(drop_all_tables) manager.command(create_barebones_data) manager.command(create_...
Add utility function to dump flask env
Add utility function to dump flask env
Python
mit
usgo/online-ratings,usgo/online-ratings,usgo/online-ratings,Kashomon/online-ratings,Kashomon/online-ratings,Kashomon/online-ratings
433d9b2c1c29f32a7d5289e84673308c96302d8d
controlers/access.py
controlers/access.py
'''Copyright(C): Leaf Johnson 2011 This file is part of makeclub. makeclub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later versi...
'''Copyright(C): Leaf Johnson 2011 This file is part of makeclub. makeclub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later versi...
FIX a bug, you fuck'in forgot to rename the new function
FIX a bug, you fuck'in forgot to rename the new function
Python
agpl-3.0
cardmaster/makeclub,cardmaster/makeclub,cardmaster/makeclub
addc1e83911f72282eca9603e2c483ba6ef5ef7c
packages/xsp.py
packages/xsp.py
GitHubTarballPackage('mono', 'xsp', '2.11', 'd3e2f80ff59ddff68e757a520655555e2fbf2695', configure = './autogen.sh --prefix="%{prefix}"')
GitHubTarballPackage('mono', 'xsp', '3.0.11', '4587438369691b9b3e8415e1f113aa98b57d1fde', configure = './autogen.sh --prefix="%{prefix}"')
Update to the latest XSP.
Update to the latest XSP.
Python
mit
BansheeMediaPlayer/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild
d8b29fd094a7a2d74c74e32b05a810930655fb47
src/modules/phython.py
src/modules/phython.py
import json import runpy import sys def run(): args = sys.argv if len(args) < 3: raise Exception('Both module name and function name are required.') module, function = args[1:3] module = runpy.run_module(module) if function not in module: raise Exception(function + ' is not defin...
import json import runpy import sys def run(): args = sys.argv if len(args) < 3: raise Exception('Both module name and function name are required.') module, function = args[1:3] module = runpy.run_module(module) if function not in module: raise Exception(function + ' is not defin...
Fix raw_input() error in python 3
Fix raw_input() error in python 3
Python
mit
marella/phython,marella/phython,marella/phython
745c9445e16f72dbc1791abef2b7f52eb5e1f093
open_spiel/python/tests/referee_test.py
open_spiel/python/tests/referee_test.py
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Increase timeouts for the python test.
Increase timeouts for the python test.
Python
apache-2.0
deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel
e912c76ec60abf9a8263e65d8df8d466518f57b2
pysswords/db.py
pysswords/db.py
from glob import glob import os import shutil from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = cr...
from glob import glob import os import shutil from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = cr...
Change GPG password encryption to AES256
Change GPG password encryption to AES256
Python
mit
scorphus/passpie,eiginn/passpie,marcwebbie/passpie,marcwebbie/pysswords,scorphus/passpie,eiginn/passpie,marcwebbie/passpie