Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix missing cmd name in error message
import sys import subprocess from vantage import utils from vantage.exceptions import VantageException def shell_cmd(env, cmd, *args): utils.loquacious(f"Running system defined '{cmd}' inside env", env) utils.loquacious(f" With args: {args}", env) try: cmd = utils.find_executable(cmd) i...
import sys import subprocess from vantage import utils from vantage.exceptions import VantageException def shell_cmd(env, cmd, *args): utils.loquacious(f"Running system defined '{cmd}' inside env", env) utils.loquacious(f" With args: {args}", env) try: cmd_path = utils.find_executable(cmd) ...
Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
Make pep8 happy, remove mixed tabs and spaces
#!/usr/bin/env python import unittest import load import os import mix class parseBPlinesTestCase(unittest.TestCase): def test_overwrite(self): # Test that a later line overwrites a previous line grid = mix.parseBPlines(['@foo@;bar;baz', '@foo@;rag']) self.assertEqual(grid.tokens[0], '@foo@') self.assertEqual...
#!/usr/bin/env python import unittest import load import os import mix class parseBPlinesTestCase(unittest.TestCase): def test_overwrite(self): # Test that a later line overwrites a previous line grid = mix.parseBPlines(['@foo@;bar;baz', '@foo@;rag']) self.assertEqual(grid.tokens[0], '@fo...
Fix log_error so it now catches exceptions
from .. util import class_name, log class LogErrors: """ Wraps a function call to catch and report exceptions. """ def __init__(self, function, max_errors=-1): """ :param function: the function to wrap :param int max_errors: if ``max_errors`` is non-zero, then only the ...
from .. util import class_name, log class LogErrors: """ Wraps a function call to catch and report exceptions. """ def __init__(self, function, max_errors=-1): """ :param function: the function to wrap :param int max_errors: if ``max_errors`` is non-zero, then only the ...
Bump to version with package data fix
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a10', description='', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src...
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a11', description='', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src...
Exclude tests from getting installed
import os import re from setuptools import ( find_packages, setup, ) version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]") def get_version(): base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'curator/__init__.py')) as initf: for line in initf: ...
import os import re from setuptools import ( find_packages, setup, ) version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]") def get_version(): base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'curator/__init__.py')) as initf: for line in initf: ...
Add python_requires to help pip
from setuptools import setup import sys import piexif sys.path.append('./piexif') sys.path.append('./tests') with open("README.rst", "r") as f: description = f.read() setup( name = "piexif", version = piexif.VERSION, author = "hMatoba", author_email = "hiroaki.mtb@outlook.com", description ...
from setuptools import setup import sys import piexif sys.path.append('./piexif') sys.path.append('./tests') with open("README.rst", "r") as f: description = f.read() setup( name = "piexif", version = piexif.VERSION, author = "hMatoba", author_email = "hiroaki.mtb@outlook.com", description ...
Use pandoc to convert README from MD to RST.
#!/usr/bin/env python from setuptools import setup setup( name='djoser', version='0.0.1', packages=['djoser'], license='MIT', author='SUNSCRAPERS', description='REST version of Django authentication system.', author_email='info@sunscrapers.com', long_description=open('README.md').read(...
#!/usr/bin/env python from setuptools import setup try: import pypandoc description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): description = open('README.md').read() setup( name='djoser', version='0.0.1', packages=['djoser'], license='MIT', author='SUNSCRAP...
Remove the version specifier for Henson
from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand import sys class PyTest(TestCommand): def finalize_options(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest ...
from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand import sys class PyTest(TestCommand): def finalize_options(self): super().finalize_options() self.test_args = [] self.test_suite = True def run_tests(self): import pytest ...
Use find_packages to find packages instead of having them somewhere manually
from setuptools import setup setup( name='txkazoo', version='0.0.4', description='Twisted binding for Kazoo', maintainer='Manish Tomar', maintainer_email='manish.tomar@rackspace.com', license='Apache 2.0', py_modules=['txkazoo'], install_requires=['twisted==13.2.0', 'kazoo==2.0b1'] )
from setuptools import find_packages, setup setup( name='txkazoo', version='0.0.4', description='Twisted binding for Kazoo', maintainer='Manish Tomar', maintainer_email='manish.tomar@rackspace.com', license='Apache 2.0', packages=find_packages(), install_requires=['twisted==13.2.0', 'ka...
Add pins so tests pass outside of Travis as well
from setuptools import setup, find_packages setup( name='jmbo-banner', version='0.5', description='Jmbo banner app.', long_description=open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='dev@praekelt.c...
from setuptools import setup, find_packages setup( name='jmbo-banner', version='0.5', description='Jmbo banner app.', long_description=open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='dev@praekelt.c...
Discard docstrings in addition to the -O optimizations.
#!/usr/bin/python -O # -*- coding: utf-8 -*- import sqlite3 from parser import SQLITE3_DB_NAME from random import randint, randrange def main(): """ Ouputs a random clue (with game ID) from 10 random games for manual verification. """ sql = sqlite3.connect(SQLITE3_DB_NAME) # list of random game ids gids = [ra...
#!/usr/bin/python -OO # -*- coding: utf-8 -*- import sqlite3 from parser import SQLITE3_DB_NAME from random import randint, randrange def main(): """ Ouputs a random clue (with game ID) from 10 random games for manual verification. """ sql = sqlite3.connect(SQLITE3_DB_NAME) # list of random game ids gids = [r...
Remove assertion in test that should not have made it in
""" Tests for staticsite.py - the static site generator """ import os.path import pytest from fantail.staticsite import StaticSite def test_init(tmpdir, caplog): # Verify path does not exist path = str(tmpdir.join('test-site')) assert not os.path.isdir(path) # Create the site site = StaticSite(p...
""" Tests for staticsite.py - the static site generator """ import os.path import pytest from fantail.staticsite import StaticSite def test_init(tmpdir, caplog): # Verify path does not exist path = str(tmpdir.join('test-site')) assert not os.path.isdir(path) # Create the site site = StaticSite(p...
Add helpers for obtain indexes to connection manager.
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from threading import local from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import utils class ConnectionManager(object): def __init__(self): self._connections = local() ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from threading import local from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import utils from . import base class ConnectionManager(object): def __init__(self): self._connect...
Add aync notification processing support
from django.http import HttpResponse from .models import Notification def create_notification(request): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>Missing parameter topic', ...
from django.conf import settings from django.http import HttpResponse from .models import Notification def create_notification(request): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>M...
Add extra field to detail output
from flask.ext.restful import fields from meta import BasicResource from config.pins import PinManager MANAGER = PinManager() class Pin(BasicResource): def __init__(self): super(Pin, self).__init__() self.fields = { "num": fields.Integer, "mode": fields.String, ...
from flask.ext.restful import fields from meta import BasicResource from config.pins import PinManager MANAGER = PinManager() class Pin(BasicResource): def __init__(self): super(Pin, self).__init__() self.fields = { "num": fields.Integer, "mode": fields.String, ...
Add option for blank voting
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) attachment = models.ManyToManyField('attachments.Attachment') voted_for = models.PositiveIntegerField() voted_against...
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) attachment = models.ManyToManyField('attachments.Attachment') voted_for = models.PositiveIntegerField(blank=True, null=Tr...
Add GradientDescent with Momentum Optimiser.
import numpy as np class Optimiser: def __init__(self, network): self.nn = network self.step_sign = -1.0 # minimise by default def step(self): self.nn.forward() self.nn.reset_gradients() self.nn.backward() self.update_params() def update_params(se...
import numpy as np class Optimiser: def __init__(self, network): self.nn = network self.step_sign = -1.0 # minimise by default def step(self): self.nn.forward() self.nn.reset_gradients() self.nn.backward() self.update_params() def update_params(se...
Test service with Component instead of Plan db object
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Remove dependancy on vtkVersion Place a try/except around modules that required Numeric
""" VTK.py An VTK module for python that includes: Wrappers for all the VTK classes that are wrappable A Tkinter vtkRenderWidget (works like the tcl vtkTkRenderWidget) The vtkImageViewerWidget and vtkImageWindowWidget are coming soon. Classes to assist in moving data between python and VTK. """ from vtkpython impo...
""" VTK.py An VTK module for python that includes: Wrappers for all the VTK classes that are wrappable A Tkinter vtkRenderWidget (works like the tcl vtkTkRenderWidget) The vtkImageViewerWidget and vtkImageWindowWidget are coming soon. Classes to assist in moving data between python and VTK. """ from vtkpython impo...
Fix is_available method in django; proper exception handling for use checking.
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django ...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django exc...
Make the bot respond to its name
from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessag...
from twisted.plugin import IPlugin from heufybot.moduleinterface import BotModule, IBotModule from zope.interface import implements class CommandHandler(BotModule): implements(IPlugin, IBotModule) name = "CommandHandler" def actions(self): return [ ("message-channel", 1, self.handleChannelMessag...
Add PlaybookFile edit view url
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'...
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, Ansib...
Add expiration value of 5m to the session.
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) d...
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) d...
Fix date parsing having wrong offset
from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str...
from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str...
Use new extension setup() API
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__f...
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__f...
Disable caching for CMS plugin.
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDes...
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDes...
Modify text for management command message
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.al...
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.al...
Add a parametrized sample test. Make xfast faster.
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchm...
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchm...
Change directory where data is written to.
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
Add Admin page for OrganizationMember.
from apps.organizations.models import Organization, OrganizationAddress from django.contrib import admin class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 1 class OrganizationAdmin(admin.ModelAdmin): inlines = (OrganizationAddressAdmin,) admin.site.register(Organ...
from django.contrib import admin from apps.organizations.models import ( Organization, OrganizationAddress, OrganizationMember ) class OrganizationAddressAdmin(admin.StackedInline): model = OrganizationAddress extra = 1 class OrganizationAdmin(admin.ModelAdmin): inlines = (OrganizationAddressAdmin,...
Fix a pydocstyle warning in .travis.yml
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Copyright (c) 2014 CorvisaCloud, LLC # # License: MIT # """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" sy...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Copyright (c) 2014 CorvisaCloud, LLC # # License: MIT # """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syn...
Add failing (on Py 2) test for passwd_check with unicode arguments
from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(has...
# coding: utf-8 from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.asse...
Disable the warning about .env files not being present.
#!/usr/bin/env python import os import sys import dotenv dotenv.read_dotenv() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opencanada.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import warnings import dotenv with warnings.catch_warnings(): warnings.simplefilter("ignore") dotenv.read_dotenv() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opencanada.settings") from django.core.management import execute_f...
Allow data to be returned on the same request.
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers...
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers...
Make MongoInterface more of an interface
import logging from pymongo import MongoClient from pymongo.errors import DuplicateKeyError from pymongo.errors import OperationFailure class MongoInterface: def __init__(self): self._logger = logging.getLogger('spud') self.client = MongoClient() self.db = self.client.spud self._co...
import logging from pymongo import MongoClient, database, collection # from pymongo.errors import DuplicateKeyError # from pymongo.errors import OperationFailure class MongoInterface: def __init__(self): self._logger = logging.getLogger('spud') self.db = database.Database(MongoClient(), 'spud') ...
Change the admin filter to a FieldListFilter
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ class CountryFilter(admin.SimpleListFilter): """ A country filter for Django admin that only returns a list of countries related to the model. """ title = _('Country') parameter_name = 'country' def lookup...
from django.contrib import admin from django.utils.encoding import force_text from django.utils.translation import ugettext as _ class CountryFilter(admin.FieldListFilter): """ A country filter for Django admin that only returns a list of countries related to the model. """ title = _('Country') ...
Upgrade test namespace * Change openerp namespace to odoo in test imports
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase from openerp.exceptions import ValidationError class TestMedicalPrescriptionOrderLine(TransactionCase): def setUp(self): super(TestM...
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase from odoo.exceptions import ValidationError class TestMedicalPrescriptionOrderLine(TransactionCase): def setUp(self): super(TestMedical...
Add FedEx Express shipper class
from .base import Shipper class FedEx(Shipper): barcode_pattern = r'^96\d{20}$' shipper = 'FedEx' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): sequence, check_digit = self.tracking_number[:-1], self.tracking_number[-1] ...
from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): sequence, check_digit = self.tracking_num...
Update ptvsd version number for 2.1 RTM
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 ...
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 ...
Add support for launching Steam games on windows through the Steam protocol
from lib.game_launcher import GameLauncher, GameLauncherException import sys import shlex import subprocess class SteamGameLauncher(GameLauncher): def __init__(self, **kwargs): super().__init__(**kwargs) def launch(self, **kwargs): app_id = kwargs.get("app_id") if app_id is None: ...
from lib.game_launcher import GameLauncher, GameLauncherException import sys import shlex import subprocess import webbrowser class SteamGameLauncher(GameLauncher): def __init__(self, **kwargs): super().__init__(**kwargs) def launch(self, **kwargs): app_id = kwargs.get("app_id") if...
Add pytest-watch to console scripts to match the name.
import os from setuptools import setup, find_packages def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() setup( name='pytest-watch', version='3.1.0', description='Local continuous test runner with pytest and watchdog.', long_description...
import os from setuptools import setup, find_packages def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() setup( name='pytest-watch', version='3.1.0', description='Local continuous test runner with pytest and watchdog.', long_description...
Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation
from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField import pyclamav class RWValidatedFileField(ValidatedFileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_typ...
from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField class RWValidatedFileField(ValidatedFileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_types. Exa...
Modify pypi description to use README.md
from setuptools import setup setup( name="simple_slack_bot", packages=["simple_slack_bot"], # this must be the same as the name above version="1.3.2", description="Simple Slack Bot makes writing your next Slack bot incredibly easy", long_description="Simple Slack Bot makes writing your next Slack ...
from setuptools import setup from os import path # read the contents of your README file this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="simple_slack_bot", packages=["simple_slack_bot"]...
Use GET /me if you want the current user JSON
import logging from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.api import users from django.utils import simplejson from model import get_current_youtify_user from model import YoutifyUser from model import get_youtify_user_by_nick from model import get_current...
import logging from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.api import users from django.utils import simplejson from model import get_current_youtify_user from model import YoutifyUser from model import get_youtify_user_by_nick from model import get_current...
Add argparse, handle data file missing
import sys from core import KDPVGenerator def print_help(): print('Usage: python run.py [data.yml]') def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): if len(sys.argv) < 2: filename = 'data.yml' else: filename = sys.argv[1] ...
import argparse import os from core import KDPVGenerator def generate(filename): generator = KDPVGenerator.from_yml(filename) generator.generate() def main(): parser = argparse.ArgumentParser(description='KDPV Generator') parser.add_argument('filename', nargs='?', default='data.yml', help='data file...
Fix folder structure of created tarballs
import os import tarfile import tempfile def make_tarball(source, tar_basename, extension=".tar.gz", compression="gz"): dest = tempfile.mkdtemp() tar_name = "{}{}".format(tar_basename, extension) tar_path = os.path.join(dest, tar_name) mode = "w:{}".format(compression or "") with tarfile.open(tar...
import os import tarfile import tempfile def make_tarball(source, tar_basename, extension=".tar.gz", compression="gz"): """Create a tarball from a source directory, and store it in a temporary directory. :param str source: The directory (or file... whatever) that we're compressing into a tarball....
Remove logger and fix typos
""" Two User Approval Overrides CloudBolt's standard Order Approval workflow. This Orchestration Action requires two users to approve an order before it is becomes Active. """ from utilities.logger import ThreadLogger logger = ThreadLogger(__name__) def run(order, *args, **kwargs): # Return the order's status ...
""" Two User Approval Overrides CloudBolt's standard Order Approval workflow. This Orchestration Action requires two users to approve an order before it becomes Active. Requires CloudBolt 8.8 """ def run(order, *args, **kwargs): # Return the order's status to "PENDING" if fewer than two users have # approve...
Fix test_deploy_with_operation_executor_override by setting back the version of target_aware_mock plugin to 1.0
from setuptools import setup setup( name='target-aware-mock', version='4.2', packages=['target_aware_mock'], )
from setuptools import setup setup( name='target-aware-mock', version='1.0', packages=['target_aware_mock'], )
Reformat for easier copy and pasting (needed for usability with AWS Console).
from __future__ import print_function from timeit import default_timer as timer import json import datetime print('Loading function') def eratosthenes(n): sieve = [ True for i in range(n+1) ] def markOff(pv): for i in range(pv+pv, n+1, pv): sieve[i] = False markOff(2) f...
from __future__ import print_function from timeit import default_timer as timer import json import datetime print('Loading function') def eratosthenes(n): sieve = [ True for i in range(n+1) ] def markOff(pv): for i in range(pv+pv, n+1, pv): sieve[i] = False markOff(2) f...
Move top-level imports from v0 to v1.
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from ._core import (Broker, BrokerES, Header, ALL, lookup_config, list_configs, describe_configs, temp_config, ...
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, ...
Set config logging in init to debug
import os, logging from flask import Flask from flask.ext.basicauth import BasicAuth from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) # S...
import os, logging from flask import Flask from flask.ext.basicauth import BasicAuth from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) # S...
Fix Import error as a result of answering No to include Login
"""template URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
"""template URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
Throw deprecation warnings for these imports, which will be removed in the next version. They've been deprecated for two years so we can make it happen.
# Here for backwards compatibility (deprecated) from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.Ba...
import warnings from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from d...
Allow QuerySet objects to be reversed
from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): re...
from reobject.utils import signed_attrgetter class QuerySet(list): def __init__(self, *args, **kwargs): super(QuerySet, self).__init__(*args, **kwargs) def count(self): return len(self) def delete(self): for item in self: item.delete() def exists(self): re...
Add instance assertion to table
# -*- coding: utf-8 -*- ############################################################################## # # Author: Dave Lasley <dave@laslabs.com> # Copyright: 2015 LasLabs, Inc [https://laslabs.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
# -*- coding: utf-8 -*- ############################################################################## # # Author: Dave Lasley <dave@laslabs.com> # Copyright: 2015 LasLabs, Inc [https://laslabs.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affe...
Mark get_test_binary as not being a test
import os.path import unittest POSSIBLE_TEST_BINARIES = [ 'libreadline.so.5', 'libreadline.so.6', ] POSSIBLE_TEST_BINARY_PATHS = [ '/lib', '/usr/lib', '/usr/local/lib', ] class TestBase(unittest.TestCase): def get_test_binary(self): """Helper to obtain a test binary for object file te...
import os.path import unittest POSSIBLE_TEST_BINARIES = [ 'libreadline.so.5', 'libreadline.so.6', ] POSSIBLE_TEST_BINARY_PATHS = [ '/lib', '/usr/lib', '/usr/local/lib', ] class TestBase(unittest.TestCase): def get_test_binary(self): """Helper to obtain a test binary for object file te...
Add custom Admin model TaxonomyNode, hide freesound ex
from django.contrib import admin from datasets.models import Dataset, Sound, Annotation, Vote, Taxonomy, DatasetRelease, TaxonomyNode admin.site.register(Dataset) admin.site.register(Sound) admin.site.register(Annotation) admin.site.register(Vote) admin.site.register(Taxonomy) admin.site.register(DatasetRelease) admin...
from django.contrib import admin from datasets.models import Dataset, Sound, Annotation, Vote, Taxonomy, DatasetRelease, TaxonomyNode class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq') admin.site.register(Dataset) admin.site.register(Sound) admin.site.r...
Use from __future__ import for print function
""" logging middleware example """ def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
from __future__ import print_function """ logging middleware example """ def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dis...
Add functionality to print list of parseable files
# -*- coding: utf-8 -*- import os import argparse import fs_utils from pybtex.database.input import bibtex def main(): """ Command-line interface """ parser = argparse.ArgumentParser(description="Manage BibTeX files") parser.add_argument("-t", "--test", action="store_true", help="...
# -*- coding: utf-8 -*- import os import argparse import fs_utils from pybtex.database.input import bibtex def main(): """ Command-line interface """ parser = argparse.ArgumentParser(description="Manage BibTeX files") parser.add_argument("-t", "--test", action="store_true", help="...
Use %APPDATA% for CONFIGURATION_DIR on Windows
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'...
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or os.path.exp...
Break PEP8 and Pydocstring to check Travis
"""Views for the general application.""" from django.views.generic import TemplateView from django.http import HttpResponse class GeneralIndexView(TemplateView): """View for the homepage that renders from a template.""" template_name = 'general/index.html' class GeneralAboutView(TemplateView): """View...
"""Views for the general application.""" from django.views.generic import TemplateView from django.http import HttpResponse class GeneralIndexView(TemplateView): """View for the homepage that renders from a template.""" template_name = 'general/index.html' class GeneralAboutView(TemplateView): """View...
Increase timeout from 400 to 800 seconds.
import unittest, time, sys, os sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): localhost = h2o.decide_if_localhost() if (localhost...
import unittest, time, sys, os sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): localhost = h2o.decide_if_localhost() if (localhost...
Fix test for python 3
# -*- coding: utf-8 -*- import pytest import odin class MultiPartResource(odin.Resource): id = odin.IntegerField() code = odin.StringField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') class TestFields(object): def test_multipartfield__get_value(self): target = MultiPartRe...
# -*- coding: utf-8 -*- import pytest import odin class MultiPartResource(odin.Resource): id = odin.IntegerField() code = odin.StringField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') class TestFields(object): def test_multipartfield__get_value(self): target = MultiPartRe...
Implement ProductDetail with a generic RetrieveUpdateDestroyAPIView class
from django.http import HttpResponse from django.http import Http404 from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .permissions import IsAdminOrReadOnly from .models import Product from .serializers import...
from rest_framework import generics from .permissions import IsAdminOrReadOnly from .models import Product from .serializers import ProductSerializer class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (IsAdminOrReadOnly...
Raise ValueError if n < 1
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n == 1: return Counter() divisor = 2 wh...
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n < 1: raise ValueError if n == 1: ...
Fix error String statement has no effect
# -*- coding: utf-8 -*- from openerp import fields, models, api """ This module create model of Wizard """ class Wizard(models.TransientModel): """" This class create model of Wizard """ _name = 'openacademy.wizard' def _default_sessions(self): return self.env['openacademy.session'].brow...
# -*- coding: utf-8 -*- """ This module create model of Wizard """ from openerp import fields, models, api class Wizard(models.TransientModel): """" This class create model of Wizard """ _name = 'openacademy.wizard' def _default_sessions(self): return self.env['openacademy.session'].bro...
Update regex to match only UUIDs
""" URL configuration for the JASMIN notifications app. """ __author__ = "Matt Pryor" __copyright__ = "Copyright 2015 UK Science and Technology Facilities Council" from django.conf.urls import url, include from . import views app_name = 'jasmin_notifications' urlpatterns = [ url(r'^(?P<uuid>[a-zA-Z0-9-]+)/$', v...
""" URL configuration for the JASMIN notifications app. """ __author__ = "Matt Pryor" __copyright__ = "Copyright 2015 UK Science and Technology Facilities Council" from django.conf.urls import url, include from . import views app_name = 'jasmin_notifications' urlpatterns = [ url( r'^(?P<uuid>[0-9a-f]{8}...
Add domaintools to the import list
from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
Add docstring to recaptcha check
from functools import wraps from django.conf import settings import requests def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recap...
from functools import wraps from django.conf import settings import requests def check_recaptcha(view_func): """Chech that the entered recaptcha data is correct""" @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST':...
Enforce that arguments must implement non-zero methods.
import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__e...
import unittest from mock import MagicMock, Mock from nose.tools import * from gargoyle.inputs.arguments import * class BaseArgument(object): def setUp(self): self.argument = self.klass(self.valid_comparison_value) @property def interface_functions(self): return ['__lt__', '__le__', '__e...
Fix string resolution for filesystem
import angr import logging l = logging.getLogger(name=__name__) class getcwd(angr.SimProcedure): def run(self, buf, size): cwd = self.state.fs.cwd size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1) try: self.state.memory.store(buf, cwd, size=size) self...
import angr import logging l = logging.getLogger(name=__name__) class getcwd(angr.SimProcedure): def run(self, buf, size): cwd = self.state.fs.cwd size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1) try: self.state.memory.store(buf, cwd, size=size) self...
Fix translations for homepage stats
from rest_framework import generics, response from .models import HomePage from .serializers import HomePageSerializer # Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object class HomePageDetail(generics.GenericAPIView): serializer_class = HomePageSerializer de...
from django.utils import translation from rest_framework import generics, response from .models import HomePage from .serializers import HomePageSerializer # Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object class HomePageDetail(generics.GenericAPIView): seriali...
Update the example script to work with python3.
#!/usr/bin/env python import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM30...
#!/usr/bin/env python import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM30...
Check that input to port is an integer
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class ...
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class ...
Integrate listener and irc parts
#!/usr/bin/python import sys import asyncore import logging from irc import Bot logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s") bot = Bot('localhost') try: bot.run() asyncore.loop() except KeyboardInterrupt: bot.irc_command('QUIT', 'Bye :)') sys.exit(0)
#!/usr/bin/python import sys import asyncore import logging from irc import Bot from listener import Listener logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s") bot = Bot('localhost') listener = Listener() def parse(line): if line.startswith('@'): target, line = line[1:].split...
Complete e-mail, Graphite and push notification support
import config def sendMail(): print config.config print "Sent e-mail" def sendToGrapite(): pass
from config import config as conf from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import time import pushnotify def sendMail(recipients, subject, body): if not isinstance( recipients, list ): recipients = [ recipients ] session = smtplib.SMTP( conf.ge...
Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.
# -*- coding: utf-8 -*- import PIL.Image # check for JPEG support. try: PIL.Image._getdecoder("rgb", "jpeg", None) except IOError as e: if str(e).startswith("decoder jpeg not available"): raise Exception( "FATAL: jpeg codec not supported. Install pillow correctly! " " 'sudo apt-...
Add test to reproduce overloaded Tor guard OSSEC alert
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mappi...
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mappi...
Check for json() ValueError with requests when raising an ApiError in check_error()
from requests import Response def check_error(response: Response): """ Takes a requests package response object and checks the error code and raises the proper exception """ response_json = response.json() code = response_json.get('code', None) if response.status_code == 401: raise Per...
from requests import Response from exceptions.internal_exceptions import ApiError def check_error(response: Response): """ Takes a requests package response object and checks the error code and raises the proper exception """ if response.status_code == 401: raise PermissionError('Echosign API...
Update Layer to use ResourceInfo support class
from urllib2 import HTTPError from geoserver.support import atom_link, get_xml from geoserver.style import Style from geoserver.resource import FeatureType, Coverage class Layer: def __init__(self, node): self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ...
from urllib2 import HTTPError from geoserver.support import ResourceInfo, atom_link, get_xml from geoserver.style import Style from geoserver.resource import FeatureType, Coverage class Layer(ResourceInfo): resource_type = "layers" def __init__(self, node): self.name = node.find("name").text self.href = ...
Update SERIAL_DEVICE to match the Raspberry Pi
import serial import time # Define Constants SERIAL_DEVICE = "/dev/tty.usbmodem1421" # Establish Connection ser = serial.Serial(SERIAL_DEVICE, 9600) time.sleep(2) print("Connection Established"); # Send Data to Pi ser.write('h') time.sleep(5); ser.write('l')
import serial import time # Define Constants SERIAL_DEVICE = "/dev/ttyACM0" # Establish Connection ser = serial.Serial(SERIAL_DEVICE, 9600) time.sleep(2) print("Connection Established"); # Send Data to Pi ser.write('h') time.sleep(5); ser.write('l')
Fix path and avi -> mpg.
import unittest class AnimationTestCase(unittest.TestCase): def test_video_unload(self): # fix issue https://github.com/kivy/kivy/issues/2275 # AttributeError: 'NoneType' object has no attribute 'texture' from kivy.uix.video import Video from kivy.clock import Clock from ...
import unittest class AnimationTestCase(unittest.TestCase): def test_video_unload(self): # fix issue https://github.com/kivy/kivy/issues/2275 # AttributeError: 'NoneType' object has no attribute 'texture' from kivy.uix.video import Video from kivy.clock import Clock from ...
Load the external interface on package import
from .ignitiondelayexp import ExperimentalIgnitionDelay from .compare_to_sim import compare_to_sim from .volume_trace import VolumeTraceBuilder from .nonreactive import NonReactiveExperiments __all__ = [ 'ExperimentalIgnitionDelay', 'compare_to_sim', 'VolumeTraceBuilder', 'NonReactiveExperiments', ]
Enforce verify file on the log file and actually setup the log file logger.
''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version cl...
''' CLI entry-point for salt-api ''' # Import python libs import sys import logging # Import salt libs import salt.utils.verify from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api lib...
Fix font test to use unicode font filename for proper loading to allow passing test on windows (and other os's).
#-*- coding: utf-8 -*- import unittest class FontTestCase(unittest.TestCase): def setUp(self): import os self.font_name = os.path.join(os.path.dirname(__file__), 'कीवी.ttf') if not os.path.exists(self.font_name): from zipfile import ZipFile with ZipFile(os.path.joi...
#-*- coding: utf-8 -*- import unittest class FontTestCase(unittest.TestCase): def setUp(self): import os self.font_name = os.path.join(os.path.dirname(__file__), u'कीवी.ttf') if not os.path.exists(self.font_name): from zipfile import ZipFile with ZipFile(os.path.jo...
Fix bugs, add accountstodo method.
import sys import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir,username), password) def save(): aesjsonfile.du...
import sys import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir, self.username), self.password) def save(self): ...
Change view for login url. Add url for index page
"""restaurant URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
"""restaurant URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
Improve testing docstring output for inherited classes
# -*- coding: utf-8 -*- """ test ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ try: import unittest2 as unittest ex...
# -*- coding: utf-8 -*- """ test ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ try: import unittest2 as unittest ex...
Add list of abbreviations for each state
#http://www.gefeg.com/edifact/d03a/s3/codes/cl1h.htm state_names = ['Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jamma and Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Naga...
#http://www.gefeg.com/edifact/d03a/s3/codes/cl1h.htm #This is a terrible method, but it works for now state_names = ['Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jamma and Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Mahar...
Add new author Bumping commit and mention additional contributor to Shavar
import os from setuptools import setup, find_packages from shavar import __version__ here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() with open(os.path.join(here, 'requireme...
import os from setuptools import setup, find_packages from shavar import __version__ here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() with open(os.path.join(here, 'requireme...
Remove tests from built package
from setuptools import setup, find_packages long_description = '''\ pyimagediet is a Python wrapper around image optimisations tools used to reduce images size without loss of visual quality. It provides a uniform interface to tools, easy configuration and integration. It works on images in JPEG, GIF and PNG formats ...
from setuptools import setup, find_packages long_description = '''\ pyimagediet is a Python wrapper around image optimisations tools used to reduce images size without loss of visual quality. It provides a uniform interface to tools, easy configuration and integration. It works on images in JPEG, GIF and PNG formats ...
Update the sequence alignment example.
from alignment.sequence import Sequence from alignment.vocabulary import Vocabulary from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner # Create sequences to be aligned. a = Sequence("what a beautiful day".split()) b = Sequence("what a disappointingly bad day".split()) print "Sequence A:", a pr...
from alignment.sequence import Sequence from alignment.vocabulary import Vocabulary from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner # Create sequences to be aligned. a = Sequence('what a beautiful day'.split()) b = Sequence('what a disappointingly bad day'.split()) print 'Sequence A:', a pr...
Fix the imports in the tests of dropbox
import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.libDropbox import LibDropbox class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create()...
import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.dropboxDriver import dropboxDriver class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.cr...
Remove "less-than" restrictions on Astropy, LXML.
#!/usr/bin/env python from setuptools import find_packages, setup import versioneer install_requires = [ "astropy>=1.2, <3", "lxml>=2.3, <4.0", 'iso8601', 'orderedmultidict', 'pytz', 'six', ] test_requires = [ 'pytest>3', 'coverage' ] extras_require = { 'test': test_requires, ...
#!/usr/bin/env python from setuptools import find_packages, setup import versioneer install_requires = [ "astropy>=1.2", "lxml>=2.3", 'iso8601', 'orderedmultidict', 'pytz', 'six', ] test_requires = [ 'pytest>3', 'coverage' ] extras_require = { 'test': test_requires, 'all': te...
Add peewee dependency for simpledb.
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').r...
from setuptools import setup, find_packages setup( name='weaveserver', version='0.8', author='Srivatsan Iyer', author_email='supersaiyanmode.rox@gmail.com', packages=find_packages(), license='MIT', description='Library to interact with Weave Server', long_description=open('README.md').r...
Fix version printing of tags and releases
import github import github_token import repositories import tagsparser import flock def main(): g = github.Github(github_token.GITHUB_TOKEN) for repo in repositories.REPOSITORIES: tags, releases = g.get_tags_and_releases(repo["owner"], repo["name"], repositories.COUNT) print "Got", tags, rele...
import github import github_token import repositories import tagsparser import flock def main(): g = github.Github(github_token.GITHUB_TOKEN) for repo in repositories.REPOSITORIES: tags, releases = g.get_tags_and_releases(repo["owner"], repo["name"], repositories.COUNT) print "Got", [t.version...
Add shoot to random AI
import random # define possible actions go_north = 'go north' go_south = 'go south' go_east = 'go east' go_west = 'go west' rotate_cw = 'rotate cw' rotate_ccw = 'rotate ccw' wait = 'wait' def make_move(state): """ Given a game state, decide on a move. """ print('AI making move for state: {}'.format(state)...
import random # Move definitions go_north = 'go north' go_south = 'go south' go_east = 'go east' go_west = 'go west' rotate_cw = 'rotate cw' rotate_ccw = 'rotate ccw' wait = 'wait' shoot = 'shoot' def make_move(state): """ Given a game state, decide on a move. """ # TODO: Implement AI! return random.choic...
Replace all occurences of Nomad with Cyborg
# -*- coding: utf-8 -*- # 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, softw...
# -*- coding: utf-8 -*- # 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, softw...
Send CSP reports right to apophis.
# -*- coding: utf-8 -*- import falcon, util, json, sys, traceback # Content-security policy reports of frontend # Every CSP report is forwarded to ksi-admin@fi.muni.cz. # This is testing solution, if a lot of spam occurs, some intelligence should # be added to this endpoint. class CSP(object): def on_post(self,...
# -*- coding: utf-8 -*- import falcon, util, json, sys, traceback # Content-security policy reports of frontend # Every CSP report is forwarded to ksi-admin@fi.muni.cz. # This is testing solution, if a lot of spam occurs, some intelligence should # be added to this endpoint. class CSP(object): def on_post(self,...