Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix exceptions not displaying if a busy cursor was set. | #!/usr/bin/env python
#coding=utf8
"""
Error dialog interface.
"""
from whacked4.ui import windows
import wx
class ErrorDialog(windows.ErrorDialogBase):
def __init__(self, parent):
windows.ErrorDialogBase.__init__(self, parent)
wx.EndBusyCursor()
def set_log(self,... | #!/usr/bin/env python
#coding=utf8
"""
Error dialog interface.
"""
from whacked4.ui import windows
import wx
class ErrorDialog(windows.ErrorDialogBase):
def __init__(self, parent):
windows.ErrorDialogBase.__init__(self, parent)
if wx.IsBusy() == True:
wx.EndBusyCursor()
... |
Write tests for swappable model. | from django.test import TestCase | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, modify_settings
from boardinghouse.schema import get_schema_model
class TestSwappableModel(TestCase):
@modify_settings()
def test_schema_model_app_not_found(self):
settings.BOAR... |
Add deprecated flag for teachers and departments | from django.db import models
class Departments(models.Model):
urlid = models.IntegerField(unique = True)
name = models.CharField("Department name", max_length = 200)
class Teachers(models.Model):
urlid = models.CharField("URL ID", max_length = 30, unique = True)
name = models.CharField("Teacher name",... | from django.db import models
class Departments(models.Model):
urlid = models.IntegerField(unique = True)
name = models.CharField("Department name", max_length = 200)
deprecated = models.BooleanField(default = False)
def __unicode__(self):
return self.name
class Teachers(models.Model):
url... |
Add test of storing float | import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
... | import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_num_float(self):
self.assertEqual(
10... |
Change to path, made relative | #
# Code to load project paths
#
import os, sys
MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "/Users/dmhembere44/MR-connectome" ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )
sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MR... | #
# Code to load project paths
#
import os, sys
MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.." ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )
sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]
|
Fix typo in 0099 reverse_sql. | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
... | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
... |
Add automatic sending of 900/901 numerics for account status | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", ... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1... |
Fix ASDF tag test helper to load schemas correctly | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from asdf.types import for... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import os
import urllib.parse
import urllib.request
import yaml
import numpy as np
def run_schema_example_test(organization, standard, name, version, check_func=None):
import asdf
from asdf.tests import helpers
from... |
Add Execption for invalid Integer | from .lexerconstants import *
from .ws_token import Tokeniser
class Lexer(object):
def __init__(self, line):
self.line = line
self.pos = 0
self.tokens = []
def _get_int(self):
token = Tokeniser()
if self.line[-1] == '\n':
const = 'INT'
token.sca... | from .lexerconstants import *
from .ws_token import Tokeniser
class IntError(ValueError):
'''Exception when invalid integer is found'''
class Lexer(object):
def __init__(self, line):
self.line = line
self.pos = 0
self.tokens = []
def _get_int(self):
token = Tokeniser()
... |
Fix wrong db name for travis. | # -*- coding: utf-8 -*-
from .test import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'gis',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empty string for default.
'PORT': '',
}
}
| # -*- coding: utf-8 -*-
from .test import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empty string for default.
'PORT': '',
}... |
Load the spotify header file from an absolute path | from cffi import FFI
ffi = FFI()
print "Loading Spotify library..."
#TODO: Use absolute paths for open() and stuff
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open("spotify.processed.h") as file:
header = file.read()
ffi.cdef(header)
ffi.cdef(... | from cffi import FFI
ffi = FFI()
print "Loading Spotify library..."
#TODO: Use absolute paths for open() and stuff
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open(os.path.join(sys.path[0], "spotify.processed.h")) as file:
header = file.read()
... |
Drop unused and dangerous entrypoint `open_fileindex` | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... |
Make it possible to step() in a newly created env, rather than throwing AttributeError | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... |
Fix for broken container security test | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... |
Include the version-detecting code to allow PyXML to override the "standard" xml package. Require at least PyXML 0.6.1. | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... |
Add missing vat alias for Turkey | # __init__.py - collection of Turkish numbers
# coding: utf-8
#
# Copyright (C) 2016 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, ... | # __init__.py - collection of Turkish numbers
# coding: utf-8
#
# Copyright (C) 2016 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, ... |
Update GOV.UK Frontend/Jinja lib test | import json
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
assert package_json["dependencies"]["govuk-frontend"].startswith("3."), (
"After upgrading the Design System, manually validate that "
... | import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-fr... |
Test more edge cases of the highlighting parser | """Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as pa... | # coding: utf-8
"""Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, d... |
Add auth header to the fixture loader | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200").json()["ta... | """ Commands for interacting with Elastic Search """
# pylint: disable=broad-except
from os.path import join
import requests
from lib.tools import TEST_FOLDER
def es_is_available():
""" Test if Elastic Search is running """
try:
return (
requests.get("http://localhost:9200", auth=("ela... |
Add simple plots of downtown LA wateruse. | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
def clean(data):
"""
Take in data and return cleaned version.
"""
# Remove Date Values column
data = data.drop(["Date V... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
import matplotlib.pyplot as plt
from datetime import datetime
def clean(data):
"""
Take in data and return cleaned version.
"""
# Remove Date Values colu... |
Fix on teeny tiny little typo... Also remember to write commit messages in the present tense. | people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We... | people = 30
cars = 40
buses = 55
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We... |
Fix the use of the moksha.templates.widget template, in one place. This needs to be fixed in many places | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
from bugs import BugsControll... | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
from bugs import BugsControll... |
Remove uses of using() from migrations | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from milestones.data import fetch_milestone_relationship_types
def seed_relationship_types(apps, schema_editor):
"""Seed the relationship types."""
MilestoneRelationshipType = apps.get_model("milestones"... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from milestones.data import fetch_milestone_relationship_types
def seed_relationship_types(apps, schema_editor):
"""Seed the relationship types."""
MilestoneRelationshipType = apps.get_model("milestones"... |
Add test to DataLoader base class | import unittest
from brew.parsers import JSONDataLoader
class TestJSONDataLoader(unittest.TestCase):
def setUp(self):
self.parser = JSONDataLoader('./')
def test_format_name(self):
name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'),
('caramel crystal malt 20l', '... | import unittest
from brew.parsers import DataLoader
from brew.parsers import JSONDataLoader
class TestDataLoader(unittest.TestCase):
def setUp(self):
self.parser = DataLoader('./')
def test_read_data_raises(self):
with self.assertRaises(NotImplementedError):
self.parser.read_dat... |
Add test for StoreMagics.autorestore option | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... | import tempfile, os
from IPython.config.loader import Config
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip... |
Switch to COBYLA optimization method. Works much better. | # test1.py
# Ronald L. Rivest and Karim Husayn Karimi
# August 17, 2017
# Routine to experiment with scipy.optimize.minimize
import scipy.optimize
from scipy.stats import norm
# function to minimize:
def g(xy):
(x,y) = xy
print("g({},{})".format(x,y))
return x + y
# constraints
noise_level = 0.0000005
... | # test1.py
# Ronald L. Rivest and Karim Husayn Karimi
# August 17, 2017
# Routine to experiment with scipy.optimize.minimize
import scipy.optimize
from scipy.stats import norm
# function to minimize:
def g(xy):
(x,y) = xy
print("g({},{})".format(x,y))
return x + y
# constraints
noise_level = 0.05
# co... |
Refactor test to use user | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... |
Set some fields as tranlate | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmJobPosition... | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmJobPosition... |
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later. | """ Test script-oriented example from interactive plotting tutorial
source: docs/source/user_manual/chaco_tutorial.rst
"""
import unittest
from numpy import linspace, pi, sin
from enthought.chaco.shell import plot, show, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
... | """ Test script-oriented example from interactive plotting tutorial
source: docs/source/user_manual/chaco_tutorial.rst
"""
import unittest
from numpy import linspace, pi, sin
from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2... |
Delete import that no longer used | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._align import Align
from ._align_getter import align_getter
from ._container import MinMaxContainer
from ._data_property import (
ColumnDataProperty,
DataProperty
)
from ._error impo... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._align import Align
from ._align_getter import align_getter
from ._container import MinMaxContainer
from ._data_property import (
ColumnDataProperty,
DataProperty
)
from ._error impo... |
Remove problematic deoplete source customization. | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
'<`\g<num>:\g<desc>`>', snip)
class Source(Ba... | from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = "LanguageClient"
self.mark = "[LC]"
self.rank = 1000
self.filetypes = vim.eval(
"get(g:, 'LanguageClient... |
Check for errors in config | """manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp... | """manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp... |
UPDATE serialize method for json data | from application import db
class Artist(db.Model):
__tablename__ = 'artists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
birth_year = db.Column(db.Integer)
death_year = db.Column(db.Integer)
country = db.Column(db.String(45))
genre = db.Column(db.String(45... | from application import db
class Artist(db.Model):
__tablename__ = 'artists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
birth_year = db.Column(db.Integer)
death_year = db.Column(db.Integer)
country = db.Column(db.String(45))
genre = db.Column(db.String(45... |
Make gitpython and eventlet work with eventlet 0.25.1 | # Copyright 2019 Red Hat, Inc.
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # Copyright 2019 Red Hat, Inc.
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
Add the missing push_notifications args | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... |
Make photos and videos accessible | from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
#url(r'^google/', include('project.google.urls')),
ur... | from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
url(r'^google/', include('djangoogle.urls')),
url(r'^... |
Fix library not found on linux | from __future__ import absolute_import
import os, sys
from .wrapper import _libgdf_wrapper
from .wrapper import GDFError # re-exported
try:
from .libgdf_cffi import ffi
except ImportError:
pass
else:
def _get_lib_name():
if os.name == 'posix':
# TODO this will need to be cha... | from __future__ import absolute_import
import os
import sys
from .wrapper import _libgdf_wrapper
from .wrapper import GDFError # re-exported
try:
from .libgdf_cffi import ffi
except ImportError:
pass
else:
def _get_lib_name():
if os.name == 'posix':
# TODO this will need to ... |
Mark project as beta release | import os
from setuptools import setup
version = '0.2dev'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CHANGES.txt').read(),
])
setup(
name = "compare",
version = version,
description = "Alternative syntax for comparing/asserting expressions in Python. Supports pluggable match... | import os
from setuptools import setup
version = '0.2b'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CHANGES.txt').read(),
])
setup(
name = "compare",
version = version,
description = "Alternative syntax for comparing/asserting expressions in Python. Supports pluggable matcher... |
Bump requests from 2.5.1 to 2.20.0 | #!/usr/bin/env python
from setuptools import setup
setup(
name='Scrapper',
version='0.9.5',
url='https://github.com/Alkemic/scrapper',
license='MIT',
author='Daniel Alkemic Czuba',
author_email='alkemic7@gmail.com',
description='Scrapper is small, Python web scraping library',
py_modul... | #!/usr/bin/env python
from setuptools import setup
setup(
name='Scrapper',
version='0.9.5',
url='https://github.com/Alkemic/scrapper',
license='MIT',
author='Daniel Alkemic Czuba',
author_email='alkemic7@gmail.com',
description='Scrapper is small, Python web scraping library',
py_modul... |
Add id & category to routes list | # -*- coding: utf-8 -*-
from database.database_access import get_dao
from gtfslib.model import Route
from gtfsplugins import decret_2015_1610
from database.database_access import get_dao
def get_routes(agency_id):
dao = get_dao(agency_id)
parsedRoutes = list()
for route in dao.routes(fltr=Route.route_type == Rout... | # -*- coding: utf-8 -*-
from database.database_access import get_dao
from gtfslib.model import Route
from services.check_urban import check_urban_category
def get_routes(agency_id):
dao = get_dao(agency_id)
parsedRoutes = list()
for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS):
print(route)
pa... |
Use the @view decorator to ensure that the project page gets user data. | from mysite.search.models import Project
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
def project(request, project__name = None):
p = Project.objects.get(name=project__name)
return render... | from mysite.search.models import Project
import django.template
import mysite.base.decorators
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
@mysite.base.decorators.view
def project(request, projec... |
Add time formatter for competitions | # -*- coding: utf-8 -*-
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime... | # -*- coding: utf-8 -*-
import awesometime
def compo_times_formatter(compo):
compo.compo_time = awesometime.format_single(compo.compo_start)
compo.adding_time = awesometime.format_single(compo.adding_end)
compo.editing_time = awesometime.format_single(compo.editing_end)
compo.voting_time = awesometime... |
Fix girder_work script bug: PEP 263 is not compatible with exec | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... | ###############################################################################
# Copyright Kitware 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/lic... |
Add failing test for URL without zoom | # -*- coding: UTF-8 -*-
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.... | # -*- coding: UTF-8 -*-
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.... |
Add documentation for the control system | """
Template module to define control systems.
"""
class ControlSystem(object):
""" Define a control system to be used with a device
It uses channel access to comunicate over the network with
the hardware.
"""
def __init__(self):
raise NotImplementedError()
def get(self, pv):
... | """
Template module to define control systems.
"""
class ControlSystem(object):
""" Define a control system to be used with a device.
It uses channel access to comunicate over the network with
the hardware.
"""
def __init__(self):
raise NotImplementedError()
def get(self, pv):
... |
Save the image of the selection (to be able to reinitialise later) |
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display
# Open reference video
cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video')
# Select reference image
img=cam.getFrame(50)
modelImage = img.crop(255, 180... |
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display, Color
# Open reference video
cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video')
# Select reference image
img=cam.getFrame(50)
modelImage = img.crop(2... |
Fix ceilometerclient mocks for 2.8.0 release | #
# 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
# ... | #
# 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
# ... |
Move todos into issues tracking on GitHub | #!/usr/bin/env python
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach exa... | #!/usr/bin/env python
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the char... |
Add comments + return 1 if inconsistencies found | import re
import json
import glob
locale_folder = "../locales/"
locale_files = glob.glob(locale_folder + "*.json")
locale_files = [filename.split("/")[-1] for filename in locale_files]
locale_files.remove("en.json")
reference = json.loads(open(locale_folder + "en.json").read())
for locale_file in locale_files:
... | import re
import json
import glob
# List all locale files (except en.json being the ref)
locale_folder = "../locales/"
locale_files = glob.glob(locale_folder + "*.json")
locale_files = [filename.split("/")[-1] for filename in locale_files]
locale_files.remove("en.json")
reference = json.loads(open(locale_folder + "en... |
Check the copy model for failure | from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryCopyTableFails(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "copy-failing-models"
@property
def p... | from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryCopyTableFails(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "copy-failing-models"
@property
def p... |
Make the personal condor config world readable | from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, START... | from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, START... |
Set bytes_mode=False for future compatability with Python3 | from django.conf import settings
from ldapdb import escape_ldap_filter
import ldap
def authenticate(dn,pwd,ldap_conf_key):
# Setup connection
ldap_conf = settings.LDAPCONFS[ldap_conf_key]
server = ldap_conf['server']
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
conn = ldap.in... | from django.conf import settings
from ldapdb import escape_ldap_filter
import ldap
def authenticate(dn,pwd,ldap_conf_key):
# Setup connection
ldap_conf = settings.LDAPCONFS[ldap_conf_key]
server = ldap_conf['server']
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
conn = ldap.in... |
Drop json, bump copyright and Python version for intersphinx | ##
# Copyright (c) 2011 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
"""Default Sphinx configuration file for metamagic projects"""
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo',
'sphinx.ext.coverage', 'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
temp... | ##
# Copyright (c) 2011 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
"""Default Sphinx configuration file for metamagic projects"""
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo',
'sphinx.ext.coverage', 'sphinx.ext.viewcode',
'sphinx.ext.intersphinx']
temp... |
Add some :tiger2:s for `graph_objs_tools.py`. | from __future__ import absolute_import
from unittest import TestCase
| from __future__ import absolute_import
from unittest import TestCase
from plotly.graph_objs import graph_objs as go
from plotly.graph_objs import graph_objs_tools as got
class TestGetRole(TestCase):
def test_get_role_no_value(self):
# this is a bit fragile, but we pick a few stable values
# t... |
Fix parameter descriptions and change size to individual width and height parameters | #!/usr/bin/env python
import argparse
from s3imageresize import resize_image_folder
parser = argparse.ArgumentParser(description='Upload a file to Amazon S3 and rotate old backups.')
parser.add_argument('bucket', help="Name of the Amazon S3 bucket to save the backup file to.")
parser.add_argument('prefix', help="The... | #!/usr/bin/env python
import argparse
from s3imageresize import resize_image_folder
parser = argparse.ArgumentParser(description='Resize all images stored in a folder on Amazon S3.')
parser.add_argument('bucket', help="Name of the Amazon S3 bucket to save the backup file to.")
parser.add_argument('prefix', help="The... |
Add "dispatch_uid" to ensure we connect the signal only once | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACT... | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACT... |
Support conversion format as extension, instead of mimetype | import urllib
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
fullurl = request.build_absolute_uri(sourceurl)
conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER,
... | import urllib
from mimetypes import types_map
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
if '/' not in format:
extension = '.' + format if not format.startswith('.') else format
... |
Change the name of SelfSerializableList to PrintableList | """
A list field field that supports query string parameter parsing.
"""
from marshmallow.fields import List, ValidationError
class SelfSerializableList(list):
def __str__(self):
return ",".join(str(item) for item in self)
class QueryStringList(List):
def _deserialize(self, value, attr, obj):
... | """
A list field field that supports query string parameter parsing.
"""
from marshmallow.fields import List, ValidationError
class PrintableList(list):
def __str__(self):
return ",".join(str(item) for item in self)
class QueryStringList(List):
def _deserialize(self, value, attr, obj):
"""
... |
Change the help and assignments to match. | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from credentials.management.helpers import import_sshkeypair
class Command(BaseCommand):
help = "Import ssh keypair"
args = "[public key filename] [private key filename] [name]... | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from credentials.management.helpers import import_sshkeypair
class Command(BaseCommand):
help = "Import ssh keypair"
args = "[public key filename] [private key filename] [name]... |
Add assertion for checking arrays read from wavread | import numpy as np
from opensauce.helpers import wavread
from test.support import TestCase, data_file_path, loadmat
class TestSupport(TestCase):
def test_wavread(self):
fn = data_file_path('beijing_f3_50_a.wav')
samples, Fs = wavread(fn)
expected = loadmat('beijing_f3_50_a-wavread-expec... | import numpy as np
from opensauce.helpers import wavread
from test.support import TestCase, data_file_path, loadmat
class TestSupport(TestCase):
def test_wavread(self):
fn = data_file_path('beijing_f3_50_a.wav')
samples, Fs = wavread(fn)
expected = loadmat('beijing_f3_50_a-wavread-expec... |
Add --admin option for connecting in admin mode | import click
import os
import yaml
from panoptes_client import Panoptes
@click.group()
@click.option(
'--endpoint', type=str
)
@click.pass_context
def cli(ctx, endpoint):
ctx.config_dir = os.path.expanduser('~/.panoptes/')
ctx.config_file = os.path.join(ctx.config_dir, 'config.yml')
ctx.config = {
... | import click
import os
import yaml
from panoptes_client import Panoptes
@click.group()
@click.option('--endpoint', type=str)
@click.option('--admin', is_flag=True)
@click.pass_context
def cli(ctx, endpoint, admin):
ctx.config_dir = os.path.expanduser('~/.panoptes/')
ctx.config_file = os.path.join(ctx.config_di... |
Make fields in example app non required | import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=512)
filefield = i18n.LocalizedFileField(null=True, upload_to='files')
imagefield = i18n.LocalizedImageField(null=... | from django.db import models
import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
untranslated_charfield = models.CharField(max_length=50, blank=True)
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=500, blank=True)
... |
Change help text wording to follow WorkflowStateMixin | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_press_releases', '0008_auto_20161128_1049'),
]
operations = [
migrations.AddField(
model_name='pressrelea... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_press_releases', '0008_auto_20161128_1049'),
]
operations = [
migrations.AddField(
model_name='pressrelea... |
Make a few fields editable from the changelist | from django.contrib import admin
from newswall.models import Source, Story
admin.site.register(Source,
list_display=('name', 'is_active', 'ordering'),
list_filter=('is_active',),
prepopulated_fields={'slug': ('name',)},
)
admin.site.register(Story,
date_hierarchy='timestamp',
list_display=('... | from django.contrib import admin
from newswall.models import Source, Story
admin.site.register(Source,
list_display=('name', 'is_active', 'ordering'),
list_editable=('is_active', 'ordering'),
list_filter=('is_active',),
prepopulated_fields={'slug': ('name',)},
)
admin.site.register(Story,
da... |
Return a 404 error when no dstat csv can be loaded | from django.http import HttpResponse
from django.views.generic import View
from stackviz import settings
_cached_csv = None
def _load_csv():
global _cached_csv
if _cached_csv:
return _cached_csv
with open(settings.DSTAT_CSV, 'r') as f:
_cached_csv = f.readlines()
return _cached... | import os
from django.http import HttpResponse, Http404
from django.views.generic import View
from stackviz import settings
_cached_csv = None
def _load_csv():
global _cached_csv
if _cached_csv:
return _cached_csv
try:
with open(settings.DSTAT_CSV, 'r') as f:
_cached_csv =... |
Build APIException all exceptions must be handled | from rest_framework.views import exception_handler
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
... | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not... |
Fix GST_PLUGIN_PATH in runtime hook | import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = '{};{}'.format(
sys._MEIPASS, os.path.join(sys._MEIPASS, 'gst-plugins'))
os.environ['GST_RE... | import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'gst-plugins')
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPAS... |
Fix typo in selection theorem | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... |
Add comment to one_second_timeout assignment | from time import sleep
sleep(1)
| from time import sleep
# Due to the overhead of Python, sleeping for 1 second will cause testing to
# time out if the timeout is 1 second
sleep(1)
|
Fix data migration when making scope non-null | # encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('podcasts', '0014_auto_20140615_1032'),
]
operations = [
migrations.AlterField(
model_name='slug',
name='sco... | # encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
def set_scope(apps, schema_editor):
URL = apps.get_model('podcasts', 'URL')
Slug = apps.get_model('podcasts', 'Slug')
URL.objects.filter(scope__isnull=True).update(scope='')
Slug.objects.filter(scope__i... |
Remove the README.md loading step | from setuptools import setup
with open('README.md') as f:
description = f.read()
from beewarn import VERSION
setup(name='beewarn',
version=VERSION,
description='Utility for warning about bees',
author='Alistair Lynn',
author_email='arplynn@gmail.com',
license='MIT',
long_descr... | from setuptools import setup
from beewarn import VERSION
setup(name='beewarn',
version=VERSION,
description='Utility for warning about bees',
author='Alistair Lynn',
author_email='arplynn@gmail.com',
license='MIT',
url='https://github.com/prophile/beewarn',
zip_safe=True,
... |
Include nt.db with package data. | from setuptools import setup
description = 'New testament greek app for django.'
long_desc = open('README.rst').read()
setup(
name='django-greekapp',
version='0.0.1',
url='https://github.com/honza/greekapp',
install_requires=['django', 'redis'],
description=description,
long_description=long_d... | from setuptools import setup
description = 'New testament greek app for django.'
long_desc = open('README.rst').read()
setup(
name='django-greekapp',
version='0.0.1',
url='https://github.com/honza/greekapp',
install_requires=['django', 'redis'],
description=description,
long_description=long_d... |
Check for router platform in auto-deploy script. | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = ('Deploy configurations each IX having a router and a configuration'
' template attached.')
logger = logging.... | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = ('Deploy configurations each IX having a router and a configuration'
' template attached.')
logger = logging.... |
Fix node/nodejs name conflict on Ubuntu systems | """Host-only environment for Node.js."""
from pathlib import Path
from foreman import define_parameter, decorate_rule
from shipyard import install_packages
(define_parameter('npm_prefix')
.with_doc("""Location host-only npm.""")
.with_type(Path)
.with_derive(lambda ps: ps['//base:build'] / 'host/npm-host')
)
@... | """Host-only environment for Node.js."""
from pathlib import Path
from foreman import define_parameter, decorate_rule
from shipyard import (
ensure_file,
execute,
install_packages,
)
(define_parameter('npm_prefix')
.with_doc("""Location host-only npm.""")
.with_type(Path)
.with_derive(lambda ps: ps['... |
Add some extensions to the markdown parser | from markdown import Markdown
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE
from ..models import Image
class ImageLookupImagePattern(ImagePattern):
def sanitize_url(self, url):
if url.startswith("http"):
return url
else:
try:
image = Imag... | from markdown import Markdown
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE
from ..models import Image
class ImageLookupImagePattern(ImagePattern):
def sanitize_url(self, url):
if url.startswith("http"):
return url
else:
try:
image = Imag... |
Add shutdown scripts to turn_off servo after subscribing | #!/usr/bin/env python
# coding: utf-8
from futaba_serial_servo import RS30X
import rospy
from sensor_msgs.msg import JointState
class Slave:
def __init__(self):
self.rs = RS30X.RS304MD()
self.sub = rospy.Subscriber("/raspigibbon/master_joint_state", JointState, self.joint_callback, queue_size=10)
... | #!/usr/bin/env python
# coding: utf-8
from futaba_serial_servo import RS30X
import rospy
from sensor_msgs.msg import JointState
class Slave:
def __init__(self):
self.rs = RS30X.RS304MD()
self.sub = rospy.Subscriber("/raspigibbon/master_joint_state", JointState, self.joint_callback, queue_size=10)
... |
Add transaction support for django models. | # coding: utf-8
#
# Copyright 2013 Google Inc. 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/licenses/LICENSE-2.0
#
# Unless required by ... | # coding: utf-8
#
# Copyright 2013 Google Inc. 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/licenses/LICENSE-2.0
#
# Unless required by ... |
Fix osf clone test that was asking for a password | """Test `osf clone` command."""
import os
from mock import patch, mock_open, call
from osfclient import OSF
from osfclient.cli import clone
from osfclient.tests.mocks import MockProject
from osfclient.tests.mocks import MockArgs
@patch.object(OSF, 'project', return_value=MockProject('1234'))
def test_clone_projec... | """Test `osf clone` command."""
import os
from mock import patch, mock_open, call
from osfclient import OSF
from osfclient.cli import clone
from osfclient.tests.mocks import MockProject
from osfclient.tests.mocks import MockArgs
@patch.object(OSF, 'project', return_value=MockProject('1234'))
def test_clone_projec... |
Set test area to a burnable one. | import unittest
import fire_rs.firemodel.propagation as propagation
class TestPropagation(unittest.TestCase):
def test_propagate(self):
env = propagation.Environment([[475060.0, 477060.0], [6200074.0, 6202074.0]], wind_speed=4.11, wind_dir=0)
prop = propagation.propagate(env, 10, 20)
# pr... | import unittest
import fire_rs.firemodel.propagation as propagation
class TestPropagation(unittest.TestCase):
def test_propagate(self):
env = propagation.Environment([[480060.0, 490060.0], [6210074.0, 6220074.0]], wind_speed=4.11, wind_dir=0)
prop = propagation.propagate(env, 10, 20, horizon=3*36... |
Fix include path and ascii / utf8 errors. | #!/usr/bin/python
import sys
import glob
sys.path.append("python_scripts/gen-py")
sys.path.append("gen-py/thrift_solr/")
from thrift.transport import TSocket
from thrift.server import TServer
#import thrift_solr
import ExtractorService
import sys
import readability
import readability
def extract_with_python_rea... | #!/usr/bin/python
import sys
import os
import glob
#sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py"))
sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/"))
sys.path.append(os.path.dirname(__file__) )
from thrift.transport import TSocket
from thrift.server import TServer
#im... |
Remove assosiate user social auth step | SHELL_PLUS = "ipython"
SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player']
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login/error/'
SOCIAL_AUTH_INACTIVE_USER_URL = '/login/inactive/'
SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/'
SOCIAL_AUTH_PASSWORDLESS = True
SOCIAL_AUTH_PIPELINE = (
'social_core.pipel... | SHELL_PLUS = "ipython"
SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player']
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login/error/'
SOCIAL_AUTH_INACTIVE_USER_URL = '/login/inactive/'
SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/'
SOCIAL_AUTH_PASSWORDLESS = True
SOCIAL_AUTH_PIPELINE = (
'social_core.pipel... |
Change .env variable to KCLS_USER | import requests
from bs4 import BeautifulSoup
import json
from dotenv import load_dotenv
import os
load_dotenv(".env")
s = requests.Session()
r = s.get("https://kcls.bibliocommons.com/user/login", verify=False)
payload = {
"name": os.environ.get("USER"),
"user_pin": os.environ.get("PIN")
}
s.post("https://... | import requests
from bs4 import BeautifulSoup
import json
from dotenv import load_dotenv
import os
load_dotenv(".env")
s = requests.Session()
r = s.get("https://kcls.bibliocommons.com/user/login", verify=False)
payload = {
"name": os.environ.get("KCLS_USER"),
"user_pin": os.environ.get("PIN")
}
p = s.post(... |
Validate the presence of CONTENT_STORE. | # -*- coding: utf-8 -*-
import argparse
import sys
from os import path
from builder import DeconstJSONBuilder
from sphinx.application import Sphinx
from sphinx.builders import BUILTIN_BUILDERS
def build(argv):
"""
Invoke Sphinx with locked arguments to generate JSON content.
"""
parser = argparse.A... | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import sys
import os
from builder import DeconstJSONBuilder
from sphinx.application import Sphinx
from sphinx.builders import BUILTIN_BUILDERS
def build(argv):
"""
Invoke Sphinx with locked arguments to generate JSON content.
... |
Change init param of wordnet | #!/usr/bin/env python
################################################################################
# Created by Oscar Martinez #
# o.rubi@esciencecenter.nl #
#######################################################... | #!/usr/bin/env python
################################################################################
# Created by Oscar Martinez #
# o.rubi@esciencecenter.nl #
#######################################################... |
Move getting the event loop out of try/except | import logging
from argparse import ArgumentParser
import asyncio
from .protocol import connect_inotify
logger = logging.getLogger(__name__)
def main():
parser = ArgumentParser()
parser.add_argument(
'-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING')
parser.... | import logging
from argparse import ArgumentParser
import asyncio
from .protocol import connect_inotify
logger = logging.getLogger(__name__)
def main():
parser = ArgumentParser()
parser.add_argument(
'-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING')
parser.... |
Bump version number to reflect dev status. | """
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)... | """
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 0,
'releaselevel': 'dev',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i"... |
Update URL for baseline images | import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.1.x+... contain changes that will only
# be included in the 3.2.x release, so we update this here.
if MPL_VERSION[:3] == '3.1' and '+' in MPL_V... | import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.1.x+... contain changes that will only
# be included in the 3.2.x release, so we update this here.
if MPL_VERSION[:3] == '3.1' and '+' in MPL_V... |
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False | from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
return (course.has_ended()
and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE')
or has_access(user, 'staff', course.id))
| from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'):
return False
return course.has_ended() or has_access(user, 'staff', course.id)
|
Update to follower, reduce speed to motors. |
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self... |
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self... |
Remove deprecated context parameter from from_db_value | from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from netaddr import AddrFormatError, EUI, mac_unix_expanded
class ASNField(models.BigIntegerField):
description = "32-bit ASN field"
default_validators = [
... | from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from netaddr import AddrFormatError, EUI, mac_unix_expanded
class ASNField(models.BigIntegerField):
description = "32-bit ASN field"
default_validators = [
... |
Allow dashes in proposal kind slugs | from django.conf.urls.defaults import *
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\... | from django.conf.urls import patterns, url
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url... |
Make this test work when imported from the interpreter instead of run from regrtest.py (it still works there too, of course). | from test_support import verbose, TestFailed
import sunaudiodev
import os
def findfile(file):
if os.path.isabs(file): return file
import sys
for dn in sys.path:
fn = os.path.join(dn, file)
if os.path.exists(fn): return fn
return file
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
... | from test_support import verbose, TestFailed
import sunaudiodev
import os
def findfile(file):
if os.path.isabs(file): return file
import sys
path = sys.path
try:
path = [os.path.dirname(__file__)] + path
except NameError:
pass
for dn in path:
fn = os.path.join(dn, file)
if os.path.exists(fn): return fn
... |
Fix message tests after in message.parseMessage args three commits ago | import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_r... | import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_r... |
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function. | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCMo... | """Test that the clang modules cache directory can be controlled."""
from __future__ import print_function
import unittest2
import os
import time
import platform
import shutil
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCMo... |
Enable remote, rmessage and rnotify plugins by default | # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been ... | # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been ... |
Add more time to mqtt.test.client | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... |
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users. | from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
| from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfil... |
Remove BitVector import - Build fails | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Ind... | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_g... |
Add populate es function to test driver | #!/usr/bin/env python
from storage import Storage
NEW_REPORT = {'foo': 'bar', 'boo': 'baz'}
def main():
db_store = Storage.get_storage()
for key, value in db_store.__dict__.iteritems():
print '%s: %s' % (key, value)
print '\n'
# report_id = db_store.store(NEW_REPORT)
report_id = 'AVM0dGO... | #!/usr/bin/env python
from storage import Storage
NEW_REPORT = {'foo': 'bar', 'boo': 'baz'}
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163b62f583dbaffb2df74b9104e2aadabf8f8491bafab66", "libmagic": "ASCII text"}}},
{'report_id... |
Set more reasonable job sizes | # Your bucket to delete things from.
BUCKET = 'ADDME'
# How many processes to fork.
PROCESS_COUNT = 10
# Maximum number of objects per bulk request.
MAX_JOB_SIZE = 10000
# Your simple API access key from the APIs tab of
# <https://code.google.com/apis/console>.
DEVKEY = 'ADDME'
# On that same page, create a Client ... | # Your bucket to delete things from.
BUCKET = 'ADDME'
# How many processes to fork.
PROCESS_COUNT = 4
# Maximum number of objects per bulk request.
MAX_JOB_SIZE = 100
# Your simple API access key from the APIs tab of
# <https://code.google.com/apis/console>.
DEVKEY = 'ADDME'
# On that same page, create a Client ID ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.