Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Remove permission to edit tables
from django.contrib import admin from gym_app.models import Task, Athlete, PersonalTrainer, BodyScreening, WorkoutPlan, Tracker, MailBox, Message from django.contrib.auth.models import Permission # Register your models here. admin.site.register(Task) admin.site.register(Permission) admin.site.register(Athlete) admin.s...
from django.contrib import admin from gym_app.models import Task from django.contrib.auth.models import Permission # Register your models here. admin.site.register(Task) admin.site.register(Permission)
Use `reducer` to replace `prepare`
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.prepare import Prepare class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self...
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.roo...
Use setup_logger properly in tests.
# Copyright 2011-2016 Josh Kearney # # 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 agre...
# Copyright 2011-2016 Josh Kearney # # 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 agre...
Use default seed for the test.
import random import time from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): random.seed(time.time()) seed = random.randint(0, 100000) simplex = OpenSimplexNoise(seed) im = Image.new('L', (WIDTH, HEIGHT)) ...
from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): simplex = OpenSimplexNoise() im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): #value = simplex.n...
Change to vanilla namespace package
try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
__import__('pkg_resources').declare_namespace(__name__)
Fix style on migration - waste of time, but whatever
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-20 18:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accelerator', '0043_remove_exclude_fields'), ] operations = [ migrations.Re...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-20 18:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accelerator', '0043_remove_exclude_fields'), ] help_text = 'Show the new-style side ...
Update WiFi firmware update script.
# WINC Firmware Update Script. # # This script updates the ATWINC1500 WiFi module firmware. # Copy the firmware image to uSD card before running this script. # NOTE: Firmware version 19.5.2 does NOT support ATWINC1500-MR210PA. import network # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.M...
# WINC Firmware Update Script. # # This script updates the ATWINC1500 WiFi module firmware. # Copy the firmware image to uSD card before running this script. # NOTE: Older fimware versions are no longer supported by the host driver. # NOTE: The latest firmware (19.6.1) only works on ATWINC1500-MR210PB. import network ...
Correct typo in help string
import logging from django.utils.translation import ugettext_lazy as _ from django.core.management.base import BaseCommand from oscar.apps.customer.alerts import utils logger = logging.getLogger(__name__) class Command(BaseCommand): """ Check stock records of products for availability and send out alerts ...
import logging from django.utils.translation import ugettext_lazy as _ from django.core.management.base import BaseCommand from oscar.apps.customer.alerts import utils logger = logging.getLogger(__name__) class Command(BaseCommand): """ Check stock records of products for availability and send out alerts ...
Define the default policy file
# Copyright 2016 Red Hat Inc. # # 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...
# Copyright 2016 Red Hat Inc. # # 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...
Upgrade code to Python 3.6+, Django 2.2 and remove deprecations
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r"^$", TemplateView.as_view(template_name="homepage.html")), url(r"^remote.html$", TemplateView.as_view(template_name="remote.html"), name="remote.html"), ]
from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name="homepage.html")), re_path(r"^remote.html$", TemplateView.as_view(template_name="remote.html"), name="remote.html"), ]
Add test to clarify equality/is behavior
import Transaction import unittest class TestTransaction(unittest.TestCase) : def setUp(self) : self.test_object = Transaction.Transaction() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_can_assign_data(self) : s...
import Transaction import unittest class TestTransaction(unittest.TestCase) : def setUp(self) : self.test_object = Transaction.Transaction() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_can_assign_data(self) : s...
Add missing pytest DB marker
""" Tests that migrations are not missing """ try: from io import StringIO except ImportError: from StringIO import StringIO import pytest from django.core.management import call_command def test_no_missing_migrations(): """Check no model changes have been made since the last `./manage.py makemigration...
""" Tests that migrations are not missing """ try: from io import StringIO except ImportError: from StringIO import StringIO import pytest from django.core.management import call_command @pytest.mark.django_db def test_no_missing_migrations(): """Check no model changes have been made since the last `./...
Fix relative portion of link.
from pyshelf.cloud.stream_iterator import StreamIterator from flask import Response class ArtifactListManager(object): def __init__(self, container): self.container = container def get_artifact(self, path): """ Gets artifact or artifact list information. Args: ...
from pyshelf.cloud.stream_iterator import StreamIterator from flask import Response class ArtifactListManager(object): def __init__(self, container): self.container = container def get_artifact(self, path): """ Gets artifact or artifact list information. Args: ...
Test added. Program should be complete.
# Asks the user for input of the word and makes it lower case. normStr = raw_input("Enter the word:\n").lower(); # Inverts the string so it can compare it with the original input. invertStr = normStr[::-1];
# Asks the user for input of the word and makes it lower case. normStr = raw_input("Enter the word:\n").lower(); # Inverts the string so it can compare it with the original input. invertStr = normStr[::-1]; # Tests if the string is a palindrome. If so, it prints True. Else, prints False. if normStr == invertStr: pri...
Deal with the Django app refactoring.
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_...
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_...
Fix bug caused by giving post detail view a new name
from django.conf.urls import url, include from rest_framework import routers import service.authors.views import service.friendrequest.views import service.users.views import service.nodes.views import service.posts.views router = routers.DefaultRouter() router.register(r'users', service.users.views.UserViewSet) rout...
from django.conf.urls import url, include from rest_framework import routers import service.authors.views import service.friendrequest.views import service.users.views import service.nodes.views import service.posts.views router = routers.DefaultRouter() router.register(r'users', service.users.views.UserViewSet) rout...
Fix InspectorMemoryTest.testGetDOMStats to have consistent behaviour on CrOS and desktop versions of Chrome. Starting the browser in CrOS requires navigating through an initial setup that does not leave us with a tab at "chrome://newtab". This workaround runs the test in a new tab on all platforms for consistency.
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_...
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_...
Define a MD->RST conversion function
from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print("warning: pypandoc module not found, could not convert Markdown to RST") read_md = lambda f: open(f, 'r').read() setup(name='centerline', version='0.1', descriptio...
from setuptools import setup try: from pypandoc import convert def read_md(): return lambda f: convert(f, 'rst') except ImportError: print( "warning: pypandoc module not found, could not convert Markdown to RST" ) def read_md(): return lambda f: open(f, 'r').read() setup...
Clear all session data from websocket obj
# -*- coding: utf-8 -*- from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.clo...
# -*- coding: utf-8 -*- from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.clo...
Update post handling after migration
from django.shortcuts import render, redirect from django.http import Http404 from .models import Link, LinkForm from urlparse import urlparse def catchall(request, id): try: link = Link.objects.get(id=id) return redirect(link.url) except: parsed = urlparse(id) if parsed.netloc: ...
from django.shortcuts import render, redirect from django.http import Http404 from .models import Link, LinkForm from urlparse import urlparse def catchall(request, id): try: link = Link.objects.get(id=id) return redirect(link.url) except: parsed = urlparse(id) if parsed.netloc: ...
Remove exit statement and error message for tex output
#!/usr/bin/python import sys import latex_table import table_to_file if __name__ == "__main__": # Parse arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("input", help="the LaTeX input file to be parsed") # Add two mutually exclusive arguments: grouped/ungrouped ...
#!/usr/bin/python import sys import latex_table import table_to_file if __name__ == "__main__": # Parse arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("input", help="the LaTeX input file to be parsed") # Add two mutually exclusive arguments: grouped/ungrouped ...
Increase tollerance for heat demand test
""" Test the electricity demand SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de> SPDX-FileCopyrightText: Patrik Schönfeldt SPDX-License-Identifier: MIT """ import numpy as np from demandlib.examples import heat_demand_example def test_heat_example(): """Test the results of the heat example.""" ann...
""" Test the electricity demand SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de> SPDX-FileCopyrightText: Patrik Schönfeldt SPDX-License-Identifier: MIT """ import numpy as np from demandlib.examples import heat_demand_example def test_heat_example(): """Test the results of the heat example.""" ann...
Remove returned pile b/c mutating directly
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube, cube_sizes = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] ...
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] if(...
Use create instead of instance and save
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key ...
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key ...
Switch cache ban request to new postcommit synchronous method
from api.caching.tasks import ban_url from framework.tasks.handlers import enqueue_task from modularodm import signals @signals.save.connect def log_object_saved(sender, instance, fields_changed, cached_data): abs_url = None if hasattr(instance, 'absolute_api_v2_url'): abs_url = instance.absolute_api_v...
from functools import partial from api.caching.tasks import ban_url from framework.tasks.postcommit_handlers import enqueue_postcommit_task from modularodm import signals @signals.save.connect def log_object_saved(sender, instance, fields_changed, cached_data): abs_url = None if hasattr(instance, 'absolute_a...
Test that the service is register with the correct txt record
from saluttest import exec_test import avahitest from avahitest import AvahiListener import time def test(q, bus, conn): a = AvahiListener(q) a.listen_for_service("_presence._tcp") conn.Connect() q.expect('service-added', name='test-register@' + avahitest.get_host_name()) if __name__ == '__ma...
from saluttest import exec_test import avahitest from avahitest import AvahiListener from avahitest import txt_get_key from avahi import txt_array_to_string_array import time PUBLISHED_NAME="test-register" FIRST_NAME="lastname" LAST_NAME="lastname" def test(q, bus, conn): a = AvahiListener(q) a.listen_for_se...
Configure throughput for 'undefined' collection
class Azure: resource_group = "MajavaShakki" location = "northeurope" cosmosdb_name = f"{resource_group}mongo".lower() plan_name = f"{resource_group}Plan" site_name = f"{resource_group}Site" class Mongo: database_name = "Majavashakki" collection_throughput = 500 collections = ["gamemodels", "sessions",...
class Azure: resource_group = "MajavaShakki" location = "northeurope" cosmosdb_name = f"{resource_group}mongo".lower() plan_name = f"{resource_group}Plan" site_name = f"{resource_group}Site" class Mongo: database_name = "Majavashakki" collection_throughput = 500 system_indexes_collection = "undefined" ...
Update mozci version to handle credentials in env variables
from setuptools import setup, find_packages deps = [ 'mozillapulse', 'mozci>=0.7.0', 'requests', ] setup(name='pulse-actions', version='0.1.4', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License ...
from setuptools import setup, find_packages deps = [ 'mozillapulse', 'mozci>=0.7.3', 'requests', ] setup(name='pulse-actions', version='0.1.4', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License ...
Add more versions of Windows + environment
import os, sys from setuptools import setup setup( name='reddit_comment_scraper', version='2.0.0', description='A simple Reddit-scraping script', url='https://github.com/jfarmer/reddit_comment_scraper', author='Jesse Farmer', author_email='jesse@20bits.com', license='MIT', packages=['r...
import os, sys from setuptools import setup setup( name='reddit_comment_scraper', version='2.0.0', description='A simple Reddit-scraping script', url='https://github.com/jfarmer/reddit_comment_scraper', author='Jesse Farmer', author_email='jesse@20bits.com', license='MIT', packages=['r...
Bring in pytest and pytest-cov
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [ ] test_requirements = [ ] dist = setup( name='cloudpickle', version='0.1.0', description='Extended pickling support for Python objects', autho...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [ ] test_requirements = [ 'pytest', 'pytest-cov' ] dist = setup( name='cloudpickle', version='0.1.0', description='Extended pickling support...
Restructure context assembly for CozyLAN site
""" Site-specific code extension """ from __future__ import annotations from typing import Any from flask import g from byceps.services.seating import seat_service from byceps.services.ticketing import ticket_service def template_context_processor() -> dict[str, Any]: """Extend template context.""" if g.pa...
""" Site-specific code extension """ from __future__ import annotations from typing import Any from flask import g from byceps.services.seating import seat_service from byceps.services.ticketing import ticket_service def template_context_processor() -> dict[str, Any]: """Extend template context.""" context...
Create main() entry point for final script
import argparse import astropy.io.fits as fits import numpy as np import calc import combine if __name__=="__main__": argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) args = argpars...
import argparse import calc import combine from combine import stack_fits_data from calc import load_fits_data def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) ret...
Update to 0.0.11 version for PyPI.
# Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Add middle name display to autocomplete widget
from autocomplete_light import shortcuts as autocomplete_light from django.contrib.auth.models import User, Group class UserAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['username', 'first_name', 'last_name'] split_words = True def choices_for_request(self): self.choices...
from autocomplete_light import shortcuts as autocomplete_light from django.contrib.auth.models import User, Group class UserAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['username', 'first_name', 'last_name'] split_words = True def choices_for_request(self): self.choice...
Use PyYAML as YAML's loader and dumper
from pureyaml import dump as dumps from pureyaml import load as loads __all__ = ['dumps', 'loads']
from __future__ import absolute_import import functools from yaml import dump, Dumper, load, Loader dumps = functools.partial(dump, Dumper=Dumper) loads = functools.partial(load, Loader=Loader) __all__ = ['dumps', 'loads']
Fix whitespace issue in SecureTransport test
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() exce...
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() exce...
Fix python tests re: http routing
# -*- coding: utf-8 -*- from copper.wsgi_support import wsgi def test_http_handler(copper_client, copper_http_client): def application(environ, start_response): message = 'Hello, %s!' % (environ['PATH_INFO'],) start_response('200 OK', [ ('Content-Type', 'text/plain; charset=UTF-8'), ...
# -*- coding: utf-8 -*- from copper.wsgi_support import wsgi def test_http_handler(copper_client, copper_http_client): def application(environ, start_response): message = 'Hello, %s!' % (environ['PATH_INFO'],) start_response('200 OK', [ ('Content-Type', 'text/plain; charset=UTF-8'), ...
Fix logic bugs and add historypage handler
# -*- coding: utf-8 -*- import webapp2 # Importing request handlers from signup import Signup from login import Login from logout import Logout from wikipage import WikiPage from editpage import EditPage PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([ ('/signup', Signup),...
# -*- coding: utf-8 -*- import webapp2 # Importing request handlers from signup import Signup from login import Login from logout import Logout from wikipage import WikiPage from editpage import EditPage from historypage import HistoryPage PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIAp...
Remove print statements, not usefull anymore.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'Lily...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'Lily...
Add print statements to debug BlogPostListView
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
Fix tests now that we have H1 capturing
import os from django.test import TestCase from search.parse_json import process_file base_dir = os.path.dirname(os.path.dirname(__file__)) class TestHacks(TestCase): def test_h2_parsing(self): data = process_file( os.path.join( base_dir, 'files/api.fjson', ...
import os from django.test import TestCase from search.parse_json import process_file base_dir = os.path.dirname(os.path.dirname(__file__)) class TestHacks(TestCase): def test_h2_parsing(self): data = process_file( os.path.join( base_dir, 'files/api.fjson', ...
Work on master is now 1.5 dev work
""" Client for Swift Copyright 2012 Gregory Holt 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...
""" Client for Swift Copyright 2012 Gregory Holt 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...
Improve my bot according to tutorial
from hlt import * from networking import * myID, gameMap = getInit() sendInit("MyPythonBot") while True: moves = [] gameMap = getFrame() for y in range(gameMap.height): for x in range(gameMap.width): location = Location(x, y) if gameMap.getSite(location).owner == myID: ...
from hlt import * from networking import * myID, gameMap = getInit() sendInit("dpetkerPythonBot") def create_move(location): site = gameMap.getSite(location) # See if there's an enemy adjacent to us with less strength. If so, capture it for d in CARDINALS: neighbour_site = gameMap.getSite(location, d) ...
Revert test db to postgress
import os class Config(object): """Parent configuration class.""" DEBUG = False CSRF_ENABLED = True SECRET_KEY = os.getenv('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True SQLALCHEMY_...
import os class Config(object): """Parent configuration class.""" DEBUG = False CSRF_ENABLED = True SECRET_KEY = os.getenv('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True SQLALCHEMY_...
Use None instead of "null" in Highcharts boilerplate
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': 'null'}, 'subtitle': {'text': 'null'}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker'...
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', }, 'title': {'text': None}, 'subtitle': {'text': None}, 'credits': { 'enabled': False }, 'plotOptions': { 'series': { 'marker': { ...
Allow importing from pymp module directly
import logging import multiprocessing DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatt...
import logging import multiprocessing from pymp.dispatcher import State, Dispatcher, Proxy DEBUG = False # for now def get_logger(level=None): logger = multiprocessing.get_logger() format = '[%(asctime)s][%(levelname)s/%(processName)s] %(message)s' formatter = logging.Formatter(format) handler = lo...
Fix error to handle using mpxapi in subdirs
from .http import MPXApi from api_base import get_guid_based_id __version__ = '0.0.4' __title__ = 'mpxapi'
from .http import MPXApi from .api_base import get_guid_based_id __version__ = '0.0.4' __title__ = 'mpxapi'
Rename uploaded files to their SHA1
import hashlib from rest.models import Sound from rest.serializers import SoundSerializer from rest_framework import generics def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest()...
import hashlib from rest.models import Sound from rest.serializers import SoundSerializer from rest_framework import generics def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest()...
Make main program throw warning on python2.
import sys import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if result is not None: print(result) if len(sys.argv) >= 2: break
# vim: set fileencoding=utf-8 import sys if sys.version_info.major < 3: print("This program is for python version 3 only.") sys.exit(3) import lexer import execute while True: instr = input("» ") toks = lexer.to_toks(instr) rpn = lexer.to_rpn(toks) result = execute.eval_rpn(rpn) if res...
Make sure path is in a list
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'], "sys.path": sys.p...
""" This file is run by the system python, and outputs paths the import mechanism in the virtualenv will need to be able to import libraries from. """ import json import os import sys """ Return paths from the system python """ def py_info(): data = { "path": os.environ['PATH'].split(os.pathsep), ...
Update last modified date for HTTP 304 after migrating to qr_code 6.1.
from datetime import datetime from qrcode import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H from qr_code.qrcode.image import SVG_FORMAT_NAME QR_CODE_GENERATION_VERSION_DATE = datetime(year=2018, month=3, day=15, hour=0) SIZE_DICT = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTION...
from datetime import datetime from qrcode import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H from qr_code.qrcode.image import SVG_FORMAT_NAME QR_CODE_GENERATION_VERSION_DATE = datetime(year=2019, month=4, day=11, hour=15) SIZE_DICT = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTIO...
Remove jsondata variable to simplify the code
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\...
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\...
Use later version of requests, to match ckanext-archiver.
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.or...
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.or...
Add classifiers to show Python 3 support
#!/usr/bin/env python from setuptools import setup import lib as asteval setup(name = 'asteval', version = asteval.__version__, author = 'Matthew Newville', author_email = 'newville@cars.uchicago.edu', url = 'http://github.com/newville/asteval', license = 'BSD', description = "Safe...
#!/usr/bin/env python from setuptools import setup import lib as asteval setup(name = 'asteval', version = asteval.__version__, author = 'Matthew Newville', author_email = 'newville@cars.uchicago.edu', url = 'http://github.com/newville/asteval', license = 'BSD', description = "Safe...
Add sys and os imports
from setuptools import setup, find_packages def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#") def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(file...
from setuptools import setup, find_packages import sys import os def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#") def _read_requirements(filename): """Parses a file for pip installation requirements."...
Exclude tests folder from package
from setuptools import find_packages, setup version = '6.5.1' extras_require = { 'images': [ 'Pillow>=2.8.1,<2.9', ], } setup( name='incuna-test-utils', packages=find_packages(), include_package_data=True, version=version, description='Custom TestCases and other test helpers fo...
from setuptools import find_packages, setup version = '6.5.1' extras_require = { 'images': [ 'Pillow>=2.8.1,<2.9', ], } setup( name='incuna-test-utils', packages=find_packages(exclude=['tests']), include_package_data=True, version=version, description='Custom TestCases and othe...
Upgrade minimum Django version past security vulnerability
from setuptools import setup setup( name='tablo', description='A PostGIS table to feature service app for Django', keywords='feature service, map server, postgis, django', version='1.3.0', packages=['tablo', 'tablo.migrations', 'tablo.interfaces', 'tablo.interfaces.arcgis'], install_requires=[ ...
from setuptools import setup setup( name='tablo', description='A PostGIS table to feature service app for Django', keywords='feature service, map server, postgis, django', version='1.3.0', packages=['tablo', 'tablo.migrations', 'tablo.interfaces', 'tablo.interfaces.arcgis'], install_requires=[ ...
Set the mainline version to "dev".
from distutils.core import setup setup( name="datafork", version="0.0.1", description="Forkable global state", packages=['datafork'], author="Martin Atkins", author_email="mart@degeneration.co.uk", classifiers=[ "License :: OSI Approved :: MIT License", "Intended Audience ::...
from distutils.core import setup setup( name="datafork", version="dev", description="Forkable global state", packages=['datafork'], author="Martin Atkins", author_email="mart@degeneration.co.uk", classifiers=[ "License :: OSI Approved :: MIT License", "Intended Audience :: D...
Add permission check for TEDx
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import RegistrationForm from .models import Registration import utils def handle_registration(request): if request.method == 'POST': form = RegistrationForm(request.POST...
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect from django.shortcuts import render from clubs.models import Team from .forms import RegistrationForm from .models import Registration import utils def handle_regis...
Allow migration to run on Postgres
# Generated by Django 3.0.8 on 2020-07-23 02:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0002_auto_20200708_2203'), ] operations = [ migrations.AlterField( model_name='job', name='id', ...
# Generated by Django 3.0.8 on 2020-07-23 02:19. # Manually modified by Nokome Bentley on 2020-11-09 because the original # `AlterField` operation was causing the following error on Postgres: # django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint # In production, tha...
Change iteritems() to items() for future compatibility
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import Importer as rtmimp class TestRTMImport(TestCase): def setUp(self): self.patches = di...
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import Importer as rtmimp class TestRTMImport(TestCase): def setUp(self): self.patches = di...
Set download_url to pypi directory.
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() import os from setuptools import setup, find_packages here = os.path.dirname(__file__) version_file = os.path.join(here, 'src/iptools/__init__.py') d = {} execfile(version_file, d) version = d['__version__'] setup( name = 'iptools', ...
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() import os from setuptools import setup, find_packages here = os.path.dirname(__file__) version_file = os.path.join(here, 'src/iptools/__init__.py') d = {} execfile(version_file, d) version = d['__version__'] setup( name = 'iptools', ...
Include binaries when importing (for Windows).
from conans import ConanFile, CMake, tools class VarconfConan(ConanFile): name = "varconf" version = "1.0.3" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/varconf" description = "Configuration li...
from conans import ConanFile, CMake, tools class VarconfConan(ConanFile): name = "varconf" version = "1.0.3" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/varconf" description = "Configuration li...
Enable all auth algorithms that might be emitted by the alice.
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig class AUTH_CREDS(AUTH_CREDS_orig): enalgs = ('SHA-256-sess', 'SHA-256', 'MD5-sess', 'MD5', None) realm = 'VoIPTests.NET' def __init__(self): AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
Return a 404 if the package was not found
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', ...
"""Package blueprint.""" import os import magic from flask import Blueprint, current_app, make_response, render_template blueprint = Blueprint('packages', __name__, url_prefix='/packages') @blueprint.route('') def foo(): return 'ok' @blueprint.route('/<package_type>/<letter>/<name>/<version>', ...
Add sigma0 and alpha AMR parameters to the function.
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = df.grad(u) costheta = df.dot(m, E) ...
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = -df.grad(u) costheta ...
Test settings which don't depend on local ones
from __future__ import absolute_import import os from .local import * EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' if 'TRAVIS' not in os.environ: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'file': { 'level': 'DE...
from __future__ import absolute_import import os from .base import * DEBUG = True TEMPLATES[0]['OPTIONS']['debug'] = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': utils.get_env_setting('DB_NAME'), 'USER': utils.get_env_setting('DB_USER'), ...
Add --feedvaldiator option to validator
"""Validate GTFS""" import os import mzgtfs.feed import mzgtfs.validation import task class FeedEaterValidate(task.FeedEaterTask): def run(self): # Validate feeds self.log("===== Feed: %s ====="%self.feedid) feed = self.registry.feed(self.feedid) filename = self.filename or os.path.join(self.workdi...
"""Validate GTFS""" import os import mzgtfs.feed import mzgtfs.validation import task class FeedEaterValidate(task.FeedEaterTask): def __init__(self, *args, **kwargs): super(FeedEaterValidate, self).__init__(*args, **kwargs) self.feedvalidator = kwargs.get('feedvalidator') def parser(self): parser =...
Update call method in test client
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so...
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so...
Return chained iterators instead of only first of multiple iterators
from lxml import etree from app import formatting def get_namespace_from_top(fn, key='xmlns'): ac, el = next(etree.iterparse(fn)) return {'xmlns': el.nsmap[key]} def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None): """ Calls xmltag generator for multiple files. """ # Dep...
from lxml import etree import itertools from app import formatting def get_namespace_from_top(fn, key='xmlns'): ac, el = next(etree.iterparse(fn)) return {'xmlns': el.nsmap[key]} def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None): """ Calls xmltag generator for multiple files. ...
Format test-only's kernel_version to avoid mistakes
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_arg...
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_arg...
Create a new figure for imshow if there is already data
import matplotlib.pyplot as plt def imshow(*args, **kwargs): kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') plt.imshow(*args, **kwargs) imread = plt.imread show = plt.show def _app_show(): show()
import matplotlib.pyplot as plt def imshow(*args, **kwargs): if plt.gca().has_data(): plt.figure() kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') plt.imshow(*args, **kwargs) imread = plt.imread show = plt.show def _app_show(): show()
Add method to log to console
#!/usr/bin/env python3 # Module imports import logging import os import vitables _defaults = dict( AUTHOR = "Keith F Prussing", AUTHOR_EMAIL = "kprussing74@gmail.com", LICENSE = "MIT", PLUGIN_CLASS = "VtImageViewer", PLUGIN_NAME = "Image Viewer", COMMENT = "Display data sets as images", V...
#!/usr/bin/env python3 # Module imports import logging import os import vitables _defaults = dict( AUTHOR = "Keith F Prussing", AUTHOR_EMAIL = "kprussing74@gmail.com", LICENSE = "MIT", PLUGIN_CLASS = "VtImageViewer", PLUGIN_NAME = "Image Viewer", COMMENT = "Display data sets as images", V...
Fix run section with import statement
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, d...
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': import os host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, ...
Add more skeleton function code and TODOs
# Python 3.6 class Expr: pass class App(Expr): def __init__(self, fname, args=()): self.fname = fname self.args = args def __str__(self): return '{0}({1})'.format(self.fname, ','.join(map(str, self.args))) class Var(Expr): def __init__(self, name): self.name = name ...
# Python 3.6 class Expr: pass class App(Expr): def __init__(self, fname, args=()): self.fname = fname self.args = args def __str__(self): return '{0}({1})'.format(self.fname, ','.join(map(str, self.args))) class Var(Expr): def __init__(self, name): self.name = name ...
Add docstring into user_path function
# Copyright 2015-2016 Masayuki Yamamoto # # 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 agree...
# Copyright 2015-2016 Masayuki Yamamoto # # 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 agree...
Enable test now that it passes
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, ...
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, ...
Rewrite without using try-except to break out of two loops.
import nis verbose = 0 if __name__ == '__main__': verbose = 1 maps = nis.maps() try: for nismap in maps: if verbose: print nismap mapping = nis.cat(nismap) for k, v in mapping.items(): if verbose: print ' ', k, v if not k: continue if nis.match(k, nismap) <> v: print "NIS match...
import nis verbose = 0 if __name__ == '__main__': verbose = 1 maps = nis.maps() done = 0 for nismap in maps: if verbose: print nismap mapping = nis.cat(nismap) for k, v in mapping.items(): if verbose: print ' ', k, v if not k: continue if nis.match(k, nismap) <> v: print "NIS mat...
Increment minor version number ahead of release.
"""Main initialisation for extension.""" VERSION = (0, 2, 2) __version__ = '.'.join(map(str, VERSION)) try: from geokey.extensions.base import register register( 'geokey_dataimports', 'Data Imports', display_admin=True, superuser=False, version=__version__ ) excep...
"""Main initialisation for extension.""" VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) try: from geokey.extensions.base import register register( 'geokey_dataimports', 'Data Imports', display_admin=True, superuser=False, version=__version__ ) excep...
Fix sponsor level name in the django admin
from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel from ordered_model.models import OrderedModel class SponsorLevel(OrderedModel): name = models.CharField(_("name"), max_length=20) conference = models.ForeignKey( "confer...
from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel from ordered_model.models import OrderedModel class SponsorLevel(OrderedModel): name = models.CharField(_("name"), max_length=20) conference = models.ForeignKey( "confer...
Disable CGC simprocedures, it's unhelpful at the moment
import angr import simuvex class DrillerTransmit(simuvex.SimProcedure): ''' CGC's transmit simprocedure which supports errors ''' def run(self, fd, buf, count, tx_bytes): if self.state.mode == 'fastpath': # Special case for CFG generation self.state.store_mem(tx_bytes,...
import angr import simuvex class DrillerTransmit(simuvex.SimProcedure): ''' CGC's transmit simprocedure which supports errors ''' def run(self, fd, buf, count, tx_bytes): if self.state.mode == 'fastpath': # Special case for CFG generation self.state.store_mem(tx_bytes,...
Fix so that error under test actually gets triggered.
import morepath import os from .template_engine import FormatLoader class App(morepath.App): pass @App.path(path='{name}') class Person(object): def __init__(self, name): self.name = name @App.template_loader(extension='.unknown') def get_template_loader(template_directories, settings): return...
import morepath import os from .template_engine import FormatLoader class App(morepath.App): pass @App.path(path='{name}') class Person(object): def __init__(self, name): self.name = name @App.template_loader(extension='.unknown') def get_template_loader(template_directories, settings): return...
Fix bug in Pax Mininet node class
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __in...
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __in...
Fix hashing for Python 3
try: from hashlib import md5 except ImportError: from md5 import md5 from django.http import HttpResponseBadRequest from secretballot.middleware import SecretBallotIpUseragentMiddleware class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware): def generate_token(self, request): ...
try: from hashlib import md5 except ImportError: from md5 import md5 from django.http import HttpResponseBadRequest from secretballot.middleware import SecretBallotIpUseragentMiddleware class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware): def generate_token(self, request): ...
Add exception for import operation error and validation error
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ValidationError(BaseExcelError): pass class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class SerializerConfi...
class BaseExcelError(Exception): def __init__(self, message): super(BaseExcelError, self).__init__() self.message = message class ColumnNotEqualError(BaseExcelError): pass class FieldNotExist(BaseExcelError): pass class ImportOperationFailed(BaseExcelError): pass class Serialize...
Remove unsed json module import
import requests_unixsocket import urllib import json import re def dockerapi_dispatcher(app,request): method = request.method uri = re.match(r"^.+/dockerapi/(.+)", request.url).group(1) session = requests_unixsocket.Session() unix_socket = urllib.quote_plus( app.config['SOCKET'] ) return getattr(s...
import requests_unixsocket import urllib import re def dockerapi_dispatcher(app,request): method = request.method uri = re.match(r"^.+/dockerapi/(.+)", request.url).group(1) session = requests_unixsocket.Session() unix_socket = urllib.quote_plus( app.config['SOCKET'] ) return getattr(session,metho...
Add a URL conf for the EpilogueView.
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from .views import AwayView, DiscussionView, GameView, PrologueView urlpatterns = patterns('', # Because sooner or later, avalonstar.tv/ will be a welcome pag...
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from .views import (AwayView, DiscussionView, EpilogueView, GameView, PrologueView) urlpatterns = patterns('', # Because sooner or later, avalonstar.tv/ w...
Use serverprefs localizer for TestingServerPreferencesGroup
from __future__ import annotations from typing import TYPE_CHECKING from botus_receptus.app_commands import test_guilds_only from discord import app_commands from .daily_bread.daily_bread_preferences_group import DailyBreadPreferencesGroup if TYPE_CHECKING: from ...erasmus import Erasmus from ...l10n import...
from __future__ import annotations from typing import TYPE_CHECKING from botus_receptus.app_commands import test_guilds_only from discord import app_commands from .daily_bread.daily_bread_preferences_group import DailyBreadPreferencesGroup if TYPE_CHECKING: from ...erasmus import Erasmus from ...l10n import...
Make Meta class enforce only known properties
from __future__ import unicode_literals class Meta(object): '''Generic container for Meta classes''' def __new__(cls, meta=None): # Return a new class base on ourselves attrs = dict( (name, getattr(meta, name)) for name in dir(meta) if not name[0] == '_' ...
from __future__ import unicode_literals class Meta(object): '''Generic container for Meta classes''' def __new__(cls, meta=None): # Return a new class base on ourselves attrs = dict( (name, getattr(meta, name)) for name in dir(meta) if not name[0] == '_' and...
Remove debug print from view
import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consume...
import six from django.http import HttpResponseRedirect from django.shortcuts import reverse from django.conf import settings from openid.consumer import consumer import wargaming wot = wargaming.WoT(settings.WARGAMING_KEY, language='ru', region='ru') def auth_callback(request): oidconsumer = consumer.Consume...
Add notice on how to add custom apps for development
""" Django settings for laufpartner_server project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ f...
""" Django settings for laufpartner_server project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ f...
Allow specifying counter in SYNC message
class SyncProducer(object): """Transmits a SYNC message periodically.""" #: COB-ID of the SYNC message cob_id = 0x80 def __init__(self, network): self.network = network self.period = None self._task = None def transmit(self): """Send out a SYNC message once.""" ...
class SyncProducer(object): """Transmits a SYNC message periodically.""" #: COB-ID of the SYNC message cob_id = 0x80 def __init__(self, network): self.network = network self.period = None self._task = None def transmit(self, count=None): """Send out a SYNC messag...
Make dulwich check the tag.
from django.core.validators import RegexValidator sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$", message="Must be valid sha1 sum") tag_validator = RegexValidator(regex="^[A-Za-z][\w\-\.]+[A-Za-z]$", message="Must be letters and numbers" + ...
from django.core.validators import RegexValidator from django.core.exceptions import ValidationError from dulwich.repo import check_ref_format import re sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$", message="Must be valid sha1 sum") tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+...
Remove tags from list_filter and filter_horizontal
from django.contrib import admin from geartracker.models import * class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("make", "model", "size")} list_display = ('__unicode__', 'type', 'metric_weight', 'acquired') list_filter = ('archived', 'category', 'type', 'make', 'tags') search_field...
from django.contrib import admin from geartracker.models import * class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("make", "model", "size")} list_display = ('__unicode__', 'type', 'metric_weight', 'acquired') list_filter = ('archived', 'category', 'type', 'make') search_fields = ('ma...
Add nick to the log
import irc.client import sys import os class IrcClient(object): def __init__(self, server, port, channel, bot_name): self.server = server self.port = port self.channel = channel self.bot_name = bot_name def start(self): self._client = irc.client.IRC() self._cli...
import irc.client import sys import os class IrcClient(object): def __init__(self, server, port, channel, bot_name): self.server = server self.port = port self.channel = channel self.bot_name = bot_name def start(self): self._client = irc.client.IRC() self._cli...
Add helper function to convert money instances to default currency
from __future__ import unicode_literals from djmoney_rates.utils import convert_money import moneyed from .settings import bazaar_settings def convert_money_to_default_currency(money): """ Convert money amount to the system default currency. If money has no 'currency' attribute does nothing """ ...
Fix a problem with the allocations
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields class StockMove(models.Model): _in...
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields class StockMove(models.Model): _in...
Make copy of X in feed-forward
from .model import Model from ... import describe def _run_child_hooks(model, X, y): for layer in model._layers: for hook in layer.on_data_hooks: hook(layer, X, y) X = layer(X[:1000]) @describe.on_data(_run_child_hooks) class FeedForward(Model): '''A feed-forward network, that ch...
from .model import Model from ... import describe def _run_child_hooks(model, X, y): for layer in model._layers: for hook in layer.on_data_hooks: hook(layer, X, y) X = layer(X) if hasattr(X, 'shape'): X = model.ops.xp.ascontiguousarray(X) @describe.on_data(_run_ch...
Use PowerManagementNoop on import errors
# coding=utf-8 """ Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate. Allows you to add observer for power notifications if platform supports it. Usage: from power import PowerManagement, PowerManagementObserver # Automatically imports platform-speci...
# coding=utf-8 """ Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate. Allows you to add observer for power notifications if platform supports it. Usage: from power import PowerManagement, PowerManagementObserver # Automatically imports platform-speci...
Allow passing initialization kwargs to PDFDocument through pdf_response
from datetime import date import re from django.db.models import Max, Min from django.http import HttpResponse from pdfdocument.document import PDFDocument def worklog_period(obj): activity_period = obj.worklogentries.aggregate(Max('date'), Min('date')) article_period = obj.articleentries.aggregate(Max('dat...
from datetime import date import re from django.db.models import Max, Min from django.http import HttpResponse from pdfdocument.document import PDFDocument def worklog_period(obj): activity_period = obj.worklogentries.aggregate(Max('date'), Min('date')) article_period = obj.articleentries.aggregate(Max('dat...