Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix Account import in management command
from django.core.management.base import BaseCommand, CommandError from backend.models import Account from backend.tasks import get_all_contributions class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): parser.add_argument('--username', dest='usern...
from django.core.management.base import BaseCommand, CommandError from backend.models.account import Account from backend.tasks import get_all_contributions class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): parser.add_argument('--username', des...
Fix bug in Pipeline call where we run the whole Pipeline on list input
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is None: self.convert_token = lambda x: x elif callable(convert_token): self.convert_token = convert_token else: ...
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is None: self.convert_token = lambda x: x elif callable(convert_token): self.convert_token = convert_token else: ...
Fix bug that was causing this to not even work at all
# project from checks import AgentCheck VM_COUNTS = { 'pgpgin': 'pages.in', 'pgpgout': 'pages.out', 'pswpin': 'pages.swapped_in', 'pswpout': 'pages.swapped_out', 'pgfault': 'pages.faults', 'pgmajfault': 'pages.major_faults' } class MoreLinuxVMCheck(AgentCheck): def check(self, instance): ...
# project from checks import AgentCheck VM_COUNTS = { 'pgpgin': 'pages.in', 'pgpgout': 'pages.out', 'pswpin': 'pages.swapped_in', 'pswpout': 'pages.swapped_out', 'pgfault': 'pages.faults', 'pgmajfault': 'pages.major_faults' } class MoreLinuxVMCheck(AgentCheck): def check(self, instance): ...
Create destination path if it does no exist and copy file using shutil
import os class Generator: def run(self, sourcedir, outputdir): sourcedir = os.path.normpath(sourcedir) outputdir = os.path.normpath(outputdir) prefix = len(sourcedir)+len(os.path.sep) for root, dirs, files in os.walk(sourcedir): destpath = os.path.join(outputdir, root[...
import os import shutil class Generator: def run(self, sourcedir, outputdir): sourcedir = os.path.normpath(sourcedir) outputdir = os.path.normpath(outputdir) prefix = len(sourcedir)+len(os.path.sep) for root, dirs, files in os.walk(sourcedir): destpath = os.path.join(ou...
CORRECT height/width conversion this time around
import argparse import numpy as np from PIL import Image lookup = " .,:-?X#" def image_to_ascii(image): """ PIL image object -> 2d array of values """ quantised = image.quantize(len(lookup)) quantised.show() array = np.asarray(quantised.resize((128,64))) return [[lookup[k] for k in i...
import argparse import numpy as np from PIL import Image lookup = " .,:-!?X#" def image_to_ascii(image, width=128): """ PIL image object -> 2d array of values """ def scale_height(h, w, new_width): print "original height: {}".format(h) print "original width: {}".format(w) pr...
Refactor tests in preparation of the merge of redirect tests.
"""Check REDIRECTIONS""" import io import os import pytest import nikola.plugins.command.init from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test...
"""Check REDIRECTIONS""" import io import os import pytest import nikola.plugins.command.init from nikola import __main__ from .helper import append_config, cd from .test_demo_build import prepare_demo_site from .test_empty_build import ( # NOQA test_archive_exists, test_avoid_double_slash_in_rss, test...
Make sure every payment state is
# -*- coding: utf-8 -*- """ byceps.blueprints.shop_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from collections import Counter def count_ordered_articles(article): """Count how often the article has been ordered, grouped by the order's payment state. ...
# -*- coding: utf-8 -*- """ byceps.blueprints.shop_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from collections import Counter from ..shop.models import PaymentState def count_ordered_articles(article): """Count how often the article has been ordered, grou...
Call diff_fonts with correct params
"""Functional tests Test will produce the following tuple of all path permutations paths = ['path/to/font_a', 'path/to/font_b'] [ (path/to/font_a, path/to/font_b), (path/to/font_b, path/to/font_a), ] and run them through our main diff_fonts functions. This test is slow and should be run on challenging font...
"""Functional tests Test will produce the following tuple of all path permutations paths = ['path/to/font_a', 'path/to/font_b'] [ (path/to/font_a, path/to/font_b), (path/to/font_b, path/to/font_a), ] and run them through our main diff_fonts functions. This test is slow and should be run on challenging font...
Add a url to github.
from setuptools import setup import os version = 0.1 setup( version=version, description="A script allowing to setup Amazon EC2 instances through configuration files.", long_description=open("README.txt").read() + "\n\n" + open(os.path.join("docs", "HISTORY.txt")).read(), name="mr...
from setuptools import setup import os version = 0.1 setup( version=version, description="A script allowing to setup Amazon EC2 instances through configuration files.", long_description=open("README.txt").read() + "\n\n" + open(os.path.join("docs", "HISTORY.txt")).read(), name="mr...
Rewrite the test script to hint all glyphs
from psautohint import autohint from psautohint import psautohint d = "tests/data/source-code-pro" mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") gg = [] ii = None for m in mm: f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None) g = f.convertToBez("A", Fa...
from psautohint import autohint from psautohint import psautohint baseDir = "tests/data/source-code-pro" masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") glyphList = None fonts = [] for master in masters: print("Hinting %s" % master) path = "%s/%s/font.otf" % (baseDir, mas...
Use python internal functions for generating, removing and changing directories
import os from subprocess import call from itertools import product, repeat # To be called from the main OpenSpace modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): settings.ap...
import os from subprocess import call from itertools import product, repeat import shutil # To be called from the main OpenSpace modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): ...
Rewrite custom log format to a class, add verbosity, and vars for options.
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads def lambda_handler(event, context): print('LOG RequestId: {}\tResponse:\n\n{}'.format( context.aws_request_id, None )) return None # Comment or remove everything below before deploying...
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads # Disable 'testing_locally' when deploying to AWS Lambda testing_locally = True verbose = True class CWLogs(object): def __init__(self, context): self.context = context def event(self, message, ev...
Add credentials module to core list
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPriv...
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPriv...
Fix a race condition in error reporting causing highlighted lines to get out of sync
from errormarker import ErrorMarker from util import delayed class ErrorReporter(object): def __init__(self, window, error_report, settings, expand_filename): self._marker = ErrorMarker(window, error_report, settings) self._error_report = error_report self._expand_filename = expand_filen...
from errormarker import ErrorMarker from util import delayed class ErrorReporter(object): def __init__(self, window, error_report, settings, expand_filename): self._marker = ErrorMarker(window, error_report, settings) self._error_report = error_report self._expand_filename = expand_filen...
Fix flake8 errors for build.
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries =...
from __future__ import absolute_import from __future__ import print_function import logging from kale import task logger = logging.getLogger(__name__) class FibonacciTask(task.Task): # How many times should taskworker retry if it fails. # If this task shouldn't be retried, set it to None max_retries =...
Switch to OpsGenie API V2
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key')...
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'applic...
Remove broken telemetry policy check
# Copyright 2012 Nebula, 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 agree...
# Copyright 2012 Nebula, 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 agree...
Update benchmarks to Pyton 3.
import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): ...
import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): ...
Update to changed zeit.cms test browser setup API
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing import zope.testbrowser.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without aut...
import mock import zeit.brightcove.convert import zeit.brightcove.testing import zeit.cms.testing class NotificationTest(zeit.cms.testing.BrowserTestCase): layer = zeit.brightcove.testing.LAYER def test_runs_import_as_system_user(self): # View is available without authentication b = zeit.cms...
Update HistoryIndeView - listdir is working.
from .view import View from errno import ENOENT from stat import S_IFDIR from gitfs import FuseMethodNotImplemented, FuseOSError from log import log class HistoryIndexView(View): def getattr(self, path, fh=None): ''' Returns a dictionary with keys identical to the stat C structure of s...
from datetime import datetime from errno import ENOENT from stat import S_IFDIR from pygit2 import GIT_SORT_TIME from .view import View from gitfs import FuseMethodNotImplemented, FuseOSError from log import log class HistoryIndexView(View): def getattr(self, path, fh=None): ''' Returns a dict...
Remove cms dependency in test-runner
HELPER_SETTINGS = { 'SITE_ID': 1, 'TIME_ZONE': 'Europe/Zurich', 'LANGUAGES': ( ('en', 'English'), ('de', 'German'), ('fr', 'French'), ), 'INSTALLED_APPS': [ 'parler', 'treebeard', 'aldryn_categories', ], 'PARLER_LANGUAGES': { 1: ( ...
HELPER_SETTINGS = { 'SITE_ID': 1, 'TIME_ZONE': 'Europe/Zurich', 'LANGUAGES': ( ('en', 'English'), ('de', 'German'), ('fr', 'French'), ), 'INSTALLED_APPS': [ 'parler', 'treebeard', 'aldryn_categories', ], 'PARLER_LANGUAGES': { 1: ( ...
Update test_render_PUT_valid_parameters to be an approximate first draft.
import json import urllib from twisted.trial import unittest import mock from mlabsim import update class UpdateResourceTests (unittest.TestCase): def test_render_PUT_valid_parameters(self): # Test data: tool_extra = { 'collector_onion': 'testfakenotreal.onion', } ...
import json import urllib from twisted.trial import unittest import mock from mlabsim import update class UpdateResourceTests (unittest.TestCase): def test_render_PUT_valid_parameters(self): # Test data: fqdn = 'mlab01.ooni-tests.not-real.except-it-actually-could-be.example.com' tool_...
Replace uni linebreaks with simple linefeeds in order to make highlighting work
from django import template from django.utils.safestring import mark_safe from django.utils.html import escape register = template.Library() def highlight_request(message): content = message.get_content() description = message.request.description try: index = content.index(description) except...
from django import template from django.utils.safestring import mark_safe from django.utils.html import escape register = template.Library() def highlight_request(message): content = message.get_content() description = message.request.description description = description.replace("\r\n", "\n") try: ...
Fix these class names and imports so it works
from armstrong import hatband from hatband_support import models from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Te...
from armstrong import hatband from . import models from django.db.models import TextField from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { TextFi...
Add code to show last commit message
from flask import Flask, request from pprint import pprint import json app = Flask(__name__) lastCommit = "No recorded commits!" @app.route("/") def hello(): return "IntegralGit: continuous integration via GitHub" @app.route("/update", methods=["POST"]) def update(): print json.dumps(request.form['payload']) r...
from flask import Flask, request from pprint import pprint import json app = Flask(__name__) lastCommit = "No recorded commits!" @app.route("/") def hello(): return "IntegralGit: continuous integration via GitHub" @app.route("/latest") def latest(): return lastCommit @app.route("/update", methods=["POST"]) def ...
Make function return false or true.
""" This file is part of Lisa. Lisa is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lisa is distributed in the hope that it will be useful,...
""" This file is part of Lisa. Lisa is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lisa is distributed in the hope that it will be useful,...
Fix cached graph out-of-sync when checking.
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: flow.set_cached_graph(graph...
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: flow.set_cached_graph(graph...
Update the mpl rcparams for mpl 2.0+
def setup_text_plots(fontsize=8, usetex=True): """ This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. """ import matplotlib matplotlib.rc('legend', fontsize=fontsize, handlelength=3) matplotlib.rc('axes', titlesize=fontsize) matp...
def setup_text_plots(fontsize=8, usetex=True): """ This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. """ import matplotlib from distutils.version import LooseVersion matplotlib.rc('legend', fontsize=fontsize, handlelength=3) mat...
Add addSettings call also to the testing code.
PATH = 0 VALUE = 1 MINIMUM = 2 MAXIMUM = 3 # Simulates the SettingsSevice object without using the D-Bus (intended for unit tests). Values passed to # __setitem__ (or the [] operator) will be stored in memory for later retrieval by __getitem__. class MockSettingsDevice(object): def __init__(self, supported_settin...
PATH = 0 VALUE = 1 MINIMUM = 2 MAXIMUM = 3 # Simulates the SettingsSevice object without using the D-Bus (intended for unit tests). Values passed to # __setitem__ (or the [] operator) will be stored in memory for later retrieval by __getitem__. class MockSettingsDevice(object): def __init__(self, supported_settin...
Update database URIs for C9.
class DevelopmentConfig(object): DATABASE_URI = "postgresql://action:action@localhost:5432/posts" DEBUG = True class TestingConfig(object): DATABASE_URI = "postgresql://action:action@localhost:5432/posts-test" DEBUG = True
class DevelopmentConfig(object): DATABASE_URI = "postgresql://ubuntu:thinkful@localhost:5432/posts" DEBUG = True class TestingConfig(object): DATABASE_URI = "postgresql://ubuntu:thinkful@localhost:5432/posts-test" DEBUG = True
Add find import to oslib init
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2017 Caian Benedicto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2017 Caian Benedicto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
Add test capturing need for an alternate keyring with an alternate keychain.
import pytest import keyring from keyring.testing.backend import BackendBasicTests from keyring.backends import macOS @pytest.mark.skipif( not keyring.backends.macOS.Keyring.viable, reason="macOS backend not viable", ) class Test_macOSKeychain(BackendBasicTests): def init_keyring(self): return ma...
import pytest import keyring from keyring.testing.backend import BackendBasicTests from keyring.backends import macOS @pytest.mark.skipif( not keyring.backends.macOS.Keyring.viable, reason="macOS backend not viable", ) class Test_macOSKeychain(BackendBasicTests): def init_keyring(self): return ma...
Add print debug to text function
from flask import request import requests from ..utils.status import get_status from ..utils.reminders import create_reminder import twilio.twiml import json from datetime import datetime def call(): resp = twilio.twiml.Response() resp.record(timeout=10, transcribe=True, transcribeCallback='http://...
from flask import request import requests from ..utils.status import get_status from ..utils.reminders import create_reminder import twilio.twiml import json from datetime import datetime def call(): resp = twilio.twiml.Response() resp.record(timeout=10, transcribe=True, transcribeCallback='http://...
Read database user and password from environment.
import os from django.conf import settings os.environ['REUSE_DB'] = '1' if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django_nose', 'markitup', '...
import os from django.conf import settings os.environ['REUSE_DB'] = '1' if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django_nose', 'markitup', '...
Hide "view site" link in admin
from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('django_netjsonconfig.controller.urls', namespace='controller')), ] ...
from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() admin.site.site_url = None urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('django_netjsonconfig.controller.urls', n...
Generalize print_tree to work with different number of columns.
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_childre...
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_childre...
Return new file name when uploading
from flask import Flask, request, jsonify, send_from_directory from werkzeug import secure_filename import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) projects = os.listdir(UPLOAD_FOLDER) r...
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) projects = os.listdir(UPLOAD_FOLDER) return projects.__repr__() + "\n" @a...
Enable global by default in example.
"""This is an example app, demonstrating usage.""" import os from flask import Flask from flask_jsondash.charts_builder import charts app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=False, JSONDASH_GLOBALDASH=False, JSONDASH_GLOBAL_USER='global', )...
"""This is an example app, demonstrating usage.""" import os from flask import Flask from flask_jsondash.charts_builder import charts app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=False, JSONDASH_GLOBALDASH=True, JSONDASH_GLOBAL_USER='global', ) ...
Fix a clearly wrong sign
from ppb_vector import Vector2 from math import isclose import pytest @pytest.mark.parametrize("left, right, expected", [ (Vector2(1, 1), Vector2(0, -1), 135), (Vector2(1, 1), Vector2(-1, 0), 135), (Vector2(0, 1), Vector2(0, -1), 180), (Vector2(-1, -1), Vector2(1, 0), 135), (Vector2(-1, -1), Vector...
from ppb_vector import Vector2 from math import isclose import pytest @pytest.mark.parametrize("left, right, expected", [ (Vector2(1, 1), Vector2(0, -1), -135), (Vector2(1, 1), Vector2(-1, 0), 135), (Vector2(0, 1), Vector2(0, -1), 180), (Vector2(-1, -1), Vector2(1, 0), 135), (Vector2(-1, -1), Vecto...
Test using multiple concurrent sessions
import BaseHTTPServer import threading import time import owebunit import bottle app = bottle.Bottle() @app.route('/ok') def ok(): return 'ok' @app.route('/internal_server_error') def internal_error(): bottle.abort(500, 'internal server error') def run_server(): app.run(host='localhost', port=8041) cla...
import BaseHTTPServer import threading import time import owebunit import bottle app = bottle.Bottle() @app.route('/ok') def ok(): return 'ok' @app.route('/internal_server_error') def internal_error(): bottle.abort(500, 'internal server error') def run_server(): app.run(host='localhost', port=8041) cla...
Fix code for review comments
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging logger = logging.getLogger(__name__) def _api_call(url, params={}): try: logger.info("API Call for url: %s, params: %s" % (url, params)) r = ...
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging from urllib.parse import urljoin logger = logging.getLogger(__name__) def _api_call(url, params=None): params = params or {} try: logger.info("AP...
Use local render_template than Flask's native
from flask import render_template from flask.views import View class RenderableView(View): def __init__(self, template, view): self.template = template self.view = view def dispatch_request(self, *args, **kwargs): view_model = self.view(*args, **kwargs) return render_template(...
from flaskbb.utils.helpers import render_template from flask.views import View class RenderableView(View): def __init__(self, template, view): self.template = template self.view = view def dispatch_request(self, *args, **kwargs): view_model = self.view(*args, **kwargs) return ...
Add unit test for getting reaction rate names
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] expected_timesteps = 2 expected_dimensions = (20.0, 20.0, 2.0) def setUp(self): self...
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] expected_reaction_rates = ['MyGrowth-rate'] expected_timesteps = 2 expected_dimensions = (20.0, 2...
Add tests for editor panel JS
from fancypages.test.testcases import SplinterTestCase class TestEditingFancyPage(SplinterTestCase): is_staff = True is_logged_in = True def test_moving_a_block(self): pass
from django.core.urlresolvers import reverse from fancypages.test.testcases import SplinterTestCase class TestTheEditorPanel(SplinterTestCase): is_staff = True is_logged_in = True def _get_cookie_names(self): return [c.get('name') for c in self.browser.cookies.all()] def test_can_be_opened_...
Fix version number reporting so we can be installed before Django.
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
VERSION = (1, 0, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases...
Use the proper none value
# vim: set fileencoding=utf-8 # Pavel Odvody <podvody@redhat.com> # # HICA - Host integrated container applications # # MIT License (C) 2015 from base.hica_base import * class TtyInjector(HicaInjector): def get_description(self): return 'Allocates a TTY for the process' def get_config_key(self): return '...
# vim: set fileencoding=utf-8 # Pavel Odvody <podvody@redhat.com> # # HICA - Host integrated container applications # # MIT License (C) 2015 from base.hica_base import * class TtyInjector(HicaInjector): def get_description(self): return 'Allocates a TTY for the process' def get_config_key(self): return '...
Change client.webrtc.fyi master ports as they conflict with master.client.quickoffice
# Copyright 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. """ActiveMaster definition.""" from config_bootstrap import Master class WebRTCFYI(Master.Master3): project_name = 'WebRTC FYI' master_port = 8063 sl...
# Copyright 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. """ActiveMaster definition.""" from config_bootstrap import Master class WebRTCFYI(Master.Master3): project_name = 'WebRTC FYI' master_port = 8072 sl...
Fix for zero depth path
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = p...
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = p...
Handle case where deconstruct receives string
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, m...
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, m...
Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
""" Wrapper for Cuneiform. """ from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = (...
""" Wrapper for Cuneiform. """ import tempfile import subprocess as sp from ocradmin.ocr.tools import check_aborted, set_progress from ocradmin.ocr.utils import HocrParser from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certai...
Add scipy in requirements list
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Developme...
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Developme...
Remove changelog from release description
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "ali@indydevs.org" __copyright__ = "Copyright 2014, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os....
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "ali@indydevs.org" __copyright__ = "Copyright 2014, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os....
Fix a hard-coded version number
from distutils.core import setup # setuptools breaks # Dynamically calculate the version based on knowledge.VERSION version_tuple = __import__('rest_hooks').VERSION version = '1.0.4' #'.'.join([str(v) for v in version_tuple]) setup( name = 'django-rest-hooks', description = 'A powerful mechanism for sending r...
from distutils.core import setup # setuptools breaks # Dynamically calculate the version based on knowledge.VERSION version_tuple = __import__('rest_hooks').VERSION version = '.'.join([str(v) for v in version_tuple]) setup( name = 'django-rest-hooks', description = 'A powerful mechanism for sending real time ...
Include pcbmode_config.json file in package
from setuptools import setup, find_packages setup( name = "pcbmode", packages = find_packages(), use_scm_version=True, setup_requires=['setuptools_scm'], install_requires = ['lxml', 'pyparsing'], package_data = { 'pcbmode': ['stackups/*.json', 'styles/*/*.json', ...
from setuptools import setup, find_packages setup( name = "pcbmode", packages = find_packages(), use_scm_version=True, setup_requires=['setuptools_scm'], install_requires = ['lxml', 'pyparsing'], package_data = { 'pcbmode': ['stackups/*.json', 'styles/*/*.json', ...
Change assignment to boolean equals
from genes import apt import platform class Config: OS = platform.system() (DIST, _, CODE) = platform.linux_distribution() REPO = DIST.lower() + '-' + CODE def main(): if Config.OS == 'Linux': if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian': apt.recv_key('58118E89F3A912897C07...
from genes import apt import platform class Config: OS = platform.system() (DIST, _, CODE) = platform.linux_distribution() REPO = DIST.lower() + '-' + CODE def main(): if Config.OS == 'Linux': if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian': apt.recv_key('58118E89F3A912897C07...
Handle no config.yaml in migrations
""" Migrate config to docker hosts list """ import os import yaml filename = os.path.join('data', 'configs.yaml') with open(filename) as handle: data = yaml.load(handle) host = data.pop('docker_host') data['docker_hosts'] = [host] with open(filename, 'w') as handle: yaml.dump(data, handle, default_flow_styl...
""" Migrate config to docker hosts list """ import os import sys import yaml filename = os.path.join('data', 'configs.yaml') try: with open(filename) as handle: data = yaml.load(handle) except FileNotFoundError: # This is fine; will fail for new installs sys.exit(0) host = data.pop('docker_host')...
Use `django.templatetags.static`to load the file
from django.conf import settings def compatible_staticpath(path): ''' Try to return a path compatible all the way back to Django 1.2. If anyone has a cleaner or better way to do this let me know! ''' try: # >= 1.4 from django.contrib.staticfiles.storage import staticfiles_storage ...
from django.conf import settings def compatible_staticpath(path): ''' Try to return a path compatible all the way back to Django 1.2. If anyone has a cleaner or better way to do this let me know! ''' try: # >= 1.4 from django.templatetags.static import static return static(...
Add role removal and logic cleanup
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg =...
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg =...
TEST allink_apps subtree - pulling
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from django.utils.translation import ugettext_lazy as _ from parler.admin import TranslatableTabularInline from adminsortable.admin import SortableTabularInline from cms.admin.placeholderadmin import PlaceholderAdminMixin from allink_cor...
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from parler.admin import TranslatableTabularInline from adminsortable.admin import SortableTabularInline from cms.admin.placeholderadmin import PlaceholderAdminMixin from allink_core.allink_base.admin import AllinkBaseAdminSortable from...
Add dummy class to test generate_ordinates
# -*- coding: utf-8 -*- import datac import numpy as np import os params = {"temp_sun": 6000.} bandgaps = np.linspace(0, 3.25, 100) abscissae = datac.generate_abscissae(bandgaps, "bandgap", params) pwd = os.getcwd() testdir = "test" filename = "data.dat" fqpn = os.path.join(pwd, testdir, filename) datac.write_json(f...
# -*- coding: utf-8 -*- import datac import numpy as np import os import unittest class dummyclass(object): """ Simple class for testing `generate_ordinates` """ def __init__(self, params): pass def fun(self): """ Return value of `True` """ return True par...
Index should be ones without a category.
from django.http import Http404 from django.views.generic import ListView, DetailView from faq.models import Question, Category class FAQQuestionListView(ListView): context_object_name = "question_list" template_name = "faq/question_list.html" def get_queryset(self): return Question.objects.all() class FAQQ...
from django.http import Http404 from django.views.generic import ListView, DetailView from faq.models import Question, Category class FAQQuestionListView(ListView): context_object_name = "question_list" template_name = "faq/question_list.html" def get_queryset(self): return Question.objects.filter(categories...
Make es-index-data command use multiprocess indexing.
from pyramid.paster import get_app import logging from webtest import TestApp index = 'encoded' EPILOG = __doc__ def run(app, collections=None, record=False): environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': 'INDEXER', } testapp = TestApp(app, environ) testapp.post_json(...
from pyramid.paster import get_app import logging from webtest import TestApp index = 'encoded' EPILOG = __doc__ def run(app, collections=None, record=False): environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': 'INDEXER', } testapp = TestApp(app, environ) testapp.post_json(...
Fix syntax error, missing ')'
import sys fai = sys.argv[1] chunk_size = int(sys.argv[2]) overlap = 150 # Base pairs with open(fai, 'r') as infile: for line in infile: name = line.split('\t')[0] stop = int(line.split('\t')[1]) start = 1 while start < stop: start = max(1, start - overlap)...
import sys fai = sys.argv[1] chunk_size = int(sys.argv[2]) overlap = 150 # Base pairs with open(fai, 'r') as infile: for line in infile: name = line.split('\t')[0] stop = int(line.split('\t')[1]) start = 1 while start < stop: start = max(1, start - overlap)...
Add search based on school name
from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields lis...
from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields sea...
Fix some base64 auth keys are not captured by url
from django.conf.urls import url from .views import serve_report urlpatterns = [ url( r'^view/(?P<auth_key>[\w:]+)/(?P<file_path>.*)', serve_report, name='serve_report' ), ]
from django.conf.urls import url from .views import serve_report urlpatterns = [ url( r'^view/(?P<auth_key>[\w:-]+)/(?P<file_path>.*)', serve_report, name='serve_report' ), ]
Fix Django version check for 1.10
# -*- encoding: utf-8 -*- from django import get_version from django.test import TestCase from django.core.management import call_command if get_version().split('.') >= ['1', '7']: from django.test import override_settings from django.apps import apps initial_data_fixture = 'initial_data_modern' clear...
# -*- encoding: utf-8 -*- import django from django.test import TestCase from django.core.management import call_command if django.VERSION >= (1, 7): from django.test import override_settings from django.apps import apps initial_data_fixture = 'initial_data_modern' clear_app_cache = apps.clear_cache e...
Increment version after unit testing refactoring
""" :mod:`zsl` -- zsl module ======================== Main service module. :platform: Unix, Windows :synopsis: The Atteq Service Layer. Service for exposing data to clients. Just provides DB access, feeds access and \ other various aspects of service applications. .. moduleauthor:: Martin Babka <babka@atte...
""" :mod:`zsl` -- zsl module ======================== Main service module. :platform: Unix, Windows :synopsis: The Atteq Service Layer. Service for exposing data to clients. Just provides DB access, feeds access and \ other various aspects of service applications. .. moduleauthor:: Martin Babka <babka@atte...
Add search options for images, reorder field listing, use field names in list display rather than properties.
from django.contrib import admin from icekit.utils.admin.mixins import ThumbnailAdminMixin from . import models class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin): list_display = ['description', 'title', 'thumbnail'] list_display_links = ['description', 'thumbnail'] filter_horizontal = ['categories...
from django.contrib import admin from icekit.utils.admin.mixins import ThumbnailAdminMixin from . import models class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin): list_display = ['thumbnail', 'alt_text', 'title', ] list_display_links = ['alt_text', 'thumbnail'] filter_horizontal = ['categories', ]...
Add XNAT_CFG env var to config list.
import os __all__ = ['default_configuration'] def default_configuration(): """ Returns the XNAT configuration file location determined as the first file found in the following precedence order: 1. ``xnat.cfg`` in the home ``.xnat`` subdirectory 2. ``xnat.cfg`` in the home directory ...
import os __all__ = ['default_configuration'] def default_configuration(): """ Returns the XNAT configuration file location determined as the first file found in the following precedence order: 1. The ``XNAT_CFG`` environment variable, if it is set. 1. ``xnat.cfg`` in the current workin...
Make sure test setup is run for subdirectories
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Openstack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/...
Apply pre-commit changes: Resolve conflicts
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail optional autofollow", "summary": """ Choose if you want to automatically add new recipients as followers on mail.compose.message""", "author": "ACSONE SA/NV...
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail optional autofollow", "summary": """ Choose if you want to automatically add new recipients as followers on mail.compose.message""", "author": "ACSONE SA/NV...
Allow strike time to be blank.
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = m...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Order(models.Model): user = models.ForeignKey(User) # Last updated timestamp, used for sorting date = models.DateTimeField(auto_now_add=True, auto_now=True) # When we will strike striketime = m...
Remove spaces in function named arguments
# -*- coding: utf-8 -*- """ Flask app initialization. """ import os.path from flask import Flask MAIN_DATA_CSV = os.path.join( os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'sample_data.csv' ) app = Flask(__name__) # pylint: disable=invalid-name app.config.update( DEBUG = True, DATA_CSV = M...
# -*- coding: utf-8 -*- """ Flask app initialization. """ import os.path from flask import Flask MAIN_DATA_CSV = os.path.join( os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'sample_data.csv' ) app = Flask(__name__) # pylint: disable=invalid-name app.config.update( DEBUG=True, DATA_CSV=MAIN_...
Revert "Wrap fact exports in quotes"
#!/usr/bin/env python """ stack-builder.hiera_config ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module will read metadata set during instance launch and override any yaml under the /etc/puppet/data directory (except data_mappings) that has a key matching the metadata """ import yaml import os hiera_dir ...
#!/usr/bin/env python """ stack-builder.hiera_config ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module will read metadata set during instance launch and override any yaml under the /etc/puppet/data directory (except data_mappings) that has a key matching the metadata """ import yaml import os hiera_dir ...
Fix incorrect search on activity fields
# -*- coding: utf-8 """ ain7/organizations/filters.py """ # # Copyright © 2007-2016 AIn7 Devel Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or...
# -*- coding: utf-8 """ ain7/organizations/filters.py """ # # Copyright © 2007-2016 AIn7 Devel Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or...
Clean method for dict ds
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self...
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self...
Change the version to tag it.
from setuptools import setup setup( name = 'upstox', packages = ['upstox_api'], version = '1.5.2', include_package_data=True, description = 'Official Python library for Upstox APIs', author = 'Upstox Development Team', author_email = 'support@upstox.com', url = 'https://github.com/upstox/upstox-python',...
from setuptools import setup setup( name = 'upstox', packages = ['upstox_api'], version = '1.5.3', include_package_data=True, description = 'Official Python library for Upstox APIs', author = 'Upstox Development Team', author_email = 'support@upstox.com', url = 'https://github.com/upstox/upstox-python',...
Make sure ext.csrf is installed with WTForms
import os, sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from distutils.core import setup import wtforms setup( name='WTForms', version=wtforms.__version__, url='http://wtforms.simplecodes.com/', license='BSD', author='Thomas Johansson, James Crasta', author_email='wtforms...
import os, sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from distutils.core import setup import wtforms setup( name='WTForms', version=wtforms.__version__, url='http://wtforms.simplecodes.com/', license='BSD', author='Thomas Johansson, James Crasta', author_email='wtforms...
Remove history from long description
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', '') setup( name='gnsq', version='1.0.0', description='...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() setup( name='gnsq', version='1.0.0', description='A gevent based python client for NSQ.', long_description=readme, long_description_content_type='tex...
Make sure any config overrides are reset
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Change Planning to Pre Alpha
#!/usr/bin/env python from setuptools import setup, find_packages def install(): setup( name='dogu', version='1.0', license='MIT', description='Dogu server, Implementation of dogu interace', long_description='Dogu server, Implementation of dogu interace', author='L...
#!/usr/bin/env python from setuptools import setup, find_packages def install(): setup( name='dogu', version='1.0', license='MIT', description='Dogu server, Implementation of dogu interace', long_description='Dogu server, Implementation of dogu interace', author='L...
Change name of module made by cython to rk4cython to test.
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy import configuration ext_modules = [Extension("sourceterm.srccython", ["sourceterm/srccython.pyx"], extra_compile_args=["-g"], extra_link_args=["-g"], ...
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy import configuration ext_modules = [Extension("sourceterm.srccython", ["sourceterm/srccython.pyx"], extra_compile_args=["-g"], extra_link_args=["-g"], ...
Add 'Systems Administration' to the list of project classifiers
from setuptools import setup, find_packages from suponoff import __version__ as version if __name__ == '__main__': with open("README.rst") as f: long_description = f.read() setup( name="suponoff", version=version, author="Gambit Research", author_email="opensource@gambi...
from setuptools import setup, find_packages from suponoff import __version__ as version if __name__ == '__main__': with open("README.rst") as f: long_description = f.read() setup( name="suponoff", version=version, author="Gambit Research", author_email="opensource@gambi...
Add python shebang and change file mode to executable
# run.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 0.0.0 from app import app if __name__ == "__main__": # run the application app.run(debug=app.config['DEBUG'])
#!/usr/bin/env python # run.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 0.0.0 from app import app if __name__ == "__main__": # run the application app.run(debug=app.config['DEBUG'])
Add a fuzz call for SBCommunication: obj.connect(None).
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) ...
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) ...
Add label in error message
import pprint import sublime import json from .util import Util # for debug pp = pprint.PrettyPrinter(indent=4) class Base(object): def settings(self, attr): settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings')) user_settings = json.loads(su...
import pprint import sublime import json from .util import Util # for debug pp = pprint.PrettyPrinter(indent=4) class Base(object): def settings(self, attr): settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings')) user_settings = json.loads(su...
Fix map resolving to empty list on Python 3.
# The supported extensions, as defined by https://github.com/github/markup supported_extensions = ['.md', '.markdown'] # The default filenames when no file is provided default_filenames = map(lambda ext: 'README' + ext, supported_extensions)
# The supported extensions, as defined by https://github.com/github/markup supported_extensions = ['.md', '.markdown'] # The default filenames when no file is provided default_filenames = ['README' + ext for ext in supported_extensions]
Convert squashed migration to regular migration
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.gis.db.models.fields class Migration(migrations.Migration): replaces = [('addressbase', '0001_initial'), ('addressbase', '0002_auto_20160611_1700'), ('addressbase', '0003_auto_20160611_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.gis.db.models.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Address', fields=[ ...
Remove unecessary code in cache backend _set
# -*- coding: utf-8 -*- class BaseCacheBackend(object): def get(self, thumbnail_name): if isinstance(thumbnail_name, list): thumbnail_name = ''.join(thumbnail_name) return self._get(thumbnail_name) def set(self, thumbnail): thumbnail_name = thumbnail.name if isins...
# -*- coding: utf-8 -*- class BaseCacheBackend(object): def get(self, thumbnail_name): if isinstance(thumbnail_name, list): thumbnail_name = ''.join(thumbnail_name) return self._get(thumbnail_name) def set(self, thumbnail): return self._set(thumbnail.name, thumbnail) ...
Fix version comparison of Werkzeug.
""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._interna...
""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry,...
Create assert true in teste_view
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retor...
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Test...
Add two lists with square and grain numbers
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains...
Set values in a single query
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1)
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
Add query capture in flask.
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store():...
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store():...
Work with custom user models in django >= 1.5
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model Us...
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model Us...
Fix missing import and bad query for screenshots
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=Tru...
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: retu...
Fix installation of numarray headers on Windows.
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ...
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ...
Disable linter in in-progress code
def upload(upload_info): """ :type upload_info: dict """ client_id = upload_info['client_id'] resource_id = upload_info['resource_id'] resource_type = upload_info['resource_type'] raise NotImplementedError def download(client_id): """ :type client_id: str :rtype dict """...
def upload(upload_info): """ :type upload_info: dict """ client_id = upload_info['client_id'] # noqa: F841 resource_id = upload_info['resource_id'] # noqa: F841 resource_type = upload_info['resource_type'] # noqa: F841 raise NotImplementedError def download(client_id): # noqa: F841 ...
Raise error if any in IPythonParallelRunner.wait_tasks
""" Task runner using IPython parallel interface. See `The IPython task interface`_ and `IPython Documentation`_ in `IPython Documentation`_. .. _The IPython task interface: http://ipython.org/ipython-doc/dev/parallel/parallel_task.html .. _DAG Dependencies: http://ipython.org/ipython-doc/dev/parallel/dag_depe...
""" Task runner using IPython parallel interface. See `The IPython task interface`_ and `IPython Documentation`_ in `IPython Documentation`_. .. _The IPython task interface: http://ipython.org/ipython-doc/dev/parallel/parallel_task.html .. _DAG Dependencies: http://ipython.org/ipython-doc/dev/parallel/dag_depe...