Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix assumption that tornado.web was imported. | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn import __version__... | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
import tornado.web
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn... |
Fix proper default values for metadata migration | """Add movie metadata (imdb rating, number of votes, metascore) and relevancy
Revision ID: 2c240cb3edd1
Revises: 588336e02ca
Create Date: 2014-02-09 13:46:18.630000
"""
# revision identifiers, used by Alembic.
revision = '2c240cb3edd1'
down_revision = '588336e02ca'
from alembic import op
import sqlalchemy as sa
d... | """Add movie metadata (imdb rating, number of votes, metascore) and relevancy
Revision ID: 2c240cb3edd1
Revises: 588336e02ca
Create Date: 2014-02-09 13:46:18.630000
"""
# revision identifiers, used by Alembic.
revision = '2c240cb3edd1'
down_revision = '588336e02ca'
from alembic import op
import sqlalchemy as sa
d... |
Make catch-all actually catch all | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... |
Use newer interface for filtering | # -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.blob.interfaces import IATBlobImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, ui... | # -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.contenttypes.interfaces import IImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, u... |
Change data access script to issue SELECTs that actually return a value | #!/usr/bin/env python
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...... | #!/usr/bin/env python
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
... |
Bring forward more contents into top namespace | from .__about__ import __version__
from .compiler import RDLCompiler
from .walker import RDLListener, RDLWalker
from .messages import RDLCompileError
| from .__about__ import __version__
from .compiler import RDLCompiler
from .walker import RDLListener, RDLWalker
from .messages import RDLCompileError
from .node import AddressableNode, VectorNode, SignalNode
from .node import FieldNode, RegNode, RegfileNode, AddrmapNode, MemNode
from .component import AddressableCom... |
Fix response with json for get_work | import json
from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from breach.strategy import Strategy
from breach.models import Victim
def get_work(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
... | import json
from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from breach.strategy import Strategy
from breach.models import Victim
def get_work(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
... |
Make identifiers camel-case; remove redundant space. | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: Class... | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
# Camel-caes
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
... |
Fix test for python 2 | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((*CAMERA_RESOLUTION, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(tes... | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((MAX_WIDTH, MAX_HEIGHT, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(... |
Bump version for v0.7.0 release | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0-dev"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except Nam... |
Add Slack channels the Slack Plugin | from drupdates.utils import *
from drupdates.constructors.reports import *
import json
class slack(Reports):
def __init__(self):
self.currentDir = os.path.dirname(os.path.realpath(__file__))
self.settings = Settings(self.currentDir)
def sendMessage(self, reportText):
""" Post the report to a Slack ch... | from drupdates.utils import *
from drupdates.constructors.reports import *
import json
class slack(Reports):
def __init__(self):
self.currentDir = os.path.dirname(os.path.realpath(__file__))
self.settings = Settings(self.currentDir)
def sendMessage(self, reportText):
""" Post the report to a Slack ch... |
Raise exception if sdb does not exist | #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# 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 requir... | #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# 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 requir... |
Fix missing self in class methods and wrong formatting | class TestCase:
def assertEqual(value, expected):
if value != expected:
raise CaseFailed("{0} != {1}")
def assertTrue(value):
assertEqual(value, True)
def assertFalse(value):
assertEqual(value, False)
class CaseFailed(Exception):
def __init__(self, message):
... | class TestCase:
def assertEqual(self, value, expected):
if value != expected:
raise CaseFailed("{0} != {1}".format(value, expected))
def assertTrue(self, value):
assertEqual(value, True)
def assertFalse(self, value):
assertEqual(value, False)
class CaseFailed(Exceptio... |
Fix linting errors in GoBot | from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
import math
import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r... | """
GoBot Example
"""
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
"""
GoBot
"""
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN... |
Fix the keywords, url, and description. |
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
n... |
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
n... |
Use relative path in for LICENSE | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='orges',
version='0.0.1',
description='OrgES Package - Organic Computing for Evolution Strategies',
long_description=open('README.rst').read(),
author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
author_email='... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages, Extension
import os
setup(
name='orges',
version='0.0.1',
description='OrgES Package - Organic Computing for Evolution Strategies',
long_description=open('README.rst').read(),
author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
autho... |
Add faceting test to Group index | from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
... | from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
... |
Add ability to set insttoken | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
def getBaseURL... | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... |
Disable annoying syncdb info for volatile db | from .util import import_module
import logging
def init():
"""
Initialize nazs environment, setup logging, processes and all
needed stuff for running nazs
"""
from django.core import management
# Sync volatile db, TODO set correct permissions
management.call_command('syncdb', database='vo... | from .util import import_module
import logging
def init():
"""
Initialize nazs environment, setup logging, processes and all
needed stuff for running nazs
"""
from django.core import management
# Sync volatile db, TODO set correct permissions
management.call_command('syncdb',
... |
Set message attribute on InvalidValidationResponse error class. | __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):... | __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):... |
Add help text for plugin enable option | from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.en... | from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.en... |
Fix bug where only PDF files in current directory can be found | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... |
Add the support for custom setting given by bash script (run as "python_script.py sizeOfDataset numOfEpochs nameOfExp") | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
#d = load_8376_resized_150x150(desired_number=10)
#d.statistics()
start = time.time()
print time.ctime()
main_vgg16(TMP_size_of_dataset=100, TMP_num_of_epochs=150, name_of_the_experiment = '... | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
import sys
# DEFAULT VALUES:
TMP_size_of_dataset=100
TMP_num_of_epochs=150
name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth'
# python python_script.py var1 var2 var3
if len(sys.argv... |
Remove BaseListingMixin as superclass for SubmissionListingMixin | """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin
class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
"""Adds additional methods pertaining to Submission ... | """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_k... |
Change number-jokes to match the tutorial. | import random
from botfriend.bot import TextGeneratorBot
class ExampleBot(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setu... | import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
set... |
Return exception for non ajax | import json
from django.http import HttpResponse
from django.conf import settings
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {'error': str(exception)}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb)... | import json
from django.http import HttpResponse
from django.conf import settings
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {'error': str(exception)}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb)... |
Set default race and class without extra database queries | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... |
Remove monkey patching in favor of inheritance for SpatialReference | """Spatial reference systems"""
from osgeo import osr
# Monkey patch SpatialReference since inheriting from SWIG classes is a hack
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
retu... | """Spatial reference systems"""
from osgeo import osr
class BaseSpatialReference(osr.SpatialReference):
"""Base class for extending osr.SpatialReference."""
def __repr__(self):
return self.wkt
@property
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = ... |
Add parameter for log level | """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# If any issues related to global state arise, the following class should
# be ... | """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# https://softwareengineering.stackexchange.com/questions/148108/why-is-global-... |
Update leaflet request to be over https | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... |
Simplify importer paths after dockerization | import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART... | import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART... |
Update docs/params for initialization methods. | """
Implementation of methods for sampling initial points.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from ..utils import ldsample
# exported symbols
__all__ = ['init_middle', '... | """
Implementation of methods for sampling initial points.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from ..utils import ldsample
# exported symbols
__all__ = ['init_middle', '... |
Add feature importance bar chart. | from libgbdt import Forest as _Forest
class Forest:
def __init__(self, forest):
if type(forest) is str or type(forest) is unicode:
self._forest = _Forest(forest)
elif type(forest) is _Forest:
self._forest = forest
else:
raise TypeError, 'Unsupported fores... | from libgbdt import Forest as _Forest
class Forest:
def __init__(self, forest):
if type(forest) is str or type(forest) is unicode:
self._forest = _Forest(forest)
elif type(forest) is _Forest:
self._forest = forest
else:
raise TypeError, 'Unsupported fores... |
Set correct gen_description in rss importer. |
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url i... |
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url i... |
Change download and documentation URLs. | #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
... | #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
... |
Make sure the dependencies get installed | from distutils.core import setup
setup(
name='wunderclient',
packages=['wunderclient'],
version='0.0.1',
description='A Wunderlist API client',
author='Kevin LaFlamme',
author_email='k@lamfl.am',
url='https://github.com/lamflam/wunderclient',
download_url='https://github.com/lamflam/wun... | import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
requires = []
with open(os.path.join(here, 'requirements.txt')) as f:
for line in f.read().splitlines():
if line.find('--extra-index-url') == -1:
requires.append(line)
setup(
name='wunderclient',... |
Make compilation of extensions optional through an environment variable. | from distutils.core import setup
from distutils.core import Extension
setup(name = 'wrapt',
version = '0.9.0',
description = 'Module for decorators, wrappers and monkey patching.',
author = 'Graham Dumpleton',
author_email = 'Graham.Dumpleton@gmail.com',
license = 'BSD',
url = 'http... | import os
from distutils.core import setup
from distutils.core import Extension
with_extensions = os.environ.get('WRAPT_EXTENSIONS', 'true')
with_extensions = (with_extensions.lower() != 'false')
setup_kwargs = dict(
name = 'wrapt',
version = '0.9.0',
description = 'Module for decorators, wrappers ... |
Send what state is saved | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
... | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
... |
Make data source module for hss division debug-only, until it is fixed | # -*- coding: utf-8 -*-
from flask.ext.babel import gettext
from ..division import Division
from database_utils import init_db
from ldap_utils import init_ldap
from ipaddress import IPv4Network
import user
def init_context(app):
init_db(app)
init_ldap(app)
division = Division(
name='hss',
display_n... | # -*- coding: utf-8 -*-
from flask.ext.babel import gettext
from ..division import Division
from database_utils import init_db
from ldap_utils import init_ldap
from ipaddress import IPv4Network
import user
def init_context(app):
init_db(app)
init_ldap(app)
division = Division(
name='hss',
display_n... |
Add lsst-dd-rtd-theme as explicit dependency | from setuptools import setup, find_packages
import os
packagename = 'documenteer'
description = 'Tools for LSST DM documentation projects'
author = 'Jonathan Sick'
author_email = 'jsick@lsst.org'
license = 'MIT'
url = 'https://github.com/lsst-sqre/documenteer'
version = '0.1.7'
def read(filename):
full_filename... | from setuptools import setup, find_packages
import os
packagename = 'documenteer'
description = 'Tools for LSST DM documentation projects'
author = 'Jonathan Sick'
author_email = 'jsick@lsst.org'
license = 'MIT'
url = 'https://github.com/lsst-sqre/documenteer'
version = '0.1.7'
def read(filename):
full_filename... |
Bring US site shipping repo up-to-date | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... |
Use inout proxy script for log. | import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
# ['langserver-go', '-trace', '-logfile', '/tmp/lan... | import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["/bin/bash", "/opt/rls/wrapper.sh"],
# ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
... |
Add the rest of the basic parsing code | # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
self.romData = open(romPath, 'rb').read()
if "NES" not in self.romData[0:3]:
print "Unrecognized format!"
return None
... | # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
romData = open(romPath, 'rb').read()
headerSize = 0x10
bankSize = 0x4000
vromBankSize = 0x2000
if "NES" not in romData[0:4]:
... |
Make sure we have a recipient before sending notification | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... |
Replace console output for raw txt | import requests
import os
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, d... | import requests
import os
import sys
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
... |
Raise throttle limit for anon users | REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '50/day',
}
}
| REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5000/day',
}
}
|
Enforce ordering on cluster nodes endpoint | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... |
Add the action required to fix the issue to the warning | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... |
Set default taking access for GradingProjectSurvey to org. | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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... |
Use Django simple_tag instead of classytags because there were no context in template rendering. | from classytags.helpers import InclusionTag
from django import template
from django.template.loader import render_to_string
register = template.Library()
class CookielawBanner(InclusionTag):
"""
Displays cookie law banner only if user has not dismissed it yet.
"""
template = 'cookielaw/banner.html'... | # -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
return render_to_st... |
Convert every datetime field into float. | # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREAT... | # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREAT... |
Remove the admin from the url resolver | # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# ... | # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# ... |
Remove hack for sqpyte again | #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plug... | #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plug... |
Add the proper tests for the base app | from django.test import TestCase
from splinter import Browser
class TestBaseViews(TestCase):
def setUp(self):
self.browser = Browser('chrome')
def tearDown(self):
self.browser.quit()
def test_home(self):
self.browser.visit('http://localhost:8000')
test_string = 'Hello, w... | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from splinter import Browser
class TestBaseViews(StaticLiveServerTestCase):
"""Integration test suite for testing the views in the app: base.
Test the url for home and the basefiles like robots.txt and hum... |
Change choice_id field to choice | from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Mod... | from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Mod... |
Add get method to settings | from flask import Flask
from roomcontrol.music import music_service
from roomcontrol.light import light_service
from roomcontrol.alarm import alarm_service
app = Flask(__name__)
app.register_blueprint(music_service, url_prefix='/music')
app.register_blueprint(light_service, url_prefix='/light')
app.register_blueprint(... | from flask import Flask
from roomcontrol.music import music_service
from roomcontrol.light import light_service
from roomcontrol.alarm import alarm_service
app = Flask(__name__)
app.register_blueprint(music_service, url_prefix='/music')
app.register_blueprint(light_service, url_prefix='/light')
app.register_blueprint(... |
Improve names to reduce line size | from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languag... | from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languag... |
Fix spelling in coord_utils import. | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
imp... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
imp... |
Allow meals with unknown payer | from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')... | from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')... |
Rename the filename argument to spreadsheet. | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, filename):
"""
Updates the qiprofile database from the clinical... | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clini... |
Fix bugs in rf and xgb models | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_to... | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_to... |
Increment version number, includes bug fixes for synchronized decorator and KeyboardInterrupt handling | #!/usr/bin/env python
from distutils.core import setup
setup(
name = "deco",
version = "0.5.1",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman',
author_email='asherman1024@gmail.com',
url='https://github.com/alex-sherman/deco')
| #!/usr/bin/env python
from distutils.core import setup
setup(
name = "deco",
version = "0.5.2",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman',
author_email='asherman1024@gmail.com',
url='https://github.com/alex-sherman/deco')
|
Include kv files in package. | from setuptools import setup, find_packages
import cplcom
setup(
name='CPLCom',
version=cplcom.__version__,
packages=find_packages(),
package_data={'cplcom': ['../media/*', './*.kv']},
install_requires=['moa', 'kivy'],
author='Matthew Einhorn',
author_email='moiein2000@gmail.com',
lice... | from setuptools import setup, find_packages
import cplcom
setup(
name='CPLCom',
version=cplcom.__version__,
packages=find_packages(),
package_data={'cplcom': ['../media/*', 'graphics.kv']},
install_requires=['moa', 'kivy'],
author='Matthew Einhorn',
author_email='moiein2000@gmail.com',
... |
Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served. | from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image')
]
| from django.conf import settings
from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path(getattr(settings, 'SERVE_QR_CODE_IMAGE_PATH', 'images/serve-qr-code-image/'), views.serve_qr_code_image, name='serve_qr_code_image')
]
|
Swap parse call for synchronous_parse | import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_str... | import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_str... |
Fix the name on the package from brew to brewday | from setuptools import find_packages
from setuptools import setup
setup(
name='brew',
version='0.0.1',
author='Chris Gilmer',
author_email='chris.gilmer@gmail.com',
maintainer='Chris Gilmer',
maintainer_email='chris.gilmer@gmail.com',
description='Brew Day Tools',
url='https://github.co... | from setuptools import find_packages
from setuptools import setup
setup(
name='brewday',
version='0.0.1',
author='Chris Gilmer',
author_email='chris.gilmer@gmail.com',
maintainer='Chris Gilmer',
maintainer_email='chris.gilmer@gmail.com',
description='Brew Day Tools',
url='https://github... |
Update sampledata generator to allow component resources | """Module for factories for tesing resources application."""
import random
from factory import DjangoModelFactory, Faker, post_generation
from factory.faker import faker
from resources.models import (
Resource,
ResourceComponent,
)
class ResourceFactory(DjangoModelFactory):
"""Factory for generating reso... | """Module for factories for tesing resources application."""
import random
from factory import DjangoModelFactory, Faker, post_generation
from factory.faker import faker
from resources.models import (
Resource,
ResourceComponent,
)
class ResourceFactory(DjangoModelFactory):
"""Factory for generating reso... |
Disable GUI testing for now |
from polyglotdb.gui.widgets.basic import DirectoryWidget
def test_directory_widget(qtbot):
widget = DirectoryWidget()
qtbot.addWidget(widget)
widget.setPath('test')
assert(widget.value() == 'test')
|
#from polyglotdb.gui.widgets.basic import DirectoryWidget
#def test_directory_widget(qtbot):
# widget = DirectoryWidget()
# qtbot.addWidget(widget)
# widget.setPath('test')
# assert(widget.value() == 'test')
|
Remove import for type annotation | from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=k... | import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
... |
Return easily identifiable values from User methods. | class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
return 'class method'
def __init__(self, name, age):
self.name = name
self.ag... | class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
return 'static_method return value'
@classmethod
def class_method(cls):
return 'class_method return value'
def __init__(self, name, ag... |
Initialize select dropdown for categories with maps | from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
def __init__(self, *args, **kwar... | from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
class Media:
js = ('js/se... |
Move init_app after DJANGO_SETTINGS_MODULE set up | #!/usr/bin/env python
import os
import sys
from website.app import init_app
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
init_app(set_backends=True, routes=False, attach_request_handlers=False... | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
from website.app import init_app
init_app(set_backends=True, routes=False, attach_request_handlers=... |
Add random people and rooms |
people = '123456'
room = 'abcdef'
# murder configuration
# who was where
# who is the murderer
# current configuration
# who was where
# player location
| import random
people = '123456'
room = 'abcdef'
# murder configuration
# who was where
# who is the murderer
# current configuration
# who was where
# player location
murder_config_people = list(people)
random.shuffle(murder_config_people)
murder_location = random.choice(room)
murderer = people[room.find(murder... |
Update environment variable name for port to listen on from VCAP_APP_PORT (deprecated) -> PORT | #!/usr/bin/env python
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return open('index.html').read()
port = os.getenv('VCAP_APP_PORT', '5000')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(port))
| #!/usr/bin/env python
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return open('index.html').read()
port = os.getenv('PORT', '5000')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(port))
|
Add default values for username and passwd and add a TODO. | #!/bin/python3
""" This script contains functions for the REST client.
Author: Julien Delplanque
"""
import http.client
import json
def get_pacman_pkgs_to_update(ip: str, username: str, passwd: str):
""" Get the list of packages from the REST server hosted by
the raspberry pi.
Keyword arg... | #!/bin/python3
""" This script contains functions for the REST client.
Author: Julien Delplanque
"""
import http.client
import json
def get_pacman_pkgs_to_update(ip: str, username: str=None, passwd: str=None):
""" Get the list of packages from the REST server hosted by
the raspberry pi.
T... |
Add weighted undirected graph in main() | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def prim():
"""Prim's Minimum Spanning Tree in weighted graph."""
pass
def main():
pass
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim():
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|... |
Support Django being on the path but unused. | try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd', 'VERSION']
VERSION = (0, 1)
if settings:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
statsd = Stat... | try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd', 'VERSION']
VERSION = (0, 1)
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
... |
Create test to check that a person has been added | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTru... | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTru... |
Add --regression command line option | from __future__ import absolute_import, division, print_function
from dials.conftest import regression_data, run_in_tmpdir
| from __future__ import absolute_import, division, print_function
from dials.conftest import pytest_addoption, regression_data, run_in_tmpdir
|
Include createHour field that will streamline groupBy operations in the db | from django.db import models
from django.utils.timezone import now
class Reading(models.Model):
# Authenticating on user
owner = models.ForeignKey('auth.User', related_name='api',
default='')
# When the row gets made
created = models.DateTimeField(auto_now_add=True)
... | from django.db import models
from django.utils.timezone import now
class Reading(models.Model):
# Authenticating on user
owner = models.ForeignKey('auth.User', related_name='readings',
default='')
# When the row gets made
created = models.DateTimeField(auto_now_add=True)
... |
Modify parsing logic for last_modified in JSON | # Stdlib imports
from datetime import datetime
from pytz import timezone
# Core Django imports
from django.utils.timezone import utc
# Imports from app
from sync_center.models import Map, KML
def get_update_id_list(model_name, req_data):
db_data = None
if model_name == 'map':
db_data = Map.objects.... | # Stdlib imports
from datetime import datetime
from pytz import timezone
# Core Django imports
from django.utils.timezone import utc
# Imports from app
from sync_center.models import Map, KML
def get_update_id_list(model_name, req_data):
db_data = None
if model_name == 'map':
db_data = Map.objects.... |
Add a convenience method to get the player ship | from . import packet as p
class Tracker:
def __init__(self):
self.objects = {}
def update_object(self, record):
try:
oid = record['object']
except KeyError:
return
else:
self.objects.setdefault(oid, {}).update(record)
def remove_object(s... | from . import packet as p
class Tracker:
def __init__(self):
self.objects = {}
@property
def player_ship(self):
for _obj in self.objects.values():
if _obj['type'] == p.ObjectType.player_vessel:
return _obj
return {}
def update_object(self, record):
... |
Change process killing from -9 to -15 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
clean zombie processes
"""
# @author chengdujin
# @contact chengdujin@gmail.com
# @created Aug. 22, 2013
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
import subprocess
def clean():
"""
kill zombie processes if there is any
"""
command ... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
clean zombie processes
"""
# @author chengdujin
# @contact chengdujin@gmail.com
# @created Aug. 22, 2013
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
import subprocess
def clean():
"""
kill zombie processes if there is any
"""
command ... |
Fix provider check causing Devshell auth failure | # -*- coding: utf-8 -*-
# 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 require... | # -*- coding: utf-8 -*-
# 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 require... |
Add required dependency to mqo_programs. | # -*- coding: utf-8 -*-
{
'name': "MQO Programs",
'summary': """Manage programs""",
'description': """
MQO module for managing programs:
""",
'author': "Your Company",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules list... | # -*- coding: utf-8 -*-
{
'name': "MQO Programs",
'summary': """Manage programs""",
'description': """
MQO module for managing programs:
""",
'author': "Your Company",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules list... |
Fix a bug on a query example for python | # This example shows how queries can be executed in an iterative manner.
# Iterative evaluation will be slower, as more server requests are performed.
#
# Documentation: http://docs.basex.org/wiki/Clients
#
# (C) BaseX Team 2005-12, BSD License
import BaseXClient, time
try:
# create session
session = B... | # This example shows how queries can be executed in an iterative manner.
# Iterative evaluation will be slower, as more server requests are performed.
#
# Documentation: http://docs.basex.org/wiki/Clients
#
# (C) BaseX Team 2005-12, BSD License
import BaseXClient, time
try:
# create session
session = B... |
Add basic tests for configuration | """Tests for the config command
"""
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR
class TestBasicLoading(Confi... | """Tests for the config command
"""
import pytest
import textwrap
from pip.status_codes import ERROR
from tests.lib.configuration_helpers import kinds, ConfigurationFileIOMixin
def test_no_options_passed_should_error(script):
result = script.pip('config', expect_error=True)
assert result.returncode == ERROR... |
Allow arbitrary kwargs for die utility function. by: Glenn, Giles | # Copyright (c) 2011 Resolver Systems Ltd.
# All Rights Reserved
#
try:
import unittest2 as unittest
except ImportError:
import unittest
from datetime import timedelta
from mock import call
class ResolverTestMixins(object):
def assertCalledOnce(self, mock, *args, **kwargs):
if mock.call_args_lis... | # Copyright (c) 2011 Resolver Systems Ltd.
# All Rights Reserved
#
try:
import unittest2 as unittest
except ImportError:
import unittest
from datetime import timedelta
from mock import call
class ResolverTestMixins(object):
def assertCalledOnce(self, mock, *args, **kwargs):
if mock.call_args_lis... |
Allow governing templatetag to be called with a Statement object | from django import template
register = template.Library()
@register.filter(name='governing')
def governing(party, date):
return party.is_governing(date)
| from django import template
from ..models import Party, Statement
register = template.Library()
@register.filter(name='governing')
def governing(obj, date=None):
if isinstance(obj, Party):
assert date is not None, "Date must be supplied when 'govern' is called with a Party object"
return obj.is_go... |
Fix the grefs route in the airship server | import os
import json
from flask import Flask, render_template
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels()]
jsonbody = json.dumps(channels)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def make_airship(s... | import os
import json
from flask import Flask, render_template
def jsonate(obj, escaped):
jsonbody = json.dumps(obj)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels... |
Use 2to3 for Python 3 | #!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
... | #!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
... |
Remove infinite loop if user is neither native nor verified | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api'):
... | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... |
Add RefusePickup class (for parsing) | from .util import XPathObject
class RefusePickup(XPathObject):
"""Defines attribute to XPath specification matching"""
input_properties = {
'success_msg': '//*[@id="nConf"]/h1',
'route_garbage': '//*[@id="nConf"]/strong[1]',
'next_pickup_garbage': '//*[@id="nConf"]/strong[2]',
... | |
Update unit tests to match correct behaviour | import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from smartbot import events
class TestEvents(unittest.TestCase):
def test_empty(self):
event = events.Event()
self.assertEqual(len(event.trigger()), 0)
def test_with_handlers(... | import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from smartbot import events
class TestEvents(unittest.TestCase):
def test_empty(self):
event = events.Event()
self.assertEqual(len(event.trigger()), 0)
def test_with_handlers(... |
Change interpolation sentinels to prevent collissions with pillar data | #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–14 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
import os, sys
from version import RECLASS_NAME
# defaults for the command-line options
OPT_STORAGE_TYPE... | #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–14 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
import os, sys
from version import RECLASS_NAME
# defaults for the command-line options
OPT_STORAGE_TYPE... |
Add print_stats to init file | # -*- coding: utf-8 -*-
__author__ = 'Vauxoo'
__email__ = 'info@vauxoo.com'
__version__ = '0.1.0'
| # -*- coding: utf-8 -*-
from pstats_print2list import print_stats
__author__ = 'Vauxoo'
__email__ = 'info@vauxoo.com'
__version__ = '0.1.0'
|
Add Exception to all with's block. | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 4:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.strip() for key in keys]
... | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 4:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.s... |
Adjust test (refers prev commit) | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import unittest
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
@unittest.skip('Not yet implemented')
def test_get_absolute_url(self):
user = Bakery... | # -*- coding: utf-8 -*-
from django.test import TestCase
from bakery.auth.models import BakeryUser
class TestBakeryUserModel(TestCase):
def test_get_absolute_url(self):
user = BakeryUser.objects.create_user('user', 'password')
user.name = 'John Doe'
self.assertEqual(user.get_absolute_ur... |
Save event emitter y producer reference in relayer instance | from kafka import KafkaProducer
from .event_emitter import EventEmitter
from .exceptions import ConfigurationError
__version__ = '0.1.3'
class Relayer(object):
def __init__(self, logging_topic, context_handler_class, kafka_hosts=None, topic_prefix='', topic_suffix='', source=''):
self.logging_topic = l... | from kafka import KafkaProducer
from .event_emitter import EventEmitter
from .exceptions import ConfigurationError
__version__ = '0.1.3'
class Relayer(object):
def __init__(self, logging_topic, context_handler_class, kafka_hosts=None, topic_prefix='', topic_suffix='', source=''):
self.logging_topic = l... |
Fix the VFG path test. | import angr
import logging
import os
l = logging.getLogger("angr_tests")
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)),
'../../binaries/tests'))
def test_vfg_paths():
p = angr.Project(os.path.join(test_location, "x86_64/track_user_input"))
main_a... | import angr
import logging
import os
l = logging.getLogger("angr_tests")
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)),
'../../binaries/tests'))
def test_vfg_paths():
p = angr.Project(os.path.join(test_location, "x86_64/track_user_input"))
main_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.