Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix in tests for terminal definitions.
import pytest from parglare import Grammar from parglare.exceptions import GrammarError def test_terminal_nonterminal_conflict(): # Production A is a terminal ("a") and non-terminal at the same time. g = """ A = "a" | B; B = "b"; """ try: Grammar.from_string(g) assert False ...
import pytest from parglare import Grammar def test_terminal_nonterminal(): # Production A is a terminal ("a") and non-terminal at the same time. # Thus, it must be recognized as non-terminal. g = """ S = A B; A = "a" | B; B = "b"; """ Grammar.from_string(g) # Here A shoud be non...
Add test to make sure certain classes are always found in cc.license, no matter where they are internally.
"""Tests for functionality within the cc.license module. This file is a catch-all for tests with no place else to go.""" import cc.license def test_locales(): locales = cc.license.locales() for l in locales: assert type(l) == unicode for c in ('en', 'de', 'he', 'ja', 'fr'): assert c in ...
"""Tests for functionality within the cc.license module. This file is a catch-all for tests with no place else to go.""" import cc.license def test_locales(): locales = cc.license.locales() for l in locales: assert type(l) == unicode for c in ('en', 'de', 'he', 'ja', 'fr'): assert c in ...
Fix aio RPC error extraction
# -*- coding: utf-8 -*- import asyncio import websockets import logging import json from jsonrpcclient.clients.websockets_client import WebSocketsClient from .rpc import Rpc log = logging.getLogger(__name__) class Websocket(Rpc): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
# -*- coding: utf-8 -*- import asyncio import websockets import logging import json from jsonrpcclient.clients.websockets_client import WebSocketsClient from jsonrpcclient.exceptions import ReceivedErrorResponseError from .rpc import Rpc log = logging.getLogger(__name__) class Websocket(Rpc): def __init__(self...
Refactor some redundancy in the views tests
from django.test import TestCase from django.http import HttpRequest from campaigns.views import create_campaign from campaigns.models import Campaign from campaigns.forms import CampaignForm class HomePageTest(TestCase): def test_does_root_url_resolves_the_home_page(self): called = self.client.get('/') self.ass...
from django.test import TestCase from django.http import HttpRequest from campaigns.views import create_campaign from campaigns.models import Campaign from campaigns.forms import CampaignForm def make_POST_request(titleValue, descriptionValue): request = HttpRequest() request.method = 'POST' request.POST['title'] =...
Add a test for stdio.h.
import unittest import sys from ctypeslib import h2xml, xml2py class ToolchainTest(unittest.TestCase): if sys.platform == "win32": def test(self): h2xml.main(["h2xml", "-q", "-D WIN32_LEAN_AND_MEAN", "-D _UNICODE", "-D UNICODE", ...
import unittest import sys from ctypeslib import h2xml, xml2py class ToolchainTest(unittest.TestCase): if sys.platform == "win32": def test_windows(self): h2xml.main(["h2xml", "-q", "-D WIN32_LEAN_AND_MEAN", "-D _UNICODE", "-D UNICODE", ...
Handle the fact that to_check is a set
import logging import mothermayi.errors import mothermayi.files import subprocess LOGGER = logging.getLogger(__name__) def plugin(): return { 'name' : 'pylint', 'pre-commit' : pre_commit, } def pre_commit(config, staged): pylint = config.get('pylint', {}) args = pylint.g...
import logging import mothermayi.errors import mothermayi.files import subprocess LOGGER = logging.getLogger(__name__) def plugin(): return { 'name' : 'pylint', 'pre-commit' : pre_commit, } def pre_commit(config, staged): pylint = config.get('pylint', {}) args = pylint.g...
Rework commented out code a tad
# Copyright 2013 IBM Corporation # All rights reserved # This is the main application. # It should check for existing UDP socket to negotiate socket listen takeover # It will have three paths into it: # -Unix domain socket # -TLS socket # -WSGI # Additionally, it will be able to receive particular UDP packets to...
# Copyright 2013 IBM Corporation # All rights reserved # This is the main application. # It should check for existing UDP socket to negotiate socket listen takeover # It will have three paths into it: # -Unix domain socket # -TLS socket # -WSGI # Additionally, it will be able to receive particular UDP packets to...
Test for RegexURLPattern.callback on Django 1.10
from __future__ import absolute_import, unicode_literals from functools import update_wrapper def decorate_urlpatterns(urlpatterns, decorator): for pattern in urlpatterns: if hasattr(pattern, 'url_patterns'): decorate_urlpatterns(pattern.url_patterns, decorator) if hasattr(pattern, '...
from __future__ import absolute_import, unicode_literals from functools import update_wrapper from django import VERSION as DJANGO_VERSION def decorate_urlpatterns(urlpatterns, decorator): """Decorate all the views in the passed urlpatterns list with the given decorator""" for pattern in urlpatterns: ...
Fix the security for the merge after closing memberships
# Copyright 2022 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class BasePartnerMergeAutomaticWizard(models.TransientModel): _inherit = "base.partner.merge.automatic.wizard" def _merge(self, partner_ids, dst_partner=None, extra_checks=True): ...
# Copyright 2022 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class BasePartnerMergeAutomaticWizard(models.TransientModel): _inherit = "base.partner.merge.automatic.wizard" def _merge(self, partner_ids, dst_partner=None, extra_checks=True): ...
Add license to module init file.
""" Zipline """ # This is *not* a place to dump arbitrary classes/modules for convenience, # it is a place to expose the public interfaces. __version__ = "0.5.11.dev" from . import data from . import finance from . import gens from . import utils from . algorithm import TradingAlgorithm __all__ = [ 'data', ...
# # Copyright 2013 Quantopian, 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 wr...
Read appengine refresh_token from oauth file automatically.
from fabric.api import * from fabric.contrib.console import confirm cfg = dict( appengine_dir='appengine-web/src', goldquest_dir='src', appengine_token='', ) def update(): # update to latest code from repo local('git pull') def test(): local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" %...
from fabric.api import * from fabric.contrib.console import confirm import simplejson cfg = dict( appengine_dir='appengine-web/src', goldquest_dir='src', oauth_cfg_path='/Users/olle/.appcfg_oauth2_tokens', appengine_refresh_token='', ) def read_appcfg_oauth(): fp = open(cfg['oauth_cfg_path']) ...
Add unittest account and password
# -*- coding: utf-8 -*- #DEBUG = True SECRET_KEY = "change secret key in production" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True #PERMANENT_SESSION_LIFETIME = timedelta(minutes=10)
# -*- coding: utf-8 -*- import os #DEBUG = True SECRET_KEY = "change secret key in production" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True #PERMANENT_SESSION_LIFETIME = timedelta(minutes=10) UNITTEST_USERNAME = os.environ.get('USERNAME', '') UNITTEST_PASSWORD = os.environ.get('PASSWORD', '')
Allow specification of GALAPAGOS bands
# coding: utf-8 def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd import re ...
# coding: utf-8 def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits', out_filename=None, bands='RUGIZYJHK'): """Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file""" from astropy.io import fits import pandas as pd...
Support a range of redis client versions
import os import re from setuptools import ( find_packages, setup, ) version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]") def get_version(): base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'curator/__init__.py')) as initf: for line in initf: ...
import os import re from setuptools import ( find_packages, setup, ) version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]") def get_version(): base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'curator/__init__.py')) as initf: for line in initf: ...
Maintain alphabetical order in `install_requires`
# Copyright 2021 DeepMind Technologies Limited # # 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 agr...
# Copyright 2021 DeepMind Technologies Limited # # 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 agr...
Add logging for NJ TRANSIT login status
"""Fetch NJ TRANSIT bus and rail feeds. Requires username and password to log in first. Cannot check for whether a feed is new or not, so only call to fetch this one once an email is sent to the developer account saying new feeds are available. """ import logging import requests from FeedSource import FeedSource L...
"""Fetch NJ TRANSIT bus and rail feeds. Requires username and password to log in first. Cannot check for whether a feed is new or not, so only call to fetch this one once an email is sent to the developer account saying new feeds are available. """ import logging import requests from FeedSource import FeedSource L...
Disable use tracking of all heartbeat app urls.
from .models import Session class Tracking(object): """The default tracking middleware logs all successful responses as a 'visit' variable with the URL path as its value.""" def process_response(self, request, response): if response.status_code == 200: session = Session.objects.for_re...
from .models import Session class Tracking(object): """The default tracking middleware logs all successful responses as a 'visit' variable with the URL path as its value.""" def process_response(self, request, response): if request.path.startswith('/heartbeat/'): return response ...
Switch trunk to 1.4.1, now that the 1.4.0 release branch is branched out
import gettext class Version(object): def __init__(self, canonical_version, final): self.canonical_version = canonical_version self.final = final @property def pretty_version(self): if self.final: return self.canonical_version else: return '%s-dev' ...
import gettext class Version(object): def __init__(self, canonical_version, final): self.canonical_version = canonical_version self.final = final @property def pretty_version(self): if self.final: return self.canonical_version else: return '%s-dev' ...
Send partial LogRecord event in extra ata
from __future__ import division, print_function, absolute_import import logging import bugsnag class BugsnagHandler(logging.Handler): def __init__(self, api_key=None): super(BugsnagHandler, self).__init__() # Check if API key has been specified. if not bugsnag.configuration.api_key and no...
from __future__ import division, print_function, absolute_import import logging import bugsnag class BugsnagHandler(logging.Handler): def __init__(self, api_key=None): super(BugsnagHandler, self).__init__() # Check if API key has been specified. if not bugsnag.configuration.api_key and no...
Create some shims for py3k
import os import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, ...
import os import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, ...
Remove version from Build filter.
from django.utils.translation import ugettext_lazy as _ import django_filters from builds import constants from builds.models import Build, Version ANY_REPO = ( ('', _('Any')), ) BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES class VersionFilter(django_filters.FilterSet): project = django_filters.CharFil...
from django.utils.translation import ugettext_lazy as _ import django_filters from builds import constants from builds.models import Build, Version ANY_REPO = ( ('', _('Any')), ) BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES class VersionFilter(django_filters.FilterSet): project = django_filters.CharFil...
Add criteria weighting 100% total validation
from flask import abort from .models import Service from .validation import get_validation_errors from .service_utils import filter_services def validate_brief_data(brief, enforce_required=True, required_fields=None): errs = get_validation_errors( 'briefs-{}-{}'.format(brief.framework.slug, brief.lot.slu...
from flask import abort from .models import Service from .validation import get_validation_errors from .service_utils import filter_services def validate_brief_data(brief, enforce_required=True, required_fields=None): errs = get_validation_errors( 'briefs-{}-{}'.format(brief.framework.slug, brief.lot.slu...
Add optimizer to the API
from .io import preprocess from .train import train from .network import mlp def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True, mask=None, type='normal', activation='relu', testset=False, learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0., epo...
from .io import preprocess from .train import train from .network import mlp def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True, mask=None, type='normal', activation='relu', testset=False, learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0., epo...
Stop cassandra from deleting documents, delete documents from old index as well
import logging from scripts.util import documents from scrapi import settings from scrapi.linter import RawDocument from scrapi.processing.elasticsearch import es from scrapi.tasks import normalize, process_normalized, process_raw logger = logging.getLogger(__name__) def rename(source, target, dry=True): asser...
import logging from scripts.util import documents from scrapi import settings from scrapi.linter import RawDocument from scrapi.processing.elasticsearch import es from scrapi.tasks import normalize, process_normalized, process_raw logger = logging.getLogger(__name__) def rename(source, target, dry=True): asser...
Fix - Apache error AH02429
# -*- coding: utf-8 -*- import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) tr...
# -*- coding: utf-8 -*- import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) tr...
Fix failure on Django < 1.4.5
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # Django >= 1.4.5 from django.utils.encoding import force_bytes, force_text, smart_text # NOQA from django.utils.six import string_types, text_type, binary_type # NOQA except ImportError: # pragma: no cover # Django < 1.4.5 fr...
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # Django >= 1.4.5 from django.utils.encoding import force_bytes, force_text, smart_text # NOQA from django.utils.six import string_types, text_type, binary_type # NOQA except ImportError: # pragma: no cover # Django < 1.4.5 fr...
Update the default value for the placeholder
import betamax import os with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'once' if os.environ.get('TRAVIS_GH3'): record_mode = 'never' config.default_cassette_options['record_mode'] = record_mode config.define_cassette_placeholder( ...
import betamax import os with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'once' if os.environ.get('TRAVIS_GH3'): record_mode = 'never' config.default_cassette_options['record_mode'] = record_mode config.define_cassette_placeholder( ...
Use the correct user ID to show the user from the profiles view. Fixes %61.
from signbank.registration.models import * from django.contrib import admin from django.core.urlresolvers import reverse class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials'] readonly_fields = ['user...
from signbank.registration.models import * from django.contrib import admin from django.core.urlresolvers import reverse class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'permissions', 'best_describes_you', 'australian', 'auslan_user', 'deaf', 'researcher_credentials'] readonly_fields = ['user...
Use mkdir instead of makedirs because we don't need parent directories made
from os import makedirs from os.path import abspath, dirname, exists, join from shutil import rmtree from tvrenamr.config import Config from tvrenamr.main import TvRenamr from tvrenamr.tests import urlopenmock class BaseTest(object): files = 'tests/files' def setup(self): # if `file` isn't there, ma...
from os import mkdir from os.path import abspath, dirname, exists, join from shutil import rmtree from tvrenamr.config import Config from tvrenamr.main import TvRenamr from tvrenamr.tests import urlopenmock class BaseTest(object): files = 'tests/files' def setup(self): # if `file` isn't there, make ...
Sort by kq too when returning peer review assignments
# Copyright 2013 Rooter Analysis S.L. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
# Copyright 2013 Rooter Analysis S.L. # # 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...
Use distributed flag for xfail test
import qnd import tensorflow as tf def model_fn(x, y): return (y, 0.0, tf.contrib.framework.get_or_create_global_step().assign_add()) def input_fn(q): shape = (100,) return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32) train_and_evaluate = qnd.def_train_and_evaluate() ...
import qnd import tensorflow as tf def model_fn(x, y): return (y, 0.0, tf.contrib.framework.get_or_create_global_step().assign_add()) def input_fn(q): shape = (100,) return tf.zeros(shape, tf.float32), tf.ones(shape, tf.int32) train_and_evaluate = qnd.def_train_and_evaluate(dis...
Rename photo endpoint to submission
""".. Ignore pydocstyle D400. ============= Core API URLs ============= The ``routList`` is ment to be included in ``urlpatterns`` with the following code: .. code-block:: python from rest_framework import routers from rolca.core.api import urls as core_api_urls route_lists = [ core_api_urls.r...
""".. Ignore pydocstyle D400. ============= Core API URLs ============= The ``routList`` is ment to be included in ``urlpatterns`` with the following code: .. code-block:: python from rest_framework import routers from rolca.core.api import urls as core_api_urls route_lists = [ core_api_urls.r...
Add a model property to tell if credentials have expired
from django.db import models from django.contrib.auth.models import User import datetime def default_expiry_time(): return datetime.datetime.now() + datetime.timedelta(days=1) def random_string(): return User.objects.make_random_password(16) class Credentials(models.Model): "Keeps track of issued MAC credentia...
from django.db import models from django.contrib.auth.models import User import datetime def default_expiry_time(): return datetime.datetime.now() + datetime.timedelta(days=1) def random_string(): return User.objects.make_random_password(16) class Credentials(models.Model): "Keeps track of issued MAC credentia...
Add a hack to auto-inject new deps
from urllib.parse import urljoin from urllib.request import urlopen from urllib.error import URLError import sys GITHUB_USERS = [('Polymer', '0.5.2')] def resolve_missing_user(user, branch, package): assets = ["{}.html".format(package), "{}.css".format(package), "{}.js".format(package...
from urllib.parse import urljoin from urllib.request import urlopen from urllib.error import URLError import sys ENORMOUS_INJECTION_HACK = False GITHUB_USERS = [('Polymer', '0.5.2')] def resolve_missing_user(user, branch, package): assets = ["{}.html".format(package), "{}.css".format(package), ...
Fix typo XCRun -> xcrun
# test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for ...
# test_xcrun.py - Unit tests for swift_build_support.xcrun -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for ...
Add abstract method exceptions to make Animation inheritance easier
# TBD: Some animations mutate a pattern: shift it, fade it, etc. # Not all animations need a pattern # I need a rainbow pattern for fun # TBD: How do you do random pixels? is it a pattern that is permuted by the # animation? YES; patterns are static, animations do things with patterns, # rotate them, scramble them, sc...
# TBD: Some animations mutate a pattern: shift it, fade it, etc. # Not all animations need a pattern # I need a rainbow pattern for fun # TBD: How do you do random pixels? is it a pattern that is permuted by the # animation? YES; patterns are static, animations do things with patterns, # rotate them, scramble them, sc...
Switch to generating REST end points from docker image
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import( genRESTEndPointsForSlicerCLIsInSubDirs, genRESTEndPointsForSlicerCLIsInDocker ) _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsR...
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import( genRESTEndPointsForSlicerCLIsInSubDirs, genRESTEndPointsForSlicerCLIsInDocker ) _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsR...
Update the 503 error message.
import httpx from linguee_api.downloaders.interfaces import DownloaderError, IDownloader class HTTPXDownloader(IDownloader): """ Real downloader. Sends request to linguee.com to read the page. """ async def download(self, url: str) -> str: async with httpx.AsyncClient() as client: ...
import httpx from linguee_api.downloaders.interfaces import DownloaderError, IDownloader ERROR_503 = ( "The Linguee server returned 503. The API proxy was temporarily blocked by " "Linguee. For more details, see https://github.com/imankulov/linguee-api#" "the-api-server-returns-the-linguee-server-returned...
Convert everything to unicode strings before inserting to DB
#-*- coding: utf-8 -*- from email.MIMEBase import MIMEBase from django.core.mail.backends.base import BaseEmailBackend from database_email_backend.models import Email, Attachment class DatabaseEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): if not email_messages: retur...
#-*- coding: utf-8 -*- from email.MIMEBase import MIMEBase from django.core.mail.backends.base import BaseEmailBackend from database_email_backend.models import Email, Attachment class DatabaseEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): if not email_messages: retur...
Use only msecs of dacapo output.
import re BENCHMARKS = set(( 'avrora' , 'batik' , 'eclipse' , 'fop' , 'h2' , 'jython' , 'luindex' , 'lusearch' , 'pmd' , 'sunflow' ...
import re BENCHMARKS = set(( 'avrora' , 'batik' , 'eclipse' , 'fop' , 'h2' , 'jython' , 'luindex' , 'lusearch' , 'pmd' , 'sunflow' ...
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) class Meta: unique_together = (('app_name', 'migration'),) @classmethod def for_migrat...
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration): try: return cls.objects.get(app...
Reword the permissions for Disqus
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
Allow Jenkins to actually report build failures
"""Python script to run all tests""" import pytest if __name__ == '__main__': pytest.main()
"""Python script to run all tests""" import sys import pytest if __name__ == '__main__': sys.exit(pytest.main())
Change API url prefix to 'v2'
from django.conf import settings from django.conf.urls import include, url # from django.contrib import admin from django.conf.urls.static import static from . import views urlpatterns = [ ### API ### url(r'^$', views.root), url(r'^nodes/', include('api.nodes.urls', namespace='nodes')), url(r'^users...
from django.conf import settings from django.conf.urls import include, url, patterns # from django.contrib import admin from django.conf.urls.static import static from . import views urlpatterns = [ ### API ### url(r'^v2/', include(patterns('', url(r'^$', views.root), url(r'^nodes/', include...
Make use of Django's hashcompat module.
from django.conf import settings def generate_secret_delimiter(): try: from hashlib import sha1 except ImportError: from sha import sha as sha1 return sha1(getattr(settings, 'SECRET_KEY', '')).hexdigest() LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter(...
from django.conf import settings from django.utils.hashcompat import sha_constructor def generate_secret_delimiter(): return sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest() LITERAL_DELIMITER = getattr(settings, 'LITERAL_DELIMITER', generate_secret_delimiter())
Create new model for debts and loans
from django.contrib.auth.models import User from django.db import models from django.db.models import fields from django.utils import timezone class Transaction(models.Model): EXPENSE = 'exp' INCOME = 'inc' CATEGORY_CHOICES = ( (EXPENSE, 'expense'), (INCOME, 'income'), ) title = f...
from django.contrib.auth.models import User from django.db import models from django.db.models import fields from django.utils import timezone class Transaction(models.Model): EXPENSE = 'exp' INCOME = 'inc' CATEGORY_CHOICES = ( (EXPENSE, 'expense'), (INCOME, 'income'), ) title = f...
Patch out DNS resolver in makeService tests.
from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker from vumi_http_proxy import http_proxy from twisted.trial import unittest class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], ...
from vumi_http_proxy.servicemaker import ( Options, ProxyWorkerServiceMaker, client) from vumi_http_proxy import http_proxy from twisted.trial import unittest from vumi_http_proxy.test import helpers class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.par...
Update user details API call
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SE...
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SE...
Add a DICT_TYPES variable so we can do isinstance() checks against all the builtin dict-like objects
try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict
import collections from six.moves import UserDict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict # Users can pass in objects that subclass a few different objects # More specifically, rasterio has a CRS() class that subclasses UserDict() # In Python 2 User...
Add a comment to make some sense of a regex
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of).""" import re import iati.constants class Version(object): """Representation of an IATI Standard Version Number.""" def __init__(self, version_string): """Initialise a Version Number. ...
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of).""" import re import iati.constants class Version(object): """Representation of an IATI Standard Version Number.""" def __init__(self, version_string): """Initialise a Version Number. ...
Add Python portability to model
from django.db import models class Todo(models.Model): """ Todo Model: name, description, created """ name = models.CharField(max_length=100, unique=True) description = models.TextField() created = models.DateTimeField() def __unicode__(self): return self.name
from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Todo(models.Model): """ Todo Model: name, description, created """ name = models.CharField(max_length=100, unique=True) description = models.TextField() created = model...
Remove pointless default values from DefaultConfiguration
from datetime import timedelta class DefaultConfiguration: DEBUG = False MAIL_SERVER = "localhost" MAIL_PORT = 25 MAIL_USER = None MAIL_PASSWORD = None MAIL_CAFILE = None INVITATION_SUBJECT = "Invitation to join the FSFW!" TOKEN_BYTES = 5 TOKEN_LIFETIME = timedelta(days=7) L...
from datetime import timedelta class DefaultConfiguration: DEBUG = False MAIL_SERVER = "localhost" MAIL_PORT = 25 MAIL_USER = None MAIL_PASSWORD = None MAIL_CAFILE = None INVITATION_SUBJECT = "Invitation to join the FSFW!" TOKEN_BYTES = 5 TOKEN_LIFETIME = timedelta(days=7) L...
Add multi-languages support for search
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET....
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.utils.translation import get_language_from_request from molo.core.utils import get_locale_code from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wa...
Use the gallery_image method for required information
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimoc...
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimoc...
Add tests for userprofile properties
""" Tests for opal.models.UserProfile """ from django.test import TestCase from django.contrib.auth.models import User from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserP...
""" Tests for opal.models.UserProfile """ from django.contrib.auth.models import User from django.test import TestCase from mock import patch from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() s...
Send api-key through HTTP cookie.
import urllib __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClientOpener(urllib.FancyURLopener): version = __user_agent__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/...
import urllib import urllib2 __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_k...
Use python3 for test_docstring_optimization_compat subprocess
import subprocess import pytest from statsmodels.compat.platform import PLATFORM_WIN from statsmodels.compat.scipy import SCIPY_11 def test_lazy_imports(): # Check that when statsmodels.api is imported, matplotlib is _not_ imported cmd = ("import statsmodels.api as sm; " "import sys; " ...
import subprocess import pytest from statsmodels.compat.platform import PLATFORM_WIN from statsmodels.compat.scipy import SCIPY_11 def test_lazy_imports(): # Check that when statsmodels.api is imported, matplotlib is _not_ imported cmd = ("import statsmodels.api as sm; " "import sys; " ...
Include colons in URL matching
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand...
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand...
Set flash message *after* message sending
# coding: utf-8 from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_cla...
# coding: utf-8 from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_cla...
Test case for tent map time series
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per...
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per...
Update query init file docstring.
# -*- coding: utf-8 -*- """ Initialisation file for query directory. """
# -*- coding: utf-8 -*- """ Initialisation file for query directory, relating to local database queries. """
Revert "Properly handle non-hex characters in MAC"
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddr...
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddr...
Clean up and change cov time
import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * reject = dict(grad=4000e-13, # T / m (gradiometers) mag=4e-12, # T (magnetometers) eeg=180e-6 # ) subject = sys.ar...
import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) epochs.drop_bad_epochs(reject=reject_params) fig = epochs.pl...
Add online project scrape test
import wikibugs import configfetcher import unittest import os p = os.path.split(__file__)[0] class TestWikibugs(unittest.TestCase): def setUp(self): self.bugs = wikibugs.Wikibugs2( configfetcher.ConfigFetcher() ) def test_offline_scrape(self): content = open(p + "/T87834...
# encoding: utf-8 import wikibugs import configfetcher import unittest import os import requests p = os.path.split(__file__)[0] class TestWikibugs(unittest.TestCase): def setUp(self): self.bugs = wikibugs.Wikibugs2( configfetcher.ConfigFetcher() ) def run_scrape(self, content): ...
Connect to database before upgrading it
# Copyright (c) 2013 Mirantis 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 writ...
# Copyright (c) 2013 Mirantis 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 writ...
Use level_tag to be consistent with Django >= 1.7
from django import template from django.contrib.messages.utils import get_level_tags LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns tags for a message """ level_name = LEVEL_TAGS[message.level] if level_name == u"err...
from django import template from django.contrib.messages.utils import get_level_tags LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix along with any tags includ...
Update alembic order for merging
"""empty message Revision ID: 538eeb160af6 Revises: 1727fb4309d8 Create Date: 2015-09-17 04:22:21.262285 """ # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '1727fb4309d8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
"""empty message Revision ID: 538eeb160af6 Revises: 1727fb4309d8 Create Date: 2015-09-17 04:22:21.262285 """ # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '6b9d673d8e30' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
Add unidecode as a dependency
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], autho...
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], autho...
Change repeat command to return a list of the results of the repeated commands
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
Add abstract Broadcast protocol class
from abc import ABCMeta, abstractmethod from enum import Enum class Broadcast(metaclass=ABCMeta): """ An interface for defining a broadcast protocol. The 'propose' and 'decide' methods need to be defined """ class MessageType(Enum): SEND = 1 ECHO = 2 READY = 3 def __i...
Fix failing test through loading of examples from $PWD.
import pylearn2 from pylearn2.utils.serial import load_train_file import os from pylearn2.testing import no_debug_mode from theano import config @no_debug_mode def test_train_example(): """ tests that the grbm_smd example script runs correctly """ assert config.mode != "DEBUG_MODE" path = pylearn2.__p...
import pylearn2 from pylearn2.utils.serial import load_train_file import os from pylearn2.testing import no_debug_mode from theano import config @no_debug_mode def test_train_example(): """ tests that the grbm_smd example script runs correctly """ assert config.mode != "DEBUG_MODE" path = pylearn2.__p...
Add very brief comments about the event types
from collections import defaultdict import traceback LINT_START = 'LINT_START' LINT_RESULT = 'LINT_RESULT' LINT_END = 'LINT_END' listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn): try: listeners[topic].remove(fn) except KeyError: ...
from collections import defaultdict import traceback LINT_START = 'LINT_START' # (buffer_id) LINT_RESULT = 'LINT_RESULT' # (buffer_id, linter_name, errors) LINT_END = 'LINT_END' # (buffer_id) listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn...
Add log error if we run salt-api w/ no config
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is con...
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is con...
Fix script for release file already present case
from __future__ import absolute_import from __future__ import unicode_literals from configparser import Error from requests.exceptions import HTTPError from twine.commands.upload import main as twine_upload from twine.utils import get_config from .utils import ScriptError def pypi_upload(args): print('Uploading...
from __future__ import absolute_import from __future__ import unicode_literals from configparser import Error from requests.exceptions import HTTPError from twine.commands.upload import main as twine_upload from twine.utils import get_config from .utils import ScriptError def pypi_upload(args): print('Uploading...
Rewrite alt_tz as proper fixture. Skip when tzset isn't available.
import datetime import time import contextlib import os from unittest import mock from tempora import timing def test_IntervalGovernor(): """ IntervalGovernor should prevent a function from being called more than once per interval. """ func_under_test = mock.MagicMock() # to look like a funct...
import datetime import time import contextlib import os from unittest import mock import pytest from tempora import timing def test_IntervalGovernor(): """ IntervalGovernor should prevent a function from being called more than once per interval. """ func_under_test = mock.MagicMock() # to loo...
Increase number of Kociemba test iterations to 100
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie import Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c...
from src.Move import Move from src.NaiveCube import NaiveCube from src.Cubie import Cube from src.Solver import Kociemba import timeout_decorator import unittest class TestKociembaSolver(unittest.TestCase): @timeout_decorator.timeout(300) def _test_solution(self, c): solver = Kociemba.KociembaSolver(c...
Add loop to the python example
from gi.repository import Zeitgeist log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None)
from gi.repository import Zeitgeist, Gtk log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None) Gtk.main()
Update tests for nbgrader feedback
from .base import TestBase from nbgrader.api import Gradebook import os class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("Problem Set 1") gb.add_student("foo") gb.add_student("bar") return ...
from .base import TestBase from nbgrader.api import Gradebook import os import shutil class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("ps1") gb.add_student("foo") return dbpath def test_help(...
Change sha fetching to use --parent-only and removed ref parameter
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo, ref): self.git_repo = git_repo self.ref = ref s...
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo): self.git_repo = git_repo self.tempdir = None @con...
Sort by longest path (assuming stdlib stuff will be in the longest).
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SIT...
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SIT...
Add request parameter to backend.authenticate
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end f...
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end f...
Fix Python import path on Travis.
from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
import sys # Hack for Travis, where local imports don't work. if '' not in sys.path: sys.path.insert(0, '') from pelicanconf import * # Over-ride so there is paging. DEFAULT_PAGINATION = 5
Simplify nethack protocol to a single method.
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): data = '{"register": {"...
""" An example client. Run simpleserv.py first before running this. """ import json from twisted.internet import reactor, protocol # a client protocol class EchoClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): self.send_message('auth...
Implement equality check for DraftText nodes
from __future__ import absolute_import, unicode_literals import json from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(self, value, **kwargs): super(DraftText, self)....
from __future__ import absolute_import, unicode_literals import json from django.utils.functional import cached_property from draftjs_exporter.html import HTML from wagtail.wagtailcore.rich_text import RichText from wagtaildraftail.settings import get_exporter_config class DraftText(RichText): def __init__(se...
Update main to run a profiler
import sys from . import BinaryData for filename in sys.argv[1:]: with open(filename) as infile: data = BinaryData(infile.read()) for packet in data.packets(): print hex(packet.key_id), packet.creation_date
import sys import cProfile from . import AsciiData, BinaryData def parsefile(name): with open(name) as infile: if name.endswith('.asc'): data = AsciiData(infile.read()) else: data = BinaryData(infile.read()) counter = 0 for packet in data.packets(): counter ...
Update wording on path of the image.
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), ...
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), ...
Add possibility to debug csv streamer views.
# -*- coding: utf-8 -*- import functools import io from urllib.parse import quote from django.http import StreamingHttpResponse def strip_generator(fn): @functools.wraps(fn) def inner(output, event, generator=False): if generator: # Return the generator object only when using StringIO. ...
# -*- coding: utf-8 -*- import functools import html import io from urllib.parse import quote from django.conf import settings from django.http import HttpResponse, StreamingHttpResponse def strip_generator(fn): @functools.wraps(fn) def inner(output, event, generator=False): if generator: ...
Print command in failure case
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', ...
# A romanesco script to convert a slide to a TIFF using vips. import subprocess import os out_path = os.path.join(_tempdir, out_filename) convert_command = ( 'vips', 'tiffsave', '"%s"' % in_path, '"%s"' % out_path, '--compression', 'jpeg', '--Q', '90', '--tile', '--tile-width', '256', ...
Remove /u/ from username path
import dateutil.parser import datetime import humanize status_view = """\ === Bashhub Status https://bashhub.com/u/{0} Total Commands: {1} Total Sessions: {2} Total Systems: {3} === Session PID {4} Started {5} Commands In Session: {6} Commands Today: {7} """ def build_status_view(model): date = datetime.datetime...
import dateutil.parser import datetime import humanize status_view = """\ === Bashhub Status https://bashhub.com/{0} Total Commands: {1} Total Sessions: {2} Total Systems: {3} === Session PID {4} Started {5} Commands In Session: {6} Commands Today: {7} """ def build_status_view(model): date = datetime.datetime.f...
Update GR API to handle Expat Error
#!/usr/bin/env python import re import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(regex, comment_msg)) def get_book_detail...
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(r...
Document calling with __file__ as starting env path
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): """Recursively load .env files starting from `path` Given the path "foo/bar/.env" and a directory structure like: foo \-...
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): """Recursively load .env files starting from `path` Usage: from your Lambda function, call load_envs with the value __file__ to give...
Change test to check for KeyError instead of IndexError for test_non_item
from hash_table import HashTable import io import pytest words = [] with io.open('/usr/share/dict/words', 'r') as word_file: words = word_file.readlines() def test_init(): ht = HashTable() assert len(ht.table) == 1024 ht2 = HashTable(10000) assert len(ht2.table) == 10000 def test_hash(): ...
from hash_table import HashTable import io import pytest words = [] with io.open('/usr/share/dict/words', 'r') as word_file: words = word_file.readlines() def test_init(): ht = HashTable() assert len(ht.table) == 1024 ht2 = HashTable(10000) assert len(ht2.table) == 10000 def test_hash(): ...
Validate if the file exists (if/else)
#Import dependencies #Load OS functions from the standard library import os os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3') #Change path for the current directory data = open('sketch.txt') #Start iteration over the text file for each_line in data: try: ...
#Import dependencies #Load OS functions from the standard library import os #Change path for the current directory os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3') #Check if file exists if os.path.exists('sketch.txt'): #Load the text file into 'data' variable ...
Fix 500 error when no ID parameter is passed
import json from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse, Http404, HttpResponseBadRequest from django.views.generic.detail import BaseDetailView from .models import Marker class MarkerDetailView(BaseDetailView): """ Simple view for fetching marker details. """...
import json from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse, Http404 from django.views.generic.detail import BaseDetailView from .models import Marker class MarkerDetailView(BaseDetailView): """ Simple view for fetching marker details. """ # TODO: support dif...
Add a context to the fixture translations
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'),...
import json import codecs import tempfile from django.core.management.commands.makemessages import Command as BaseCommand class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'),...
Make long description not point to Travis since can't guarantee tag
from __future__ import absolute_import from setuptools import setup long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg """ setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "seppo....
from __future__ import absolute_import from setuptools import setup long_description="""http://github.com/nanonyme/simplepreprocessor""" setup( name = "simplecpreprocessor", author = "Seppo Yli-Olli", author_email = "seppo.yli-olli@iki.fi", description = "Simple C preprocessor for usage eg before CFFI...
Add a prerelease version number.
""" Flask-Selfdoc ------------- Flask selfdoc automatically creates an online documentation for your flask app. """ from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='Flask-Selfdoc', version='0.2', url='http://github.com/jwg4/flask-selfdoc',...
""" Flask-Selfdoc ------------- Flask selfdoc automatically creates an online documentation for your flask app. """ from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='Flask-Selfdoc', version='1.0a1', url='http://github.com/jwg4/flask-selfdoc...
Fix smart_open to version which supports gzip streaming
from setuptools import setup, find_packages package = 'aws-utils' version = '0.2.7' INSTALL_REQUIRES = [ 'boto>=2.38.0', 'boto3>=1.2.3', 'smart-open>=1.3.1', 'dateutils>=0.6.6', 'retrying>=1.3.3' ] setup( name=package, version=version, author="Skimlinks Ltd.", author_email="dev@sk...
from setuptools import setup, find_packages package = 'aws-utils' version = '0.2.7' INSTALL_REQUIRES = [ 'boto>=2.38.0', 'boto3>=1.2.3', 'smart_open==1.3.2', # smart open must be 1.3.2 because in 1.3.3 onward the gzip write functionality has been removed 'dateutils>=0.6.6', 'retrying>=1.3.3' ] s...
Sort the logfile by added time.
from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView from dadd.master import models class ProcessModelView(ModelView): # Make the latest first column_default_sort = ('start_time', True) def __init__(self, session): super(ProcessModelView, self).__init__(models.Pro...
from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView from dadd.master import models class ProcessModelView(ModelView): # Make the latest first column_default_sort = ('start_time', True) def __init__(self, session): super(ProcessModelView, self).__init__(models.Pro...
Support case when expiration_datetime is None
from datetime import datetime, timedelta from invisibleroads_macros_security import make_random_string class DictionarySafe(dict): def __init__(self, key_length): self.key_length = key_length def put(self, value, time_in_seconds=None): while True: key = make_random_string(self.k...
from datetime import datetime, timedelta from invisibleroads_macros_security import make_random_string class DictionarySafe(dict): def __init__(self, key_length): self.key_length = key_length def put(self, value, time_in_seconds=None): while True: key = make_random_string(self.k...