Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix tests to allow use of random, but not change each time
import simplecoin import unittest import datetime import simplecoin.models as m from decimal import Decimal from simplecoin import db class UnitTest(unittest.TestCase): """ Represents a set of tests that only need the database iniailized, but no fixture data """ def setUp(self, **kwargs): extra ...
import simplecoin import unittest import datetime import random import simplecoin.models as m from decimal import Decimal from simplecoin import db class UnitTest(unittest.TestCase): """ Represents a set of tests that only need the database iniailized, but no fixture data """ def setUp(self, **kwargs): ...
Check the number of items a little bit later
from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clon...
from perfrunner.helpers.cbmonitor import with_stats from perfrunner.helpers.local import clone_ycsb from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task from perfrunner.tests import PerfTest from perfrunner.tests.n1ql import N1QLTest class YCSBTest(PerfTest): def download_ycsb(self): clon...
Make the console app work with the new user model.
from django.shortcuts import render_to_response from account.auth import * ''' @author: Anant Bhardwaj @date: Mar 21, 2013 Datahub Console ''' @dh_login_required def index(request): return render_to_response("console.html", { 'login': get_login(request)})
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required ''' @author: Anant Bhardwaj @date: Mar 21, 2013 Datahub Console ''' @login_required def index(request): return render_to_response("console.html", { 'login': request.user.username})
Read commandline args as isbns
#!/usr/bin/env python import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ...
#!/usr/bin/env python import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_ke...
Remove PCF 1.12 from CI.
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1_12', '2_0', '2_1', '2_2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = T...
#!/usr/bin/env python import os from jinja2 import Template clusters = ['2_0', '2_1', '2_2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(...
Update the output file name
# -*- coding:utf-8 -*- import os import subprocess import sys source = sys.argv[1] TYPES = ('.jpeg', '.png', '.jpg') def convert_a_img(img_file): filename = os.path.split(img_file)[1] url_out = os.path.join(source, '-'+filename) subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out]) #####...
# -*- coding:utf-8 -*- import os import subprocess import sys source = sys.argv[1] TYPES = ('.jpeg', '.png', '.jpg') def convert_a_img(img_file): file = os.path.split(img_file)[1] filename = os.path.splitext(file)[0] suffix = os.path.splitext(file)[1] url_out = os.path.join(source, filename + '_mini' + suffi...
Use lru_cache instead of a dict cache in FunctionDispatch
import attr @attr.s(slots=True) class FunctionDispatch(object): """ FunctionDispatch is similar to functools.singledispatch, but instead dispatches based on functions that take the type of the first argument in the method, and return True or False. objects that help determine dispatch should be i...
from ._compat import lru_cache class FunctionDispatch(object): """ FunctionDispatch is similar to functools.singledispatch, but instead dispatches based on functions that take the type of the first argument in the method, and return True or False. objects that help determine dispatch should be in...
Fix error when displaying other types of surveys
from django import template from wagtail_personalisation.adapters import get_segment_adapter register = template.Library() @register.simple_tag def filter_surveys_by_segments(surveys, request): """Filter out surveys not in user's segments.""" user_segments = get_segment_adapter(request).get_segments() us...
from django import template from wagtail_personalisation.adapters import get_segment_adapter register = template.Library() @register.simple_tag def filter_surveys_by_segments(surveys, request): """Filter out surveys not in user's segments.""" user_segments = get_segment_adapter(request).get_segments() us...
Add constraint from name method
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': Differen...
Write name of last page in txt file
import os def make_chapter_files(): os.chdir('../static/images') for _, dirs, files in os.walk(os.getcwd()): dirs = [d for d in dirs if not d[0] == '.'] files = [f for f in files if not f[0] == '.'] for directory in dirs: file_path = get_filepath(directory) m...
import os def make_chapter_files(): os.chdir('../static/images') for _, dirs, files in os.walk(os.getcwd()): dirs = [d for d in dirs if not d[0] == '.'] files = [f for f in files if not f[0] == '.'] for directory in dirs: file_path = get_filepath(directory) m...
Add a class for representing the current version
"""This module contains all of the important meta-information for Hypatia such as the author's name, the copyright and license, status, and so on. """ __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author...
"""This module contains all of the important meta-information for Hypatia such as the author's name, the copyright and license, status, and so on. """ __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author...
Use assertIn in tests for better error message.
# -*- encoding: utf-8 -*- # ! python2 from __future__ import (absolute_import, division, print_function, unicode_literals) import os import tempfile from django.test import TestCase from ..tests.mailers import TestMailer class BasicUsageTestCase(TestCase): def test_message_will_be_sent_with_inlined_css(self):...
# -*- encoding: utf-8 -*- # ! python2 from __future__ import (absolute_import, division, print_function, unicode_literals) import os import tempfile from django.test import TestCase from ..tests.mailers import TestMailer class BasicUsageTestCase(TestCase): def test_message_will_be_sent_with_inlined_css(self):...
Use UTC timestamp as timestamp
from time import time def dynamic_import(path): module, builder = path.rsplit(".", 1) return getattr(__import__(module, fromlist=[builder]), builder) def current_ts(): """ Just gives current timestamp. """ return int(time() * 1000)
from datetime import datetime def dynamic_import(path): module, builder = path.rsplit(".", 1) return getattr(__import__(module, fromlist=[builder]), builder) def current_ts(): """ Just gives current timestamp. """ utcnow = datetime.utcnow() return int(utcnow.timestamp() * 1000)
Remove checks for deprecated keys in outcomes
def assert_outcomes(result, **expected): outcomes = result.parseoutcomes() for key in 'seconds', 'pytest-warnings', 'warnings', 'warning': if key in outcomes: del outcomes[key] assert outcomes == expected
def assert_outcomes(result, **expected): outcomes = result.parseoutcomes() for key in 'seconds', 'warnings': if key in outcomes: del outcomes[key] assert outcomes == expected
Throw 500 error on SQLAlchemy integrity error
import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.ab...
import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date....
Fix wagtail module paths in news
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): ret...
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get...
Add multithreading with threading module, run until the end
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespace...
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs...
Make linestyles2 test runnable (should probably fix this for other tests)
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName...
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName...
Fix random seed in unit tests
import unittest class TestCase(unittest.TestCase): pass
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_se...
Update tests for new l10n behavior
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0...
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb...
Use session instead of cookie for tracking visitor UUID
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMi...
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMi...
Improve end-user labels, values, help text.
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.err...
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.err...
Fix spreadsheets page set for RecreateSKPs bot
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state clas...
Add : entry tidy to keep relevant info.
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if...
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if...
Fix if no paragraph is in page
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filenam...
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filenam...
Make sure we always have a string to work with
# coding=utf-8 import logging import subprocess from subprocess import Popen, PIPE class GitCmdException(Exception): def __init__(self, stdout, stderr, message): self.stdout = stdout self.stderr = stderr self.message = message class RebaseAndTagException(GitCmdException): def __init_...
# coding=utf-8 import logging import subprocess from subprocess import Popen, PIPE class GitCmdException(Exception): def __init__(self, stdout, stderr, message): self.stdout = stdout self.stderr = stderr self.message = message class RebaseAndTagException(GitCmdException): def __init_...
Replace spaces with tabs, quit on <Ctrl+C>
import sys import zmq import time def main(): port = 5000 if len(sys.argv) > 1: port = sys.argv[1] int(port) bind_addr = "tcp://localhost:%s" % port context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(bind_addr) socket.setsockopt(zmq.SUBSCRIBE,'') print "Listening for events ...
import sys import zmq import time def main(): port = 5000 if len(sys.argv) > 1: port = sys.argv[1] int(port) bind_addr = "tcp://localhost:%s" % port context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(bind_addr) socket.setsockopt(zmq.SUBSCRIBE,'') ...
Add argparse as a requirement if not built in
""" Setup file """ import os from setuptools import setup, find_packages from version_helper import git_version HERE = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(HERE, 'README.rst')).read() CHANGES = open(os.path.join(HERE, 'CHANGES.txt')).read() REQUIREMENTS = [ 'mock', ] if __name_...
""" Setup file """ import os from setuptools import setup, find_packages from version_helper import git_version HERE = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(HERE, 'README.rst')).read() CHANGES = open(os.path.join(HERE, 'CHANGES.txt')).read() REQUIREMENTS = [ 'mock', ] # Python 2...
Add -f to fetch since the goal is to sync down, so we don't care about ff.
#!/usr/bin/env python """ Grab all of a user's projects from github. Copyright (c) 2008 Dustin Sallings <dustin@spy.net> """ import os import sys import subprocess import github def sync(path, user, repo): p=os.path.join(path, repo.name) + ".git" print "Syncing %s -> %s" % (repo, p) if os.path.exists(p...
#!/usr/bin/env python """ Grab all of a user's projects from github. Copyright (c) 2008 Dustin Sallings <dustin@spy.net> """ import os import sys import subprocess import github def sync(path, user, repo): p=os.path.join(path, repo.name) + ".git" print "Syncing %s -> %s" % (repo, p) if os.path.exists(p...
Print player emails in migration script.
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:gam...
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:gam...
Use format for string formatting
from django.conf import settings import factory from factory.fuzzy import FuzzyText from ..models import Book, BookSpecimen class BookFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test book %03d" % n) summary = "This is a test summary" section = 1 lang = settings.LA...
from django.conf import settings import factory from factory.fuzzy import FuzzyText from ..models import Book, BookSpecimen class BookFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test book {0}".format(n)) summary = "This is a test summary" section = 1 lang = settin...
Handle failing to publish to pulse
""" This module is currently an experiment in publishing messages to pulse. It might become a real pulse publisher one day. """ import os import sys from pulse_actions.authentication import (get_user_and_password, AuthenticationError) from mozillapulse.publishers import GenericPublisher from mozillapulse.config ...
""" This module is currently an experiment in publishing messages to pulse. It might become a real pulse publisher one day. """ import os import sys from pulse_actions.authentication import ( get_user_and_password, AuthenticationError ) from mozillapulse.publishers import GenericPublisher from mozillapulse.c...
Mark feedback comments starting with a html tag as spammy
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks message and link ...
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm import re @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks messa...
Fix api mobile only with geotrek flatpages trekking tourism
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import url, include from rest_framework import routers from geotrek.api.mobile import views as api_mobile router = routers.DefaultRouter() if 'geotrek.flatpages' in settings.INSTALLED_APPS: router.register(r'flatpages'...
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import url, include from rest_framework import routers if 'geotrek.flatpages' and 'geotrek.trekking' and 'geotrek.tourism': from geotrek.api.mobile import views as api_mobile router = routers.DefaultRouter() ur...
Update context processer to check for custom hybrid user agent.
# Determins if the requesting device is a native hybrid app (android/ios) def is_hybrid(request): return { 'is_hybrid': 'HTTP_MYUW_HYBRID' in request.META }
# Determins if the requesting device is a native hybrid app (android/ios) def is_hybrid(request): return { 'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT'] }
Update uptest for Python 3
#!/usr/bin/env python import urllib2 import argparse import portend parser = argparse.ArgumentParser() parser.add_argument('host') parser.add_argument('port', type=int) args = parser.parse_args() portend.occupied(args.host, args.port, timeout=3) root = 'http://{host}:{port}/'.format(**vars(args)) urllib2.urlopen(ro...
#!/usr/bin/env python3 import urllib.request import argparse import portend parser = argparse.ArgumentParser() parser.add_argument('host') parser.add_argument('port', type=int) args = parser.parse_args() portend.occupied(args.host, args.port, timeout=3) root = 'http://{host}:{port}/'.format(**vars(args)) urllib.req...
Return correct language for using within links
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE return { "PORTAL" : lfc.utils.get_portal(), ...
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE is_default_language = default_language == current_la...
Fix debug flag to actually work
__author__ = 'nhumrich' import os import socket syslog_host = os.getenv('SYSLOG_HOST', 'localhost') syslog_port = os.getenv('SYSLOG_PORT', 514) debug = os.getenv('DEBUG', 'False') def send(log): if isinstance(log, str): log = log.encode('utf-8') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)...
__author__ = 'nhumrich' import os import socket syslog_host = os.getenv('SYSLOG_HOST', 'localhost') syslog_port = os.getenv('SYSLOG_PORT', 514) debug = os.getenv('DEBUG', 'False') def send(log): if isinstance(log, str): log = log.encode('utf-8') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)...
Make backup failures not disruptive
''' Backup es index to S3 and refresh ''' from tornado.ioloop import IOLoop from web.api.es import ESQuery async def backup_and_refresh(): ''' Run periodically in the main event loop ''' def sync_func(): esq = ESQuery() esq.backup_all(aws_s3_bucket='smartapi') ...
''' Backup es index to S3 and refresh ''' import logging from tornado.ioloop import IOLoop from web.api.es import ESQuery async def backup_and_refresh(): ''' Run periodically in the main event loop ''' def sync_func(): esq = ESQuery() try: esq.backup_al...
Refactor S3 interactions for reusability
from IPython.display import Image import boto def s3img(uri): if uri.startswith('s3://'): uri = uri[5:] bucket_name, key_name = uri.split('/', 1) conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) key = bucket.get_key(key_name) data = key.get_contents_as_string() ret...
from IPython.display import Image import boto def parse_s3_uri(uri): if uri.startswith('s3://'): uri = uri[5:] return uri.split('/', 1) def get_s3_key(uri): bucket_name, key_name = parse_s3_uri(uri) conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) return bucket.get_k...
Fix version string so that we can install with pip/setuptools
"""Schemas for structured data.""" from flatland.exc import AdaptationError from flatland.schema import Array, Boolean, Compound, Constrained, Container,\ Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\ Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\ Pr...
"""Schemas for structured data.""" from flatland.exc import AdaptationError from flatland.schema import Array, Boolean, Compound, Constrained, Container,\ Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\ Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\ Pr...
Simplify and improve -v/-q handling.
"""Alternate way of running the unittests, for Python 2.5 or Windows.""" __author__ = 'Beech Horn' import sys import unittest def suite(): mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread'] test_mods = ['%s_test' % name for name in mods] ndb = __import__('ndb', fromlist=test_mods, ...
"""Alternate way of running the unittests, for Python 2.5 or Windows.""" __author__ = 'Beech Horn' import sys import unittest def suite(): mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread'] test_mods = ['%s_test' % name for name in mods] ndb = __import__('ndb', fromlist=test_mods, ...
Remove non-standard attribute in test user.
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@e...
""" A static dictionary with SAML testusers that can be used as response. """ USERS = { "testuser1": { "sn": ["Testsson 1"], "givenName": ["Test 1"], "eduPersonAffiliation": ["student"], "eduPersonScopedAffiliation": ["student@example.com"], "eduPersonPrincipalName": ["test@e...
Split up tests and fixed misspelling.
# -*- coding: utf-8 -*- import pytest import os import todolist import tempfile import manage @pytest.fixture def client(request): db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp() todolist.app.config['TESTING'] = True client = todolist.app.test_client() with todolist.app.app_context(): ...
# -*- coding: utf-8 -*- import pytest import os import todolist import tempfile import manage @pytest.fixture def client(request): db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp() todolist.app.config['TESTING'] = True client = todolist.app.test_client() with todolist.app.app_context(): ...
Set default property screen 256 colors.
# -*- coding: utf-8 -*- import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.run() def quit_app(): raise urwid.ExitMainLoop()
# -*- coding: utf-8 -*- import urwid def run_tag(tag, *args, **kwargs): loop = urwid.MainLoop(tag, *args, **kwargs) loop.screen.set_terminal_properties(colors=256) loop.run() def quit_app(): raise urwid.ExitMainLoop()
Update Neural Entity (now complete)
from Entity import * class NeuralEntity(Entity): """Entity the represents timestamps of action potentials, i.e. spike times. Cutouts of the waveforms corresponding to spike data in a neural entity might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`). """ def __init__(s...
from Entity import * class NeuralEntity(Entity): """Entity the represents timestamps of action potentials, i.e. spike times. Cutouts of the waveforms corresponding to spike data in a neural entity might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`). """ def __init__(s...
Test if default rotor encodes backwards properly
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def run_tests(): runner = unittest.Text...
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): ...
Make sure .git test directory is removed on Windows
import os import shutil import tempfile import builtins import subprocess import pytest from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() ...
import os import shutil import tempfile import builtins import subprocess import pytest import sys from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.g...
Use normal function instead of lambda for this
import asyncio from pytest import mark, raises from oshino.run import main from mock import patch def create_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop @mark.integration @patch("oshino.core.heart.forever", lambda: False) @patch("oshino.core.heart.create_loop", crea...
import asyncio from pytest import mark, raises from oshino.run import main from mock import patch def create_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop def error_stub(): raise RuntimeError("Simply failing") @mark.integration @patch("oshino.core.heart.forever",...
Add 'reverse' argument to get_enum_as_dict.
# Copyright 2013 Rackspace # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the...
# Copyright 2013 Rackspace # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the...
Return fake behaviour data with /getBehaviourEvent/current
import sys sys.path.append(".env/lib/python2.7/site-packages") from flask import Flask import requests app = Flask(__name__) @app.route("/") def hello(): payload = { 'access_token': '08beec989bccb333439ee3588583f19f02dd6b7e', 'asset': '357322040163096', 'filter': 'BEHAVE_ID' } r = ...
import sys sys.path.append(".env/lib/python2.7/site-packages") from flask import Flask import requests import json import random app = Flask(__name__) FAKE_DATA = True HARD_BRAKING = 10 HARD_ACCELERATION = 11 payload = { 'access_token': '08beec989bccb333439ee3588583f19f02dd6b7e', 'asset': '357322040163096',...
Correct it to actually follow the README...
def saddle_points(m): mt = transpose(m) if not m == transpose(mt): raise ValueError return set((i, j) for i, row in enumerate(m) for j, col in enumerate(mt) if (row[j] == min(row) and col[i] == max(col)) or (row[j] == max(row) and col[i] == min(col))) def transpose(...
def saddle_points(m): mt = transpose(m) if not m == transpose(mt): raise ValueError return set((i, j) for i, row in enumerate(m) for j, col in enumerate(mt) if (row[j] == max(row) and col[i] == min(col))) def transpose(m): return [list(col) for col in zip(*m)]
Add license to the packaging
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fabtools', version='0.1', description='Tools for writing awesome Fabric files', author='Ronan Amicel', a...
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fabtools', version='0.1', description='Tools for writing awesome Fabric files', author='Ronan Amicel', a...
Bump minor version to account for changes of MANIFEST
from setuptools import setup setup(name = 'graphysio', version = '0.4', description = 'Graphical visualization of physiologic time series', url = 'https://github.com/jaj42/graphysio', author = 'Jona JOACHIM', author_email = 'jona@joachim.cc', license = 'ISC', install_requires ...
from setuptools import setup setup(name = 'graphysio', version = '0.41', description = 'Graphical visualization of physiologic time series', url = 'https://github.com/jaj42/graphysio', author = 'Jona JOACHIM', author_email = 'jona@joachim.cc', license = 'ISC', install_requires...
Set development status to stable
from setuptools import setup, find_packages setup( name='sorl-thumbnail', use_scm_version=True, description='Thumbnails for Django', long_description=open('README.rst').read(), author="Mikko Hellsing", author_email='mikko@aino.se', maintainer="Jazzband", maintainer_email="roadies@jazzba...
from setuptools import setup, find_packages setup( name='sorl-thumbnail', use_scm_version=True, description='Thumbnails for Django', long_description=open('README.rst').read(), author="Mikko Hellsing", author_email='mikko@aino.se', maintainer="Jazzband", maintainer_email="roadies@jazzba...
Use new invocations error counter for testing thread sleeps etc
from invocations.docs import docs, www, sites, watch_docs from invocations.testing import test, integration, coverage, watch_tests from invocations import packaging from invoke import Collection from invoke.util import LOG_FORMAT ns = Collection( docs, www, test, coverage, integration, sites, watch_docs, wat...
from invocations.docs import docs, www, sites, watch_docs from invocations.testing import test, integration, coverage, watch_tests, count_errors from invocations import packaging from invoke import Collection from invoke.util import LOG_FORMAT ns = Collection( docs, www, test, coverage, integration, sites, watch...
Fix various documentation related warnings.
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from .dataset import * from . import dataset from .vonkries import ( chromatic_adaptation_matrix_VonKries, chromatic_adaptation_VonKries) from .fairchild1990 import chromatic_adaptation_Fairchild1990 from .cmccat2000 import (...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from .dataset import * from . import dataset from .vonkries import ( chromatic_adaptation_matrix_VonKries, chromatic_adaptation_VonKries) from .fairchild1990 import chromatic_adaptation_Fairchild1990 from .cmccat2000 import (...
Use json decorator where appropriate
from django.http import HttpResponse from django.core.cache import cache from mixcloud.utils.decorators import staff_only from mixcloud.speedbar.utils import DETAILS_PREFIX, TRACE_PREFIX from gargoyle.decorators import switch_is_active import json @staff_only @switch_is_active('speedbar:panel') def panel(request, tra...
from django.http import HttpResponse from django.core.cache import cache from mixcloud.utils.decorators import staff_only from mixcloud.speedbar.utils import DETAILS_PREFIX, TRACE_PREFIX from mixcloud.utils.decorators import json_response from gargoyle.decorators import switch_is_active import json @staff_only @switc...
Switch to Double DQN as the default algorithm.
"""Configuration data for training or evaluating a reinforcement learning agent. """ import agents def get_config(): config = { 'game': 'BreakoutDeterministic-v3', 'agent_type': agents.DeepQLearner, 'history_length': 4, 'training_steps': 50000000, 'training_freq': 4, ...
"""Configuration data for training or evaluating a reinforcement learning agent. """ import agents def get_config(): config = { 'game': 'BreakoutDeterministic-v3', 'agent_type': agents.DoubleDeepQLearner, 'history_length': 4, 'training_steps': 50000000, 'training_freq': 4, ...
Revert "Commented out unimplemented imports"
import fft import gmode_utils import cluster import proc_utils import decomposition def no_impl(*args,**kwargs): raise NotImplementedError("You need to install Multiprocess package (pip,github) to do a parallel Computation.\n" "Switching to the serial version. ") # from .feature_extr...
import fft import gmode_utils import cluster import proc_utils import decomposition def no_impl(*args,**kwargs): raise NotImplementedError("You need to install Multiprocess package (pip,github) to do a parallel Computation.\n" "Switching to the serial version. ") from .feature_extrac...
Fix line lenght in manifest
# coding: utf-8 # @ 2016 florian DA COSTA @ Akretion # © 2016 @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'External File Location', 'version': '10.0.1.0.0', 'author': 'Akretion,Odoo Community Association ...
# coding: utf-8 # @ 2016 florian DA COSTA @ Akretion # © 2016 @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'External File Location', 'version': '10.0.1.0.0', 'author': 'Akretion,Odoo Community Association ...
Undo my 'work-around' for flask-heroku.
#! /usr/bin/env python # -*- coding: utf-8 -*- """Primary setup for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division import os from flask import Flask from flask_heroku import Heroku from flask.ext.sqlalch...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Primary setup for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from flask import Flask from flask_heroku import Heroku from flask.ext.sqlalchemy import S...
Change variable name to correct sanitized input variable
from flask import Flask, request import mongoengine as me from mongoengine.connection import get_db, connect from mongosanitizer.sanitizer import sanitize import json app = Flask(__name__) class Movie(me.Document): title = me.StringField(required=True) Movie(title='test').save() @app.route("/connect_find") d...
from flask import Flask, request import mongoengine as me from mongoengine.connection import get_db, connect from mongosanitizer.sanitizer import sanitize import json app = Flask(__name__) class Movie(me.Document): title = me.StringField(required=True) Movie(title='test').save() @app.route("/connect_find") d...
Fix bad usage of a dict
from sugar.p2p.model.RemoteModel import RemoteModel from sugar.p2p.model.LocalModel import LocalModel class Store: def __init__(self, group): self._group = group self._local_models = {} def create_model(self, model_id): model = LocalModel(self._group, model_id) self._local_models[model_id] = model return...
from sugar.p2p.model.RemoteModel import RemoteModel from sugar.p2p.model.LocalModel import LocalModel class Store: def __init__(self, group): self._group = group self._local_models = {} def create_model(self, model_id): model = LocalModel(self._group, model_id) self._local_models[model_id] = model return...
Fix typo, author email, and package url
from setuptools import setup, find_packages setup( name='flask-ldap-login', version='0.1', author='Continuum Analitics', author_email='srossross@gmail.com', url='https://github.com/srossross/flask-ldap-login', packages=find_packages(), include_package_data=True, zip_safe=False, e...
from setuptools import setup, find_packages setup( name='flask-ldap-login', version='0.1', author='Continuum Analytics', author_email='dev@continuum.io', url='https://github.com/ContinuumIO/flask-ldap-login', packages=find_packages(), include_package_data=True, zip_safe=False, en...
Add project URL to the distribution info
import codecs import os from setuptools import setup, find_packages def read(filename): filepath = os.path.join(os.path.dirname(__file__), filename) return codecs.open(filepath, encoding='utf-8').read() setup( name='lemon-robots', version='0.1.dev', license='BSD', description='robots.txt sim...
import codecs import os from setuptools import setup, find_packages def read(filename): filepath = os.path.join(os.path.dirname(__file__), filename) return codecs.open(filepath, encoding='utf-8').read() setup( name='lemon-robots', version='0.1.dev', license='BSD', description='robots.txt sim...
Fix PyPI README.MD showing problem.
from os.path import abspath, dirname, join, normpath from setuptools import setup setup( # Basic package information: name='django-heroku-memcacheify', version='1.0.0', py_modules=('memcacheify',), # Packaging options: zip_safe=False, include_package_data=True, # Package dependenci...
from os.path import abspath, dirname, join, normpath from setuptools import setup setup( # Basic package information: name='django-heroku-memcacheify', version='1.0.0', py_modules=('memcacheify',), # Packaging options: zip_safe=False, include_package_data=True, # Package dependenci...
Simplify the definision of install_requires
#!/usr/bin/env python from setuptools import setup, find_packages install_requires = [] with open("requirements.txt") as fp: for s in fp: install_requires.append(s.strip()) setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, I...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="luigi-td", version='0.0.0', description="Luigi integration for Treasure Data", author="Treasure Data, Inc.", author_email="support@treasure-data.com", url="http://treasuredata.com/", install_requires=open("requi...
Change project name to avoid pypi conflict
#!/usr/bin/env python from __future__ import with_statement import sys from setuptools import setup, find_packages long_description = """ Pypimirror - A Pypi mirror script that uses threading and requests """ install_requires = [ 'beautifulsoup4==4.4.1', 'requests==2.9.1', ] setup( name='pypimirror', ...
#!/usr/bin/env python from __future__ import with_statement import sys from setuptools import setup, find_packages long_description = """ Pypimirror - A Pypi mirror script that uses threading and requests """ install_requires = [ 'beautifulsoup4==4.4.1', 'requests==2.9.1', ] setup( name='pypimirror-si...
Fix return statement for `invite`
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id ...
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id ...
Add redirect from site base url to admin index for now
"""winthrop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/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-b...
"""winthrop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ # for no...
Clean up the erepl code a little bit.
# Use with # py -i etiquette_easy.py import etiquette import os import sys P = etiquette.photodb.PhotoDB() import traceback def easytagger(): while True: i = input('> ') if i.startswith('?'): i = i.split('?')[1] or None try: etiquette.tag_export.stdout([P.g...
# Use with # py -i etiquette_easy.py import argparse import os import sys import traceback import etiquette P = etiquette.photodb.PhotoDB() def easytagger(): while True: i = input('> ') if i.startswith('?'): i = i.split('?')[1] or None try: etiquette.tag_e...
Remove choices for any number of updates.
from django.db import models from cms.models import CMSPlugin from django.utils.translation import ugettext_lazy as _ class Update(models.Model): """ Defines a date on which updates were made. """ date = models.DateField(_('Update Date')) def __str__(self): return str(self.date) clas...
from django.db import models from cms.models import CMSPlugin from django.utils.translation import ugettext_lazy as _ class Update(models.Model): """ Defines a date on which updates were made. """ date = models.DateField(_('Update Date')) def __str__(self): return str(self.date) clas...
Transform sentences to arrays of words
from os import listdir from os.path import join def file_paths(data_path): return [join(data_path, name) for name in listdir(data_path)] def training_data(data_path): paths = file_paths(data_path) raw_text = [ open(path, 'r').read() for path in paths] dataX = [] dataY = [] for text in raw_text: data ...
from os import listdir from os.path import join import re def file_paths(data_path): return [join(data_path, name) for name in listdir(data_path)] def training_data(data_path): paths = file_paths(data_path) raw_text = [open(path, 'r').read() for path in paths] dataX = [] dataY = [] for text in raw_text:...
Fix import error due to wrong import line
# Copyright (c) 2016, Daniele Venzano # # 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 w...
# Copyright (c) 2016, Daniele Venzano # # 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 w...
Remove history domain in partner in eamil module.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Convert output values from int to binary for neural network
#!/usr/bin/env python from sklearn import datasets from random import shuffle # This example loads the IRIS dataset and classifies # using our neural network implementation. # The results are visualized in a 2D-plot. def main(): iris = datasets.load_iris() X = iris.data Y = iris.target # Randomize (s...
#!/usr/bin/env python from sklearn import datasets from random import shuffle import numpy as np from neuralnet import NeuralNet # This example loads the IRIS dataset and classifies # using our neural network implementation. # The results are visualized in a 2D-plot. def main(): iris = datasets.load_iris() X...
Change to use 'shutil.rmtree' instead of 'os.rmdir'
# -*- coding: utf-8 -*- import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else...
# -*- coding: utf-8 -*- import os import shutil from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): shutil.rmtree(pat...
Fix deprecated url import, (to path)
from django.conf.urls import include, url urlpatterns = [ url('', include('rest_friendship.urls', namespace='rest_friendship')), ]
from django.urls import path, include urlpatterns = [ path('', include(('rest_friendship.urls', 'rest_friendship'), namespace='rest_friendship')), ]
Add find_game_region() to return coors of game window
#!/usr/bin/env python """ This is the main file. The script finds the game window and sets up the coordinates for each block. The MIT License (MIT) (c) 2016 """ import pyautogui, logging, time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S') # logging.d...
#!/usr/bin/env python """ This is the main file. The script finds the game window and sets up the coordinates for each block. The MIT License (MIT) (c) 2016 """ import pyautogui, logging, time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S') # logging.d...
Print final surface elevations to stdout.
#! /usr/bin/env python import numpy as np def plot_elevation(avulsion): import matplotlib.pyplot as plt z = avulsion.get_value('land_surface__elevation') plt.imshow(z, origin='lower', cmap='terrain') plt.colorbar().ax.set_label('Elevation (m)') plt.show() def main(): import argparse fr...
#! /usr/bin/env python import sys import numpy as np def plot_elevation(avulsion): import matplotlib.pyplot as plt z = avulsion.get_value('land_surface__elevation') plt.imshow(z, origin='lower', cmap='terrain') plt.colorbar().ax.set_label('Elevation (m)') plt.show() def main(): import arg...
Update package data and version number.
import os from setuptools import setup, find_packages VERSION = '0.1.3a1' README_FILENAME = 'README.rst' readme = open(os.path.join(os.path.dirname(__file__), README_FILENAME)) long_description = readme.read() readme.close() setup( name='django-cbv-formpreview', version=VERSION, author='Ryan Kaskel', ...
import os from setuptools import setup, find_packages VERSION = '0.2.0a1' README_FILENAME = 'README.rst' readme = open(os.path.join(os.path.dirname(__file__), README_FILENAME)) long_description = readme.read() readme.close() setup( name='django-cbv-formpreview', version=VERSION, author='Ryan Kaskel', ...
Add extras for the sync client.
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="txyam2", version="0.5", description="Yet Another Memcached (YAM) client for Twisted.", author="Brian Muller", author_email="bamuller@gmail.com", license="MIT", url="http://github.com/bmuller/txyam", packages=...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="txyam2", version="0.5", description="Yet Another Memcached (YAM) client for Twisted.", author="Brian Muller", author_email="bamuller@gmail.com", license="MIT", url="http://github.com/bmuller/txyam", packages=...
Allow PropDict.sources in python bindings to be any sequence.
class PropDict(dict): def __init__(self, srcs): dict.__init__(self) self._sources = srcs def set_source_preference(self, sources): """ Change list of source preference This method has been deprecated and should no longer be used. """ raise DeprecationWarn...
class PropDict(dict): def __init__(self, srcs): dict.__init__(self) self._sources = srcs def set_source_preference(self, sources): """ Change list of source preference This method has been deprecated and should no longer be used. """ raise DeprecationWarn...
Add BareMiddleware to test helpers
import asyncio import inspect import sys import rollbar def run(coro): if sys.version_info >= (3, 7): return asyncio.run(coro) assert inspect.iscoroutine(coro) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: ...
import asyncio import inspect import sys import rollbar def run(coro): if sys.version_info >= (3, 7): return asyncio.run(coro) assert inspect.iscoroutine(coro) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: ...
Check for all exceptions to main method
#!/usr/bin/python # -*- coding: utf-8 -*- import json import os import sys import argparse import tmux_wrapper as tmux __version__ = 1.0 __description__ = "A tmux wrapper featuring shortcuts and session presets." def load_session_presets(): try: file_path = os.environ["TM_SESSIONS"] except KeyError:...
#!/usr/bin/python # -*- coding: utf-8 -*- import json import os import sys import argparse import tmux_wrapper as tmux __version__ = 1.0 __description__ = "A tmux wrapper featuring shortcuts and session presets." def load_session_presets(): try: file_path = os.environ["TM_SESSIONS"] except KeyError:...
Use short description if README.md not found.
#!python import os from distutils.core import setup filepath = os.path.dirname(__file__) readme_file = os.path.join(filepath, 'README.md') try: import pypandoc long_description = pypandoc.convert(readme_file, 'rst') except(IOError, ImportError): long_description = open(readme_file).read() def extract_ver...
#!python import os from distutils.core import setup description = 'Cmdlet provides pipe-like mechanism to cascade functions and generators.' filepath = os.path.dirname(__file__) readme_file = os.path.join(filepath, 'README.md') if not os.path.exist(readme_file): long_description = description else: try: ...
Upgrade certifi 2015.11.20.1 => 2016.2.28
import sys from setuptools import find_packages, setup with open('VERSION') as version_fp: VERSION = version_fp.read().strip() install_requires = [ 'django-local-settings>=1.0a13', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils...
import sys from setuptools import find_packages, setup with open('VERSION') as version_fp: VERSION = version_fp.read().strip() install_requires = [ 'django-local-settings>=1.0a13', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils...
Add sklearn dependency for tutorial
from distutils.core import setup, Extension from setuptools import setup, Extension config = { 'include_package_data': True, 'description': 'Deep RegulAtory GenOmic Neural Networks (DragoNN)', 'download_url': 'https://github.com/kundajelab/dragonn', 'version': '0.1', 'packages': ['dragonn', 'dragon...
from distutils.core import setup, Extension from setuptools import setup, Extension config = { 'include_package_data': True, 'description': 'Deep RegulAtory GenOmic Neural Networks (DragoNN)', 'download_url': 'https://github.com/kundajelab/dragonn', 'version': '0.1', 'packages': ['dragonn', 'dragon...
Set require debug to be the same as debug.
from .base import * # noqa DEBUG = True INTERNAL_IPS = INTERNAL_IPS + ('', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app_kdl_dev', 'USER': 'app_kdl', 'PASSWORD': '', 'HOST': '' }, } LOGGING_LEVEL = logging.DEBUG LOGGIN...
from .base import * # noqa DEBUG = True REQUIRE_DEBUG = DEBUG INTERNAL_IPS = INTERNAL_IPS + ('', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app_kdl_dev', 'USER': 'app_kdl', 'PASSWORD': '', 'HOST': '' }, } LOGGING_LEVEL =...
Remove stiffscroll from ELiDE requirements
# This file is part of LiSE, a framework for life simulation games. # Copyright (c) Zachary Spector, zacharyspector@gmail.com import sys if sys.version_info[0] < 3 or ( sys.version_info[0] == 3 and sys.version_info[1] < 3 ): raise RuntimeError("ELiDE requires Python 3.3 or later") from setuptools import se...
# This file is part of LiSE, a framework for life simulation games. # Copyright (c) Zachary Spector, zacharyspector@gmail.com import sys if sys.version_info[0] < 3 or ( sys.version_info[0] == 3 and sys.version_info[1] < 3 ): raise RuntimeError("ELiDE requires Python 3.3 or later") from setuptools import se...
Make FORMATS a tuple and add FORMATS_DESC for textual format descriptions.
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( (TARBALL, "Tarball (.tar)"), (TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)")...
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( TARBALL, TARBALL_GZ, TARBALL_BZ2, TARBALL_XZ, ZIP, ) FORMATS_DESC...
Change version to 1.0.0 to match organizational versioning scheme.
#! /usr/bin/env python import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = "django-premis-event-servi...
#! /usr/bin/env python import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = "django-premis-event-servi...
Fix importError for Yaafe and Aubio
# -*- coding: utf-8 -*- from __future__ import absolute_import from . import api from . import core from . import decoder from . import analyzer from . import grapher from . import encoder __version__ = '0.5.5' __all__ = ['api', 'core', 'decoder', 'analyzer', 'grapher', 'encoder'] def _discover_modules(): impo...
# -*- coding: utf-8 -*- from __future__ import absolute_import from . import api from . import core from . import decoder from . import analyzer from . import grapher from . import encoder __version__ = '0.5.5' __all__ = ['api', 'core', 'decoder', 'analyzer', 'grapher', 'encoder'] def _discover_modules(): impo...
Fix extraneous self parameter in staticmethod
import subprocess import os from .settings import Settings class Command(): def __init__(self, command): self.__command = command self.__startup_info = None self.__shell = False if os.name == 'nt': self.__startup_info = subprocess.STARTUPINFO() self.__startu...
import subprocess import os from .settings import Settings class Command(): def __init__(self, command): self.__command = command self.__startup_info = None self.__shell = False if os.name == 'nt': self.__startup_info = subprocess.STARTUPINFO() self.__startu...
Add example for query datetime range
#!/usr/bin/env python from config import MongoSource from manager import PluginManager from log import LogDocGenerator def main(): # 1. load all plugins plugin_manager = PluginManager() # 2. get one or more mongodb collection ms = MongoSource() collection = ms.get_collection("net-test", "ename_...
#!/usr/bin/env python from config import MongoSource from manager import PluginManager from log import LogDocGenerator import datetime def main(): # 1. load all plugins plugin_manager = PluginManager() # 2. get one or more mongodb collection ms = MongoSource() collection = ms.get_collection("ne...
Add a development status classifier.
from setuptools import setup, find_packages import dnschain setup( name="dnschain", version=dnschain.__version__, url='https://github.com/okturtles/pydnschain', license='MPL', description="A Python DNSChain library", author='Greg Slepak', author_email='hi@okturtles.com', packages=find_...
from setuptools import setup, find_packages import dnschain setup( name="dnschain", version=dnschain.__version__, url='https://github.com/okturtles/pydnschain', license='MPL', description="A Python DNSChain library", author='Greg Slepak', author_email='hi@okturtles.com', packages=find_...
Cut a new version, literally just to make the PyPI page look nicer.
"""A setuptools based setup module.""" # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open as c_open from os import path HERE = path.abspath(path.dirname(__file__)) # Get the long description from the README file with c_open(pat...
"""A setuptools based setup module.""" # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open as c_open from os import path HERE = path.abspath(path.dirname(__file__)) # Get the long description from the README file with c_open(pat...
Add argparse to install_requires for Python 2.6
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='aka.tkf@gmail.com', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitsc...
from distutils.core import setup import traitscli setup( name='traitscli', version=traitscli.__version__, py_modules=['traitscli'], author=traitscli.__author__, author_email='aka.tkf@gmail.com', url='https://github.com/tkf/traitscli', license=traitscli.__license__, description='traitsc...
Add h5py as a dependency
from setuptools import setup setup(name='emopy', version='0.1', description='Emotion Recognition Package for Python', url='http://github.com/selameab/emopy', author='Selameab', author_email='email@selameab.com', license='', package_data={'emopy': ['models/*.h5', 'models/*.json...
from setuptools import setup setup(name='emopy', version='0.1', description='Emotion Recognition Package for Python', url='http://github.com/selameab/emopy', author='Selameab', author_email='email@selameab.com', license='', package_data={'emopy': ['models/*.h5', 'models/*.json...