Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set API key directly in test runner | """
Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me>
Distributed under the ISC License (see LICENSE)
"""
from distutils.core import setup, Command
from distutils.errors import DistutilsOptionError
from unittest import TestLoader, TextTestRunner
import os
import steam
class run_tests(Command):
description... | """
Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me>
Distributed under the ISC License (see LICENSE)
"""
from distutils.core import setup, Command
from distutils.errors import DistutilsOptionError
from unittest import TestLoader, TextTestRunner
import steam
class run_tests(Command):
description = "Run th... |
Add south as a dependency. | #
# Copyright 2013 Cisco Systems
#
# 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... | #
# Copyright 2013 Cisco Systems
#
# 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... |
Include Package Data was missing. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = 'django-helpline-faq',
version = '1.1',
description = 'A simple FAQ application for Django sites.',
long_description = read('README.rst'),
lic... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = 'django-helpline-faq',
version = '1.1',
description = 'A simple FAQ application for Django sites.',
long_description = read('README.rst'),
lic... |
Add unit test for expand_axis_label | import pickle
from six.moves import range
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_pickable", "bulky_attr")
class TestClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_pickable = lambda x: ... | import pickle
from six.moves import range
from fuel.utils import do_not_pickle_attributes, expand_axis_label
@do_not_pickle_attributes("non_pickable", "bulky_attr")
class TestClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_pi... |
Write to bouncer config file | #!/usr/bin/env python
import sys
import yaml
def read_parts_from_stdin():
data = sys.stdin.read()
parts_string = data.split("----")
parts_parsed = []
for part in parts_string:
part_parsed = yaml.safe_load(part)
parts_parsed.append(part_parsed)
return parts_parsed
def assemble_boun... | #!/usr/bin/env python
import sys
import yaml
def read_parts_from_stdin():
data = sys.stdin.read()
parts_string = data.split("----")
parts_parsed = []
for part in parts_string:
part_parsed = yaml.safe_load(part)
parts_parsed.append(part_parsed)
return parts_parsed
def assemble_boun... |
Add functions to add shapes and iterate over each shape to render. | #Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
sel... | #Imports
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
sel... |
Handle using the input function in python 2 for getting username for examples | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International, Inc.
from getpass import getpass
import os
from devicecloud import DeviceCloud... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International, Inc.
from getpass import getpass
import os
from six.moves import input
from de... |
Rework imports and ignore known mypy issues | # Copyright 2018 Donald Stufft and individual contributors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | # Copyright 2018 Donald Stufft and individual contributors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
Add another proxy server example string | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... |
Use reverse function for urls in carusele app | from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.TextField()
pubdate = models.DateTimeField(... | from django.core.urlresolvers import reverse
from django.db import models
class News (models.Model):
"""
News model represent detail description and
content of each carusele element.
"""
title = models.CharField(max_length=400)
description = models.TextField(default="")
content = models.Te... |
Add custom debug toolbar URL mount point. | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='we... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('... |
Fix style nit, line end for test file | """
SoftLayer.tests.CLI.modules.subnet_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing
import json
class SubnetTests(testing.TestCase):
def test_detail(self):
result = self.run_command(['subnet', 'detail', '1234'])... | """
SoftLayer.tests.CLI.modules.subnet_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing
import json
class SubnetTests(testing.TestCase):
def test_detail(self):
result = self.run_command(['subnet', 'detail', '1234'])... |
Update to line by line dataset JSON file parsing | import json
with open('dataset_item.json') as dataset_file:
dataset = json.load(dataset_file)
for i in range(len(dataset)):
if 'Continual' == dataset[i]['frequency']:
print dataset[i]['name']
| import json
dataset = []
dataset_files = ['dataset_item.json']
for f in dataset_files:
with open(f) as file:
for line in file:
dataset.append(json.loads(file))
for i in range(len(dataset)):
if 'Continual' == dataset[i]['frequency']:
print dataset[i]['name']
|
Fix bug where page stops updating by forcing it to reload after a minute of no activity | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... | #!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_... |
Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... |
Improve logging of build failure | import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
# The idea here is to modify the request handling by intercepting the
# `send_head` call which is combines the common bits of GET and HEAD commands
# and, more importantly, is the first method in the request handling pro... | import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
# The idea here is to modify the request handling by intercepting the
# `send_head` call which is combines the common bits of GET and HEAD commands
# and, more importantly, is the first method in the request handling pro... |
Remove error message when using MAQ module | from impacket.ldap import ldapasn1 as ldapasn1_impacket
class CMEModule:
'''
Module by Shutdown and Podalirius
Initial module:
https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota
Authors:
Shutdown: @_nwodtuhs
Podalirius: @podalirius_
'''
def option... | from impacket.ldap import ldapasn1 as ldapasn1_impacket
class CMEModule:
'''
Module by Shutdown and Podalirius
Initial module:
https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota
Authors:
Shutdown: @_nwodtuhs
Podalirius: @podalirius_
'''
def option... |
Use super() and self within the Cipher and Caesar classes | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = Cipher._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.ke... | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... |
Add test of deleteing child for nonterminal | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 31.08.2017 11:55
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import TreeDeletedException
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class From(Rul... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 31.08.2017 11:55
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import TreeDeletedException
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class From(Rul... |
Add choices for challenge category | from django.contrib.auth.models import User
from django.db import models
import markdown
from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH
class Challenge(models.Model):
"""A challenge represents an individual problem to be solved."""
name = models.CharField(max_length=CHALLENGE_... | from django.contrib.auth.models import User
from django.db import models
import markdown
from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH
class Challenge(models.Model):
"""A challenge represents an individual problem to be solved."""
CATEGORY_CHOICES = (
('be', 'Beer'),... |
Correct bug introduced in the previous commit (last update in feed entries). | from google.appengine.ext import db
from google.appengine.api.users import User
class Cfp(db.Model):
name = db.StringProperty()
fullname = db.StringProperty()
website = db.LinkProperty()
begin_conf_date = db.DateProperty()
end_conf_date = db.DateProperty()
submission_deadline = db.DateProperty(... | from google.appengine.ext import db
from google.appengine.api.users import User
class Cfp(db.Model):
name = db.StringProperty()
fullname = db.StringProperty()
website = db.LinkProperty()
begin_conf_date = db.DateProperty()
end_conf_date = db.DateProperty()
submission_deadline = db.DateProperty(... |
Use os.environ['PATH'] instead of sys.path | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... |
Modify abstract parameter to match its children | from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(s... | from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(s... |
Add a docstring for `test_rule_linenumber` | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... |
Fix decode bug in Process() failures | import subprocess as sub
import logbook
from piper.logging import SEPARATOR
class Process(object):
"""
Helper class for running processes
"""
def __init__(self, ns, cmd, parent_key):
self.ns = ns
self.cmd = cmd
self.popen = None
self.success = None
self.log... | import subprocess as sub
import logbook
from piper.logging import SEPARATOR
class Process(object):
"""
Helper class for running processes
"""
def __init__(self, ns, cmd, parent_key):
self.ns = ns
self.cmd = cmd
self.popen = None
self.success = None
self.log... |
Sort punctuation hits so output is based on line and column, not the order rules are checked | #!/usr/bin/python3
import re
import wlint.common
import wlint.punctuation
class PunctuationStyle(wlint.common.Tool):
def __init__(self, description):
super().__init__(description)
self.checks = wlint.punctuation.PunctuationRules().rules
def setup(self, arguments):
self.result = 0
... | #!/usr/bin/python3
import operator
import wlint.common
import wlint.punctuation
class PunctuationStyle(wlint.common.Tool):
def __init__(self, description):
super().__init__(description)
self.checks = wlint.punctuation.PunctuationRules().rules
def setup(self, arguments):
self.result... |
Add test for hashing multiple values | from nose.tools import istest, assert_equal
from whack.hashes import Hasher
@istest
def hashing_the_same_single_value_gives_the_same_hash():
def create_hash():
hasher = Hasher()
hasher.update("one")
return hasher.hexdigest()
assert_equal(create_hash(), create_hash())
| from nose.tools import istest, assert_equal
from whack.hashes import Hasher
@istest
def hashing_the_same_single_value_gives_the_same_hash():
def create_hash():
hasher = Hasher()
hasher.update("one")
return hasher.hexdigest()
assert_equal(create_hash(), create_hash())
@istest
def ... |
Make available via config file | from .logdna import LogDNAHandler
__all__ = ['LogDNAHandler']
| from .logdna import LogDNAHandler
__all__ = ['LogDNAHandler']
# Publish this class to the "logging.handlers" module so that it can be use
# from a logging config file via logging.config.fileConfig().
import logging.handlers
logging.handlers.LogDNAHandler = LogDNAHandler
|
Allow JsonRender only in production mode | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check"
)
SECRET_KEY = os.environ.get('SECRET_KEY', "PLEASE_REPLACE_ME")
# SECURITY WARNING: don't r... | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check"
)
SECRET_KEY = os.environ.get('SECRET_KEY', "PLEASE_REPLACE_ME")
# SECURITY WARNING: don't r... |
Add filters to Email Admin List View | from django.contrib import admin
from django.conf.urls import url
from .models import Email, Tag
from .views import SendEmailAdminView, UpdateTargetCountView
from .forms import EmailAdminForm
class EmailAdmin(admin.ModelAdmin):
form = EmailAdminForm
readonly_fields = ('targetted_users', 'is_sent',)
add_f... | from django.contrib import admin
from django.conf.urls import url
from .models import Email, Tag
from .views import SendEmailAdminView, UpdateTargetCountView
from .forms import EmailAdminForm
class EmailAdmin(admin.ModelAdmin):
list_display = ['__str__', 'is_sent']
list_filter = ['is_sent']
form = EmailA... |
Add FloatArgument to arguments module | from .base import BaseArgument, ListArgument
from .boolean import BooleanArgument
from .number import IntegerArgument
from .scope import ScopeArgument
from .string import StringArgument, StringListArgument
from .url import URLArgument
| from .base import BaseArgument, ListArgument
from .boolean import BooleanArgument
from .number import FloatArgument, IntegerArgument
from .scope import ScopeArgument
from .string import StringArgument, StringListArgument
from .url import URLArgument
|
Update osm way used due to data change | # http://www.openstreetmap.org/way/367477828
assert_has_feature(
16, 10471, 25331, 'roads',
{ 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind':... | # http://www.openstreetmap.org/way/444491374
assert_has_feature(
16, 10475, 25332, 'roads',
{ 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 39714073... |
Add fpp k/d data to the model. | from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = model... | from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo =... |
Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Verifies that the histograms XML file is well-formatted."""
import extract_histograms
def main():
# This will raise an exception if the file is not w... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Verifies that the histograms XML file is well-formatted."""
import extract_histograms
import os.path
def main():
# This will raise an exception if th... |
Delete a stray Python 2 print statement. | # Copyright (c) 2014, Matt Layman
import inspect
import tempfile
import unittest
from handroll import configuration
class FakeArgs(object):
def __init__(self):
self.outdir = None
self.timing = None
class TestConfiguration(unittest.TestCase):
def test_loads_from_outdir_argument(self):
... | # Copyright (c) 2014, Matt Layman
import inspect
import tempfile
import unittest
from handroll import configuration
class FakeArgs(object):
def __init__(self):
self.outdir = None
self.timing = None
class TestConfiguration(unittest.TestCase):
def test_loads_from_outdir_argument(self):
... |
Use new Epsilon versioned feature. | from distutils.core import setup
distobj = setup(
name="Axiom",
version="0.1",
maintainer="Divmod, Inc.",
maintainer_email="support@divmod.org",
url="http://divmod.org/trac/wiki/AxiomProject",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
... | from distutils.core import setup
import axiom
distobj = setup(
name="Axiom",
version=axiom.version.short(),
maintainer="Divmod, Inc.",
maintainer_email="support@divmod.org",
url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
platforms=["any"],
description="An in-process obje... |
Implement test for duplicate rooms | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_... | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_... |
Add additional space before inline comment. | from django import template
from django.utils.safestring import mark_safe
from akllt.common import formrenderer
register = template.Library() # pylint: disable=invalid-name
@register.simple_tag(name='formrenderer', takes_context=True)
def formrenderer_filter(context, form):
return mark_safe(formrenderer.render_... | from django import template
from django.utils.safestring import mark_safe
from akllt.common import formrenderer
register = template.Library() # pylint: disable=invalid-name
@register.simple_tag(name='formrenderer', takes_context=True)
def formrenderer_filter(context, form):
return mark_safe(formrenderer.render... |
Add vendor dir to path | """
WSGI config for voteswap project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | """
WSGI config for voteswap project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... |
Change username to osf uid | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word... | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word... |
Add a few more cases of "not value" | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
import pep8
class UtilTestCase(unittest.TestCase):
def test_normalize_paths(self):
cwd = os.getcwd()
self.assertEquals(pep8.normalize_paths(''), [])
self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
import pep8
class UtilTestCase(unittest.TestCase):
def test_normalize_paths(self):
cwd = os.getcwd()
self.assertEquals(pep8.normalize_paths(''), [])
self.assertEquals(pep8.normalize_paths([]), [])
self.assert... |
Disable L3 agents scheduler extension in Tempest | #
# 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
# ... |
Test that saving ProfileForm works | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.core.urlresolvers import reverse
from django.test import TestCase
from django_dynamic_fixture import G
from rest_framework im... | from django.core.urlresolvers import reverse
from django.test import TestCase
from django_dynamic_fixture import G
from rest_framework import status
from apps.authentication.models import OnlineUser as User
from apps.profiles.forms import ProfileForm
class ProfilesURLTestCase(TestCase):
def test_user_search(self... |
Fix column positions to reflect current spreadsheet. | #!/usr/bin/env python
import os
import sys
try:
username = os.environ['GOOGLE_USERNAME']
password = os.environ['GOOGLE_PASSWORD']
except KeyError:
print("Please supply username (GOOGLE_USERNAME)"
"and password (GOOGLE_PASSWORD) as environment variables")
sys.exit(1)
column_positions = {
... | #!/usr/bin/env python
import os
import sys
try:
username = os.environ['GOOGLE_USERNAME']
password = os.environ['GOOGLE_PASSWORD']
except KeyError:
print("Please supply username (GOOGLE_USERNAME)"
"and password (GOOGLE_PASSWORD) as environment variables")
sys.exit(1)
column_positions = {
... |
Change variable name & int comparison. | from flask import jsonify, current_app
from . import status
from . import utils
from ..main.helpers.service import ServiceLoader
from ..main import main
@status.route('/_status')
def status():
# ServiceLoader is the only thing that actually connects to the API
service_loader = ServiceLoader(
main.co... | from flask import jsonify, current_app
from . import status
from . import utils
from ..main.helpers.service import ServiceLoader
from ..main import main
@status.route('/_status')
def status():
# ServiceLoader is the only thing that actually connects to the API
service_loader = ServiceLoader(
main.co... |
Revert "Change to get Django 1.5 to work." | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'openshift.views.home', name='home'),
# url(r'^openshift/', include('openshift.foo.urls')),
#... | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'openshift.views.home', name='home'),
# url(r'^openshift/', include('openshift.foo.urls')... |
Change name getbusline name method | """Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .mode... | """Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .mode... |
Add missing test settings (in-memory sqlite3 db + SITE_ID) | SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
| SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SITE_ID = 1
|
Test all cases of type for opentransf | import pymorph
import numpy as np
def test_opentransf():
f = np.array([
[0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0],
[0,1,0,1,1,1,0,0],
[0,0,1,1,1,1,0,0],
[1,1,0,0,0,0,0,0]], bool)
ot = pymorph.opentransf( f, 'city-block')
for y in xrange(ot.shape[0]):
... | import pymorph
import numpy as np
def test_opentransf():
f = np.array([
[0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0],
[0,1,0,1,1,1,0,0],
[0,0,1,1,1,1,0,0],
[1,1,0,0,0,0,0,0]], bool)
ot = pymorph.opentransf( f, 'city-block')
for y in xrange(ot.shape[0]):
... |
Add in references to new services. | #!/usr/bin/env python
from mcapi.mcapp import app
from mcapi import tservices, public, utils, private, access
from mcapi.user import account, datadirs, datafiles, reviews, ud
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
debug = True
else:
debug = False
if len(sys.argv) == ... | #!/usr/bin/env python
from mcapi.mcapp import app
from mcapi import tservices, public, utils, private, access, process, machine, template
from mcapi.user import account, datadirs, datafiles, reviews, ud
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
debug = True
else:
debug = Fal... |
Add tests for falseish config values | import pytest
from timewreport.config import TimeWarriorConfig
def test_get_value_should_return_value_if_key_available():
config = TimeWarriorConfig({'FOO': 'foo'})
assert config.get_value('FOO', 'bar') == 'foo'
def test_get_value_should_return_default_if_key_not_available():
config = TimeWarriorConfi... | import pytest
from timewreport.config import TimeWarriorConfig
def test_get_value_should_return_value_if_key_available():
config = TimeWarriorConfig({'FOO': 'foo'})
assert config.get_value('FOO', 'bar') == 'foo'
def test_get_value_should_return_default_if_key_not_available():
config = TimeWarriorConfi... |
Remove some required arguments in post function context | from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the use... | from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the use... |
Add clarifying(?) comment about uid caching | import tornado
from tornado import gen
import json
import os
BASE_PATH = '.'
base_url = '/paws/public/'
@gen.coroutine
def uid_for_user(user):
url = 'https://meta.wikimedia.org/w/api.php?' + \
'action=query&meta=globaluserinfo' + \
'&format=json&formatversion=2' + \
'&guiuser={}'.... | import tornado
from tornado import gen
import json
import os
BASE_PATH = '.'
base_url = '/paws/public/'
@gen.coroutine
def uid_for_user(user):
url = 'https://meta.wikimedia.org/w/api.php?' + \
'action=query&meta=globaluserinfo' + \
'&format=json&formatversion=2' + \
'&guiuser={}'.... |
Change assertTrue(isinstance()) by optimal assert | # Copyright 2016 AT&T Corp
# 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 app... | # Copyright 2016 AT&T Corp
# 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 app... |
Bump aiohttp version constraint to <3.4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.10.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
l... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.10.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
l... |
Prepare for 1.6.1 on pypi | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
with open('README.rst', 'rb') as readme:
readme_text = readme.read().decode('utf-8')
setup(
name='django-bootstrap-pagination',
version='1.6.0',
keywords="django bootstrap pagination templatetag",
author... | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
with open('README.rst', 'rb') as readme:
readme_text = readme.read().decode('utf-8')
setup(
name='django-bootstrap-pagination',
version='1.6.1',
keywords="django bootstrap pagination templatetag",
author... |
Add a bit more to description | #!/usr/bin/env python
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.3',
description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error',
author = 'Justin Clark-Case... | #!/usr/bin/env python
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.4',
description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argpa... |
Fix long_description loading for PyPI | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_e... | import os
from setuptools import setup
README_PATH = 'README.rst'
longDesc = ""
if os.path.exists(README_PATH):
with open(README_PATH) as readme:
longDesc = readme.read()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net"... |
Revert "Allow Django Evolution to install along with Django >= 1.7." | #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/ru... | #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/ru... |
Include any files ending in '.install' in package data | #!/usr/bin/python3
# SPDX-License-Identifier: LGPL-2.1+
from setuptools import setup, Command, find_packages
class BuildManpage(Command):
description = ('builds the manpage')
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
... | #!/usr/bin/python3
# SPDX-License-Identifier: LGPL-2.1+
from setuptools import setup, Command, find_packages
class BuildManpage(Command):
description = ('builds the manpage')
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
... |
Add test for task to str params conversion | import doctest
import unittest
import luigi.task
class TaskTest(unittest.TestCase):
def test_tasks_doctest(self):
doctest.testmod(luigi.task)
| import doctest
import unittest
import luigi.task
import luigi
from datetime import datetime, timedelta
class DummyTask(luigi.Task):
param = luigi.Parameter()
bool_param = luigi.BooleanParameter()
int_param = luigi.IntParameter()
float_param = luigi.FloatParameter()
date_param = luigi.DateParamet... |
Allow site names to be up to 40 chars long (instead of 20) | """
byceps.blueprints.admin.site.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import SelectField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ....util.l10n import LocalizedForm... | """
byceps.blueprints.admin.site.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import SelectField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ....util.l10n import LocalizedForm... |
Update copyright string in docs | import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2020, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
... | import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2021, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
... |
Add block structure to perception handler. Slightly change perception handler logic. | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given an agent and a world.
:param agent: The agent ... | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given an agent and a world.
:param agent: The agent ... |
Add script to generate the yaml files for experiments | import yaml
import copy
vacuum_switching_lengths = [0, 100, 500, 1000, 5000, 10000]
solvent_switching_lengths = [500, 1000, 5000, 10000, 20000, 50000]
use_sterics = [True, False]
geometry_divisions = [90, 180, 360, 720]
# Load in template yaml:
with open("rj_hydration.yaml", "r") as templatefile:
template_yaml =... | |
Add newline at the end of the file for my sanity. | # -*- coding: utf-8 -*-
"""
test_pops
~~~~~~~~~
tests for population code
"""
from abm import pops
from abm.entities import Task
import pytest
from scipy.stats.distributions import uniform
import numpy as np
@pytest.fixture
def basicenv():
return pops.Environment()
@pytest.mark.unit
def test_distr... | # -*- coding: utf-8 -*-
"""
test_pops
~~~~~~~~~
tests for population code
"""
from abm import pops
from abm.entities import Task
import pytest
from scipy.stats.distributions import uniform
import numpy as np
@pytest.fixture
def basicenv():
return pops.Environment()
@pytest.mark.unit
def test_distr... |
Add method to rotate triangle | #!/usr/bin/env python3
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Severa... | #!/usr/bin/env python3
import math
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate... |
Fix query string update helper. | # coding: utf-8
import random
import urlparse
from string import ascii_letters, digits
from urllib import urlencode
# From http://tools.ietf.org/html/rfc6750#section-2.1
BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/'
def random_hash(length):
return ''.join(random.sample(BEARER_TOKEN_CHARSET, length))
d... | # coding: utf-8
import random
import urlparse
from string import ascii_letters, digits
from urllib import urlencode
# From http://tools.ietf.org/html/rfc6750#section-2.1
BEARER_TOKEN_CHARSET = ascii_letters + digits + '-._~+/'
def random_hash(length):
return ''.join(random.sample(BEARER_TOKEN_CHARSET, length))
d... |
Add unit tests for InfrequentValueEncoder | # pylint: disable=missing-docstring, invalid-name, import-error
import pandas as pd
from mltils.encoders import InfrequentValueEncoder
def test_infrequent_value_encoder_1():
ive = InfrequentValueEncoder()
assert ive is not None
def test_infrequent_value_encoder_2():
df = pd.DataFrame({'A': ['a', 'a', '... | |
Fix the XML format produced | #!/usr/bin/python
import sys
import os
name = sys.argv[1]
status = sys.stdin.readline()
status = status.rstrip(os.linesep)
print("<%s>" % name)
print("\t<status=\"%s\" />" % status)
if status != "SKIP":
print("\t<outcome>")
for line in sys.stdin:
# Escaping, ... !
print(line.rstrip(os.linesep))
p... | #!/usr/bin/python
import sys
import os
name = sys.argv[1]
status = sys.stdin.readline()
status = status.rstrip(os.linesep)
print("<%s status=\"%s\">" % (name, status))
print("\t<outcome>")
for line in sys.stdin:
# Escaping, ... !
print(line.rstrip(os.linesep))
print("\t</outcome>")
print("</%s>" % name)
|
Update what's needed to correct mask and model |
'''
Swap the spatial axes. Swap the spectral and stokes axes.
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
hdu[0].data = hdu[0].data[:, :, :, ::-1]
hdu[0].data = hdu[0].data[:, :, ::-1, :]
hdu.flush()
execfile("~/Dropbox/code_dev... |
'''
\Swap the spectral and stokes axes. Needed due to issue in regridding function
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
execfile("/home/eric/Dropbox/code_development/ewky_scripts/header_swap_axis.py")
hdu[0].header = heade... |
Fix lint issues related to long lines | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for fie... | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for fie... |
Add weighted graph in main() | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): TBD.
"""
pass
def main():
pass
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): TBD.
"""
pass
def main():
w_graph_d = {
'a': {'b': 1, 'd': 4, 'e': 3},
... |
Add function for get filter types | #!/usr/bin/env python
import click
import ebisearch
from pprint import pprint
@click.group()
def main():
pass
@click.command('get_results', short_help='Get list of results')
def get_results():
"""Return the list of domains in EBI"""
ebisearch.get_results(verbose=True)
@click.command('get_filter_field... | #!/usr/bin/env python
import click
import ebisearch
from pprint import pprint
@click.group()
def main():
pass
@click.command('get_results', short_help='Get list of results')
def get_results():
"""Return the list of domains in EBI"""
ebisearch.get_results(verbose=True)
@click.command('get_filter_field... |
Add gnu99 build flag for linuxy builds | #!/usr/bin/env python
"""
setup.py file for helium-client-python
"""
from distutils.core import setup, Extension
sourcefiles = ['src/helium_client.c',
'src/helium-serial.c',
'src/helium-client/helium-client.c',
'src/helium-client/cauterize/atom_api.c',
'src... | #!/usr/bin/env python
"""
setup.py file for helium-client-python
"""
from distutils.core import setup, Extension
sourcefiles = ['src/helium_client.c',
'src/helium-serial.c',
'src/helium-client/helium-client.c',
'src/helium-client/cauterize/atom_api.c',
'src... |
Add rarely, mostly and other alias | import random
in_percentage = lambda x: random.randint(1,100) <= x
"""
They've done studies, you know. 50% of the time,
it works every time.
"""
def sometimes(fn):
def wrapped(*args, **kwargs):
wrapped.x += 1
if wrapped.x % 2 == 1:
return fn(*args, **kwargs)
return
... | import random
in_percentage = lambda x: random.randint(1,100) <= x
"""
They've done studies, you know. 50% of the time,
it works every time.
"""
def sometimes(fn):
def wrapped(*args, **kwargs):
wrapped.x += 1
if wrapped.x % 2 == 1:
return fn(*args, **kwargs)
wrapped.x =... |
Add google measurement protocol back | # from google_measurement_protocol import Event, report
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
# event = Event('API', 'Fetch', label=label, value=count)
# ... | from google_measurement_protocol import event, report
import uuid
GENDERS = {
'female': 'Gender Female',
'male': 'Gender Male'
}
def log_fetch(count, gender):
label = GENDERS.get(gender, 'Gender Neutral')
client_id = uuid.uuid4()
data = event('API', 'Fetch', label=label, value=count)
report(... |
Move CACHE_TYPE to Config; add TestingConfig | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
from os import path
class Config(object):
cwd = path.abspath(path.dirname(__file__))
with open(path.join(cwd, 'me.json')) as me:
me = json.load(me)
with open(path.join(cwd, 'modules... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
from os import path
class Config(object):
CACHE_TYPE = 'simple'
cwd = path.abspath(path.dirname(__file__))
with open(path.join(cwd, 'me.json')) as me:
me = json.load(me)
with o... |
Fix an error when number of predictor columns is less than max_features. | # import numpy
from sklearn.ensemble import RandomForestClassifier as RandomForest
from sklearn.preprocessing import Imputer
from numpy import isnan
import Orange.data
import Orange.classification
def replace_nan(X, imp_model):
# Default scikit Imputer
# Use Orange imputer when implemented
if i... | import numbers
from sklearn.ensemble import RandomForestClassifier as RandomForest
from sklearn.preprocessing import Imputer
from numpy import isnan
import Orange.data
import Orange.classification
def replace_nan(X, imp_model):
# Default scikit Imputer
# Use Orange imputer when implemented
if isnan(X).s... |
Select popular pbs first instead of only closest | from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from froide.publicbody.models import PublicBody
from .amenity import AmenityProvider
class AmenityLocalProvider(AmenityProvider):
'''
Like Amenity provider but tries to find the public body
for the amen... | from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from froide.publicbody.models import PublicBody
from .amenity import AmenityProvider
class AmenityLocalProvider(AmenityProvider):
'''
Like Amenity provider but tries to find the public body
for the amen... |
Fix call to HTTP404 now it is a function. | #! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------
Convert any function into a WSGI endpoint with a simple decorator.
"""
from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404
class Router(object):
"""
Router holds the mapping of routes to callables.
"""... | #! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------
Convert any function into a WSGI endpoint with a simple decorator.
"""
from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404
class Router(object):
"""
Router holds the mapping of routes to callables.
"""... |
Add setFreq/setColor methods for FlashingBox | from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq, color):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
self.i... | from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq=1, color=Qt.black):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
... |
Add semver version limit due to compat changes | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager f... | """Setuptools configuration for rpmvenv."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='rpmvenv',
version='0.23.0',
url='https://github.com/kevinconway/rpmvenv',
description='RPM packager f... |
Add dependency on github version of fonttools | # Copyright 2015 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 applicable law or a... | # Copyright 2015 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 applicable law or a... |
Add flake8 to installation dependencies | import os
from setuptools import find_packages
from setuptools import setup
import sys
sys.path.insert(0, os.path.abspath('lib'))
exec(open('lib/ansiblereview/version.py').read())
setup(
name='ansible-review',
version=__version__,
description=('reviews ansible playbooks, roles and inventory and suggests... | import os
from setuptools import find_packages
from setuptools import setup
import sys
sys.path.insert(0, os.path.abspath('lib'))
exec(open('lib/ansiblereview/version.py').read())
setup(
name='ansible-review',
version=__version__,
description=('reviews ansible playbooks, roles and inventory and suggests... |
Fix misplaced colon in test suite | #! usr/bin/env python3
import unittest
from sqlviz import Schema
# Tests will go here...eventually
class InventorySchemaSpec (unittest.TestCase):
def setUp (self):
self.schema = Schema(
"""DROP TABLE Inventory;
CREATE TABLE Inventory
(
id INT PRIMARY... | #! usr/bin/env python3
import unittest
from sqlviz import Schema
# Tests will go here...eventually
class InventorySchemaSpec (unittest.TestCase):
def setUp (self):
self.schema = Schema(
"""DROP TABLE Inventory;
CREATE TABLE Inventory
(
id INT PRIMARY... |
Delete whitespace at line 7 | from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class ControlerLogoutTest(TestCase):
"""Unit test suite for testing the controler of
Logout in the app: tosp_auth.
Test that if the functionality of logout is correct.
""... | from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class ControlerLogoutTest(TestCase):
"""Unit test suite for testing the controler of
Logout in the app: tosp_auth.
Test that if the functionality of logout is correct.
"""... |
Return JSON from pypuppetdbquery.parse() by default | # -*- coding: utf-8 -*-
#
# This file is part of pypuppetdbquery.
# Copyright © 2016 Chris Boot <bootc@bootc.net>
#
# 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.or... | # -*- coding: utf-8 -*-
#
# This file is part of pypuppetdbquery.
# Copyright © 2016 Chris Boot <bootc@bootc.net>
#
# 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.or... |
Remove rest_framework routers, add urlpattern for users api | from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf,
name='generate-pdf'),
url(r'^', include(router.urls... | from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf,
name='generate-pdf'),
url(r'^users/$', views.UserAdmin.as_view(), name='users'),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserAdminDetail.as_view(), name='user-deta... |
Make ID of regions be definite. | import os
import json
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
df... | import os
import json
from collections import OrderedDict
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, d... |
Join word tokens into space-delimited string in InfoRetriever | # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def... | # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def... |
Fix dodo-upgrade (nothing was executed) | import os
import sys
from plumbum import local
def main(): # noqa
pip = local[os.path.join(os.path.dirname(sys.executable), "pip")]
pip["install", "--upgrade", "dodo_commands"]
| import os
import sys
from plumbum import local
def main(): # noqa
pip = local[os.path.join(os.path.dirname(sys.executable), "pip")]
pip("install", "--upgrade", "dodo_commands")
|
Exclude common unwanted package patterns | from django_rocket import __version__, __author__, __email__, __license__
from setuptools import setup, find_packages
README = open('README.rst').read()
# Second paragraph has the short description
description = README.split('\n')[1]
setup(
name='django-rocket',
version=__version__,
description=descripti... | from django_rocket import __version__, __author__, __email__, __license__
from setuptools import setup, find_packages
README = open('README.rst').read()
# Second paragraph has the short description
description = README.split('\n')[1]
setup(
name='django-rocket',
version=__version__,
description=descripti... |
Add projectSlug to build flaky tests API response | from __future__ import absolute_import
from changes.api.base import APIView
from changes.config import db
from changes.constants import Result
from changes.models import Build, Job, TestCase
class BuildFlakyTestsAPIView(APIView):
def get(self, build_id):
build = Build.query.get(build_id)
if build... | from __future__ import absolute_import
from changes.api.base import APIView
from changes.config import db
from changes.constants import Result
from changes.models import Build, Job, TestCase
class BuildFlakyTestsAPIView(APIView):
def get(self, build_id):
build = Build.query.get(build_id)
if build... |
Add messagepack to the list of dependencies, since runtime wont run without it. | #! /usr/bin/env python
import os
from setuptools import setup, find_packages
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as file:
return file.read().strip()
setup(
name='django-armet',
version='0.2.0-pre',
description='Clean and modern framewo... | #! /usr/bin/env python
import os
from setuptools import setup, find_packages
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as file:
return file.read().strip()
setup(
name='django-armet',
version='0.2.0-pre',
description='Clean and modern framewo... |
Add static files to data_files | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
... | import setuptools
from glob import glob
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
... |
Remove old method of adding datafiles. | #!/usr/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(name='pynxc',
version='0.1.7',
description='A Python to NXC Converter for programming '
'LEGO MINDSTORMS Robots',
author='Brian Blais',
author_email='bblais@bryant.edu',
maintainer='Marek Šuppa',
... | #!/usr/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(name='pynxc',
version='0.1.7',
description='A Python to NXC Converter for programming '
'LEGO MINDSTORMS Robots',
author='Brian Blais',
author_email='bblais@bryant.edu',
maintainer='Marek Šuppa',
... |
Add a dependency that got dropped. | """Setup data for aib2ofx."""
from setuptools import setup
setup(
name='aib2ofx',
description='Download data from aib.ie in OFX format',
version='0.6',
author='Jakub Turski',
author_email='yacoob@gmail.com',
url='http://github.com/yacoob/aib2ofx',
packages=['aib2ofx'],
entry_points={
... | """Setup data for aib2ofx."""
from setuptools import setup
setup(
name='aib2ofx',
description='Download data from aib.ie in OFX format',
version='0.6',
author='Jakub Turski',
author_email='yacoob@gmail.com',
url='http://github.com/yacoob/aib2ofx',
packages=['aib2ofx'],
entry_points={
... |
Improve content listing plugin's admin form | from fluent_contents.forms import ContentItemForm
#from icekit.content_collections.abstract_models import AbstractCollectedContent
from .models import ContentListingItem
class ContentListingAdminForm(ContentItemForm):
class Meta:
model = ContentListingItem
fields = '__all__'
# def __init__... | from django.forms import ModelChoiceField
from django.contrib.contenttypes.models import ContentType
from fluent_contents.forms import ContentItemForm
from .models import ContentListingItem
class ContentTypeModelChoiceField(ModelChoiceField):
def label_from_instance(self, content_type):
return u".".joi... |
Use '!=' instead of '>' when checking for mtime changes. | #!/usr/bin/env python
import os
import sys
from os.path import getmtime
# Parse script arguments and configuration files.
# ...
WATCHED_FILES = [__file__]
WATCHED_FILES_MTIMES = [(f, getmtime(f)) for f in WATCHED_FILES]
while True:
# Wait for inputs and act on them.
# ...
# Check whether a watched file... | #!/usr/bin/env python
import os
import sys
from os.path import getmtime
# Parse script arguments and configuration files.
# ...
WATCHED_FILES = [__file__]
WATCHED_FILES_MTIMES = [(f, getmtime(f)) for f in WATCHED_FILES]
while True:
# Wait for inputs and act on them.
# ...
# Check whether a watched file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.