Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix django-hvad version in requirements | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
import multilingual_survey
# 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... | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
import multilingual_survey
# 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... |
Fix exception test function for python3. | import sys
import unittest
#sys.path.insert(0, os.path.abspath('..'))
import github3
class BaseTest(unittest.TestCase):
api = 'https://api.github.com/'
kr = 'kennethreitz'
sigm = 'sigmavirus24'
todo = 'Todo.txt-python'
gh3py = 'github3py'
def setUp(self):
super(BaseTest, self).setUp()... | import sys
import unittest
#sys.path.insert(0, os.path.abspath('..'))
import github3
class BaseTest(unittest.TestCase):
api = 'https://api.github.com/'
kr = 'kennethreitz'
sigm = 'sigmavirus24'
todo = 'Todo.txt-python'
gh3py = 'github3py'
def setUp(self):
super(BaseTest, self).setUp()... |
Allow to print the ssh command | import click
@click.command()
@click.argument('environment')
@click.pass_obj
def ssh(lancet, environment):
"""
SSH into the given environment, based on the dploi configuration.
"""
namespace = {}
with open('deployment.py') as fh:
code = compile(fh.read(), 'deployment.py', 'exec')
... | from shlex import quote
import click
@click.command()
@click.option('-p', '--print/--exec', 'print_cmd', default=False,
help='Print the command instead of executing it.')
@click.argument('environment')
@click.pass_obj
def ssh(lancet, print_cmd, environment):
"""
SSH into the given environment, ... |
Format the stat name with environmenbt | from statsd import StatsClient
class StatsdClient(StatsClient):
def init_app(self, app, *args, **kwargs):
self.active = app.config.get('STATSD_ENABLED')
self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api."
if self.active:
StatsClient.__init__(
... | from statsd import StatsClient
class StatsdClient(StatsClient):
def init_app(self, app, *args, **kwargs):
self.active = app.config.get('STATSD_ENABLED')
self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api."
if self.active:
StatsClient.__init__(
... |
Add version information in module | # -*- coding: utf-8 -*-
"""
=========================
Base Library (:mod:`ibei`)
=========================
.. currentmodule:: ibei
"""
from main import uibei, SQSolarcell, DeVosSolarcell
| # -*- coding: utf-8 -*-
"""
=========================
Base Library (:mod:`ibei`)
=========================
.. currentmodule:: ibei
"""
from main import uibei, SQSolarcell, DeVosSolarcell
__version__ = "0.0.2"
|
Use HostAddressOpt for opts that accept IP and hostnames | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
Set default backend, and minimum statsmodels version | import warnings
try:
import matplotlib
# matplotlib.use('TkAgg')
HAS_MPL = True
except ImportError:
HAS_MPL = False
try:
import statsmodels.api as sm
HAS_STATSM = True
except ImportError:
HAS_STATSM = False
try:
from numba import jit, vectorize
except ImportError:
warnings.warn("N... | import warnings
DEFAULT_MPL_BACKEND = 'TkAgg'
try:
import matplotlib
# This is necessary. Random backends might respond incorrectly.
matplotlib.use(DEFAULT_MPL_BACKEND)
HAS_MPL = True
except ImportError:
HAS_MPL = False
try:
import statsmodels.api as sm
version = [int(i) for i in sm.versio... |
Fix issue with printer device-id | from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_de... | from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_de... |
Use basename instead of os.path.split(...)[-1] | from tornado.web import authenticated
from os.path import split
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@aut... | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@... |
Change command option, need to specify file name now | #!/usr/bin/python
import serial
import string
import io
import time
import sys
if __name__ == '__main__':
port = "/dev/ttyUSB0"
baudrate = "57600"
second = 0.1
if (len(sys.argv) < 3):
print("Usage: serial_dump.py /dev/ttyUSB0 57600")
exit()
elif (len(sys.argv) == 3):
port = sys.argv[1]
baudrate = sys... | #!/usr/bin/python
import serial
import string
import io
import time
import sys
if __name__ == '__main__':
port = "/dev/ttyUSB0"
baudrate = "57600"
second = 0.001
if (len(sys.argv) < 4 ):
print("Usage: \n./serial_dump.py /dev/ttyUSB0 57600 file_name 0.01")
exit()
elif (len(sys.argv) == 4):
port = sys.a... |
Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked" | import sublime, sublime_plugin
def pyramid_sort(txt):
txt = list(filter(lambda s: s.strip(), txt))
txt.sort(key = lambda s: len(s))
return txt
class PyramidSortCommand(sublime_plugin.TextCommand):
def run(self, edit):
regions = [s for s in self.view.sel() if not s.empty()]
if regions:
for r in regions:
... | #
# 123
# 12
# 1
import sublime, sublime_plugin
def pyramid_sort(txt):
txt = list(filter(lambda s: s.strip(), txt))
txt.sort(key = lambda s: len(s))
return txt
class PyramidSortCommand(sublime_plugin.TextCommand):
def run(self, edit):
regions = [s for s in self.view.sel() if not s.empty()]
if regions:
... |
Add a new line at the end of the file | """
Package database utilities for creating and modifying the database.
"""
from os.path import split, splitext
from json import load
f = open("packages.json")
data = load(f)
g = []
for p in data:
pkg = {
"name": p["name"],
"dependencies": p["dependencies"],
"version": p["versi... | """
Package database utilities for creating and modifying the database.
"""
from os.path import split, splitext
from json import load
f = open("packages.json")
data = load(f)
g = []
for p in data:
pkg = {
"name": p["name"],
"dependencies": p["dependencies"],
"version": p["versi... |
Fix the directory structure inside the source. | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies',
version='2014-04-14',
sources=['http://storage.bos.xamarin.com/bot-pro... | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies',
version='2014-04-14',
sources=['http://storage.bos.xamarin.com/bot-pro... |
Remove backwards compatibility with Django < 1.8. | # coding: utf-8
from __future__ import unicode_literals
import re
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage
from django.dispatch import receiver
from django.utils.lru_cache import lru_cache
from django.utils.module... | # coding: utf-8
from __future__ import unicode_literals
import re
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage
from django.dispatch import receiver
from django.test.signals import setting_changed
from django.utils.lru... |
Use UTF-8 in Conan recipe | from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepag... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Tim... |
Remove unintentional commas from argument list | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... |
Add users to the list of models. | from pymongo import MongoClient
# Magic decorator for defining constants
def constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class Model:
def __init__(self):
pass
@staticmethod
@constant
def COLLECTION_... | from pymongo import MongoClient
# Magic decorator for defining constants
def constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class Model:
def __init__(self):
pass
@staticmethod
@constant
def COLLECTION_... |
Fix an occurrence of E402 | """
WSGI config for test2 project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... | import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test2.settings")
application = get_wsgi_application()
|
Check if first_name is set for profile beforehand | import yaml
import sys
from conversation import Conversation
def isLocal():
return len(sys.argv) > 1 and sys.argv[1] == "--local"
if isLocal():
from local_mic import Mic
else:
from mic import Mic
if __name__ == "__main__":
print "==========================================================="
prin... | import yaml
import sys
from conversation import Conversation
def isLocal():
return len(sys.argv) > 1 and sys.argv[1] == "--local"
if isLocal():
from local_mic import Mic
else:
from mic import Mic
if __name__ == "__main__":
print "==========================================================="
prin... |
DELETE - delete default setting | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "QuesCheetah.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Change 1 based range so it counts up to n | #!/usr/bin/env python
from nodes import Node
class Sort(Node):
char = "S"
args = 1
results = 1
@Node.test_func([[2,3,4,1]], [[1,2,3,4]])
@Node.test_func(["test"], ["estt"])
def func(self, a: Node.indexable):
"""sorted(a) - returns the same type as given"""
if isinstance(a,... | #!/usr/bin/env python
from nodes import Node
class Sort(Node):
char = "S"
args = 1
results = 1
@Node.test_func([[2,3,4,1]], [[1,2,3,4]])
@Node.test_func(["test"], ["estt"])
def func(self, a: Node.indexable):
"""sorted(a) - returns the same type as given"""
if isinstance(a,... |
Set temporary ALLOWED_HOSTS for Vagrant testing. | import os
from lcp.settings.base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
| import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
|
Fix old import of math intrinsics | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['math_intrinsic',
'string_intrinsic']
... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['string_intrinsic']
for k in mods:
mod =... |
Convert to flags=value for future compatibility | import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
... | import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
... |
Create metrics table in EnsoMetricsGraph.py |
from EnsoMetricsGraph import EnsoMetricsTable
#EnsoMetrics =[{'col1':'IPSL-CM5A-LR','col2':0.82,'col3':4.1},
# {'col1':'IPSL-CM5A-MR','col2':1.2,'col3':4.5}]
EnsoMetrics =[[1,2,3],[4,5,6]]
fig=EnsoMetricsTable(EnsoMetrics, 'EnsoMetrics')
|
from EnsoMetricsGraph import EnsoMetricsTable
EnsoMetrics =[['IPSL-CM5A-LR','0.82','4.1'],
['IPSL-CM5A-MR','1.2','4.5']]
#EnsoMetrics =[[1,2,3],[4,5,6]]
fig=EnsoMetricsTable(EnsoMetrics, 'EnsoMetrics')
|
Update Point to use normal dictionaries for its coordinates | from collections import OrderedDict
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> f... |
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
... |
Fix issue with auto complete when more than 1 editor has been created | from pyqode.core import modes
from pyqode.core.api import TextHelper
class AutoCompleteMode(modes.AutoCompleteMode):
def __init__(self):
super(AutoCompleteMode, self).__init__()
self.QUOTES_FORMATS.pop("'")
self.SELECTED_QUOTES_FORMATS.pop("'")
self.MAPPING.pop("'")
def _on_ke... | from pyqode.core import modes
from pyqode.core.api import TextHelper
class AutoCompleteMode(modes.AutoCompleteMode):
def __init__(self):
super(AutoCompleteMode, self).__init__()
try:
self.QUOTES_FORMATS.pop("'")
self.SELECTED_QUOTES_FORMATS.pop("'")
self.MAPPING... |
Fix default values of Argument Parser | # -*- coding: utf-8 -*-
from queries import Grok
def print_monthly_views(site, pages, year, month):
grok = Grok(site)
for page in pages:
result = grok.get_views_for_month(page, year, month)
print result['daily_views']
def main():
""" main script. """
from argparse import ArgumentPar... | # -*- coding: utf-8 -*-
from queries import Grok
def print_monthly_views(site, pages, year, month):
grok = Grok(site)
for page in pages:
result = grok.get_views_for_month(page, year, month)
print result['daily_views']
def main():
""" main script. """
from argparse import ArgumentPar... |
Fix platform import on Linux using python3 | import sys
resolver = None
if sys.platform == "linux2":
from . import linux
resolver = linux.Resolver
elif sys.platform == "darwin":
from . import osx
resolver = osx.Resolver
elif sys.platform.startswith("freebsd"):
from . import osx
resolver = osx.Resolver
elif sys.platform == "win32":
fr... | import sys
import re
resolver = None
if re.match(r"linux(?:2)?", sys.platform):
from . import linux
resolver = linux.Resolver
elif sys.platform == "darwin":
from . import osx
resolver = osx.Resolver
elif sys.platform.startswith("freebsd"):
from . import osx
resolver = osx.Resolver
elif sys.pla... |
Load github config from external file | from django.apps import AppConfig
class SsoConfig(AppConfig):
name = 'sso'
github_client_id = '844189c44c56ff04e727'
github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
| import json
import os.path
from django.apps import AppConfig
from fmproject import settings
class SsoConfig(AppConfig):
base_config = json.load(
open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
)
name = 'sso'
github_client_id = base_config['github']['client_id']
github_cli... |
Check if we're already in the channel; Improved parameter parsing | from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsL... | from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsL... |
Fix truncated command and options | #!/usr/bin/env python
if __name__ == '__main__':
import sys
import os
import gitautodeploy
sys.stderr.write("\033[1;33m[WARNING]\033[0;33m GitAutoDeploy.py is deprecated. Please use \033[1;33m'python gitautodeploy%s'\033[0;33m instead.\033[0m\n" % (' ' + ' '.join(sys.argv[1:])).strip())
gitautodepl... | #!/usr/bin/env python
if __name__ == '__main__':
import sys
import os
import gitautodeploy
sys.stderr.write("\033[1;33m[WARNING]\033[0;33m GitAutoDeploy.py is deprecated. Please use \033[1;33m'python gitautodeploy%s'\033[0;33m instead.\033[0m\n" % (' ' + ' '.join(sys.argv[1:])).rstrip())
gitautodep... |
Test for multiple waiters on a signal | import os
import signal
import diesel
state = {'triggered':False}
def waiter():
diesel.signal(signal.SIGUSR1)
state['triggered'] = True
def test_can_wait_on_os_signals():
# Start our Loop that will wait on USR1
diesel.fork(waiter)
# Let execution switch to the newly spawned loop
diesel.slee... | import os
import signal
import diesel
from diesel.util.event import Countdown
state = {'triggered':False}
def waiter():
diesel.signal(signal.SIGUSR1)
state['triggered'] = True
def test_can_wait_on_os_signals():
# Start our Loop that will wait on USR1
diesel.fork(waiter)
# Let execution switch... |
Fix case sensitive LDAP attributes | from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP g... | from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP g... |
Add report making for facility | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from reports_monitoring import *
store = pd.HDFStore('../../data/processed/orbf_benin.h5')
data_orbf = store['data']
store.close()
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
... |
Remove unneeded 'reachedPoints' variable from Task class | from __future__ import unicode_literals
class Task(object):
def __init__(self, taskID, sheetID, name, description, maxPoints, reachedPoints=0):
self.id = taskID
self.sheetID = sheetID
self.name = name
self.description = description
self.maxPoints = maxPoints
self.r... | from __future__ import unicode_literals
class Task(object):
def __init__(self, taskID, sheetID, name, description, maxPoints):
self.id = taskID
self.sheetID = sheetID
self.name = name
self.description = description
self.maxPoints = maxPoints
|
Customize how fields on Email are displayed while adding & editing | from django.contrib import admin
from .models import Email
class EmailAdmin(admin.ModelAdmin):
exclude = ('targetted_users', 'is_sent')
admin.site.register(Email, EmailAdmin)
| from django.contrib import admin
from .models import Email
class EmailAdmin(admin.ModelAdmin):
readonly_fields = ('targetted_users', 'is_sent',)
add_fieldsets = (
(None, {
'fields': ('subject', 'message', 'post'),
}),
)
def get_fieldsets(self, request, obj=None):
... |
Implement the interface specification in two easy lines (plus an import). | import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format... | from functools import wraps
import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not a... |
Cover an even deeper nesting of closures for the overflow function, still commented out though. | #
# Kay Hayen, mailto:kayhayen@gmx.de
#
# Python test originally created or extracted from other peoples work. The
# parts from me are in the public domain. It is at least Free Software
# where it's copied from other people. In these cases, it will normally be
# indicated.
#
# If you submit Kay ... | #
# Kay Hayen, mailto:kayhayen@gmx.de
#
# Python test originally created or extracted from other peoples work. The
# parts from me are in the public domain. It is at least Free Software
# where it's copied from other people. In these cases, it will normally be
# indicated.
#
# If you submit Kay ... |
Update logging for message output and consistency. | import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug("GameModes: GET: Initializing GameObje... | import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug("GameModes: GET: Initializing GameObje... |
Add _clones attribute in new init method | __all__ = ['CloneableMeta']
class CloneableMeta(type):
def __new__(metacls, cg_name, bases, clsdict):
new_cls = super(CloneableMeta, metacls).__new__(metacls, cg_name, bases, clsdict)
return new_cls | __all__ = ['CloneableMeta']
def attach_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the _clones attribute to an empty list.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
orig_init(self, *args, **kwargs)... |
Check if keyfile exists before generating new key |
import os
from flask_app.database import init_db
# Generate new secret key
secret_key = os.urandom(24).encode('hex').strip()
with open('flask_app/secret_key.py', 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".decode("hex")')
# Initialize database
init_db()
|
import os
from flask_app.database import init_db
# Generate new secret key
key_file_path = 'flask_app/secret_key.py'
if not os.path.isfile(key_file_path):
secret_key = os.urandom(24).encode('hex').strip()
with open(key_file_path, 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".... |
Handle installing px on top of itself | import sys
import shutil
import os
def install(src, dest):
"""
Copy src (file) into dest (file) and make dest executable.
On trouble, prints message and exits with an error code.
"""
try:
_install(src, dest)
except Exception as e:
sys.stderr.write("Installing {} failed, pleas... | import sys
import shutil
import os
def install(src, dest):
"""
Copy src (file) into dest (file) and make dest executable.
On trouble, prints message and exits with an error code.
"""
try:
_install(src, dest)
except Exception as e:
sys.stderr.write("Installing {} failed, pleas... |
Fix RSS feed some more. |
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from extensions.models import Extension
class LatestExtensionsFeed(Feed):
title = "Latest extensions in GNOME Shell Extensions"
link = "/"
description = "The latest extensions in GNOME Shell Extensions"
def... |
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from extensions.models import Extension
class LatestExtensionsFeed(Feed):
title = "Latest extensions in GNOME Shell Extensions"
link = "/"
description = "The latest extensions in GNOME Shell Extensions"
def... |
Print rancher-compose command to help debug/confirmation | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... |
Remove index argument while creating order products sample | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_samp... | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_samp... |
Update list of reserved tokens | RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'static',
'public',
'private',
'protected',
'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
|
Fix memory issues by just trying every number | import sieve
def prime_factors(n):
primes = sieve.sieve(n)
factors = []
for p in primes:
while n % p == 0:
factors += [p]
n //= p
return factors
| def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
|
Add smiley face to output | #!/usr/bin/env python
"""A Python calculator"""
import sys
command = sys.argv[1]
numbers = [float(a) for a in sys.argv[2:]]
a = float(sys.argv[2])
b = float(sys.argv[3])
if command == 'add':
print sum(numbers)
elif command == 'multiply':
product = 1
for num in numbers:
product *= num
print p... | #!/usr/bin/env python
"""A Python calculator"""
import sys
command = sys.argv[1]
numbers = [float(a) for a in sys.argv[2:]]
a = float(sys.argv[2])
b = float(sys.argv[3])
if command == 'add':
print sum(numbers)
elif command == 'multiply':
product = 1
for num in numbers:
product *= num
print p... |
Add logging for DemographicInfo, and ignore empty strings. | """
Contains DemographicInfo class, which stores info found by accounts.
"""
from collections import UserDict
class DemographicInfo(UserDict):
def __setitem__(self, key, value):
if key in self.data:
self.data[key].add(value)
else:
self.data[key] = set([value])
| """
Contains DemographicInfo class, which stores info found by accounts.
"""
from collections import UserDict
import logging
log = logging.getLogger('social.info')
class DemographicInfo(UserDict):
def __setitem__(self, key, value):
# Ignore empty strings...
if type(value) is str and value == '':
... |
Allow additional properties on Text | from rctk.widgets.control import Control, remote_attribute
from rctk.task import Task
from rctk.event import Changable, Submittable
class Text(Control, Changable, Submittable):
name = "text"
value = remote_attribute('value', "")
def __init__(self, tk, value="", rows=1, columns=20):
self._value =... | from rctk.widgets.control import Control, remote_attribute
from rctk.task import Task
from rctk.event import Changable, Submittable
class Text(Control, Changable, Submittable):
name = "text"
value = remote_attribute('value', "")
def __init__(self, tk, value="", rows=1, columns=20, **properties):
... |
Fix crashes from misc. events | from __future__ import print_function
import time
from slackclient import SlackClient
import mh_python as mh
import argparse
import random
def main():
parser = argparse.ArgumentParser(
description="Slack chatbot using MegaHAL")
parser.add_argument(
"-t", "--token", type=str, help="Slack token"... | from __future__ import print_function
import time
from slackclient import SlackClient
import mh_python as mh
import argparse
import random
def main():
parser = argparse.ArgumentParser(
description="Slack chatbot using MegaHAL")
parser.add_argument(
"-t", "--token", type=str, help="Slack token"... |
Remove "Recompiling..." output when building .fp files | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
skslc = sys.argv[1]
clangFormat = sys.argv[2]
fetchClangFormat = sys.argv[3]
processors = sys.argv[4:]
exeSuffix = '.exe'... | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
skslc = sys.argv[1]
clangFormat = sys.argv[2]
fetchClangFormat = sys.argv[3]
processors = sys.argv[4:]
exeSuffix = '.exe'... |
Update to Sentimental 2.2.x with undersampling | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calculate_friend_scores... | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calcu... |
Change create sample code to ensure matching order ids data | # importing modules/ libraries
import pandas as pd
import random
# create sample of order products train data
n = 1384617
s = round(0.1 * n)
skip = sorted(random.sample(range(1,n), n-s))
order_products__train_sample_df = pd.read_csv('Data/order_products__train.csv',
skiprows = s... | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create sample of order products train data
n = 1384617
s = round(0.1 * n)
skip = sorted(random.sample(range(1,n), n-s))
order_products__train_sample_df = pd.read_csv('Data/order_products__train.csv',
... |
Test that event_model forbids dots in key names. | from bluesky.run_engine import RunEngine
from bluesky.tests.utils import setup_test_run_engine
from bluesky.examples import simple_scan, motor
RE = setup_test_run_engine()
def test_custom_metadata():
def assert_lion(name, doc):
assert 'animal' in doc
assert doc['animal'] == 'lion'
RE(simple... | import pytest
import jsonschema
from bluesky.run_engine import RunEngine
from event_model import DocumentNames, schemas
from bluesky.tests.utils import setup_test_run_engine
from bluesky.utils import new_uid
from bluesky.examples import simple_scan, motor
RE = setup_test_run_engine()
def test_custom_metadata():
... |
Use just a random string instead of uuid in shell name. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides info about a particular server.
"""
from usage import usage
import restclient
import simplejson
import subprocess
import sys
from uuid import uuid1
class Info:
def __init__(self):
self.debug = False
def runCmd(self, cmd, server, port,
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides info about a particular server.
"""
from usage import usage
import restclient
import simplejson
import subprocess
import sys
import string
import random
class Info:
def __init__(self):
self.debug = False
def _remoteShellName(self):
... |
Add missing open action to the example so that you can open other files | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSO... | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSO... |
Move pages from registration to accounts/ | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^registration/', include('registration.urls')),
(r'^$', direct_to_... | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('registration.urls')),
(r'^$', direct_to_temp... |
Fix write program telecommand part size | import struct
from telecommand import Telecommand
class EraseBootTableEntry(Telecommand):
def apid(self):
return 0xB0
def payload(self):
mask = 0
for e in self._entries:
mask |= 1 << e
return [mask]
def __init__(self, entries):
self.... | import struct
from telecommand import Telecommand
class EraseBootTableEntry(Telecommand):
def apid(self):
return 0xB0
def payload(self):
mask = 0
for e in self._entries:
mask |= 1 << e
return [mask]
def __init__(self, entries):
self.... |
Prepare for next development version | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.3.10'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.4.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
|
Test DatadogMetricsBackend against datadog's get_hostname | from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('... | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(pr... |
Add unit tests for push, peek, pop and size | import unittest
from aids.stack.stack import Stack
class StackTestCase(unittest.TestCase):
'''
Unit tests for the Stack data structure
'''
def setUp(self):
pass
def test_stack_initialization(self):
test_stack = Stack()
self.assertTrue(isinstance(test_stack, Stack))
def test_stack_is_em... | import unittest
from aids.stack.stack import Stack
class StackTestCase(unittest.TestCase):
'''
Unit tests for the Stack data structure
'''
def setUp(self):
self.test_stack = Stack()
def test_stack_initialization(self):
self.assertTrue(isinstance(self.test_stack, Stack))
def test_stack... |
Reformat total_after function + Remove itertools | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in r... | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
square = [x for x in range(1, 65)]
grai... |
Test running: exit with run test status | from os import getcwd
from sys import path as ppath
ppath.insert(1,getcwd()+'/modules') # TODO: win32 compatibilite (python path)
import unittest
from lifegame.test.LifeGameTestSuite import LifeGameTestSuite
from tests.TestSuite import TestSuite
# TODO: Lister les tests ailleurs ? Recuperer les suite de tests de modu... | from os import getcwd
from sys import path as ppath
ppath.insert(1,getcwd()+'/modules') # TODO: win32 compatibilite (python path)
import unittest
from lifegame.test.LifeGameTestSuite import LifeGameTestSuite
from tests.TestSuite import TestSuite
# TODO: Lister les tests ailleurs ? Recuperer les suite de tests de modu... |
Complete testing, change back to production code | #!/usr/local/bin/python2.7
import sys
from datetime import date
from main import app
from upload_s3 import set_metadata
from flask_frozen import Freezer
# cron is called with 3 arguments, should only run in the first week of month
cron_condition = len(sys.argv) == 3 and date.today().day > 8
force_update = len(sys.ar... | #!/usr/local/bin/python2.7
import sys
from datetime import date
from main import app
from upload_s3 import set_metadata
from flask_frozen import Freezer
# cron is called with 3 arguments, should only run in the first week of month
cron_condition = len(sys.argv) == 3 and date.today().day < 8
force_update = len(sys.ar... |
Remove unwanted whitespace in tests | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2013
# License: BSD
# Various exception tests
import unittest
import secretstorage
from secretstorage.exceptions import ItemNotFoundException
class ExceptionsTest(unittest.TestCase):
"""A test case that ensures that all SecretStorage exceptions
are raised correc... | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2013
# License: BSD
# Various exception tests
import unittest
import secretstorage
from secretstorage.exceptions import ItemNotFoundException
class ExceptionsTest(unittest.TestCase):
"""A test case that ensures that all SecretStorage exceptions
are raised correc... |
Fix test that wasn't running | from framewirc import exceptions
class MissingAttributesTest:
def test_message(self):
attrs = ['some', 'attrs']
expected = 'Required attribute(s) missing: {}'.format(attrs)
exception = exceptions.MissingAttributes(attrs)
assert str(exception) == expected
| from framewirc import exceptions
def test_message():
attrs = ['some', 'attrs']
expected = 'Required attribute(s) missing: {}'.format(attrs)
exception = exceptions.MissingAttributes(attrs)
assert str(exception) == expected
|
Make Input importable from root | from __future__ import absolute_import
from . import activations
from . import applications
from . import backend
from . import datasets
from . import engine
from . import layers
from . import preprocessing
from . import utils
from . import wrappers
from . import callbacks
from . import constraints
from .... | from __future__ import absolute_import
from . import activations
from . import applications
from . import backend
from . import datasets
from . import engine
from . import layers
from . import preprocessing
from . import utils
from . import wrappers
from . import callbacks
from . import constraints
from .... |
Add some files for reverse-engineering | from os.path import dirname
from puresnmp.pdu import PDU
from puresnmp.test import readbytes_multiple
from puresnmp.x690.types import pop_tlv
HERE = dirname(__file__)
for row in readbytes_multiple('authpriv.hex', HERE):
print(row)
pdu, _ = pop_tlv(row)
print(pdu.pretty())
| from os.path import dirname
HERE = dirname(__file__)
from puresnmp.pdu import PDU
from puresnmp.test import readbytes_multiple
from puresnmp.x690.types import pop_tlv
for row in readbytes_multiple("authpriv.hex", HERE):
print(row)
pdu, _ = pop_tlv(row)
print(pdu.pretty())
|
Change it to upload to pypi | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
import os
here = os.pa... | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
import os
here = os.pa... |
Convert README to Restructured Text for distribution. | """Setuptools file for a MultiMarkdown Python wrapper."""
from codecs import open
from os import path
from distutils.core import setup
from setuptools import find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup... | """Setuptools file for a MultiMarkdown Python wrapper."""
from codecs import open
from os import path
from distutils.core import setup
from setuptools import find_packages
import pypandoc
here = path.abspath(path.dirname(__file__))
long_description = pypandoc.convert_file('README.md', 'rst')
setup(
name='scripto... |
Fix issue with deleting boto3 from ZIP file | from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='publish-aws-lambda',
version='0.3',
description='Publish a Python module as a set of AWS lambda functions',
url='https://github.com/ophirh/publish-aws-lambda',
author='Ophir',
... | from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='publish-aws-lambda',
version='0.3.1',
description='Publish a Python module as a set of AWS lambda functions',
url='https://github.com/ophirh/publish-aws-lambda',
author='Ophir',... |
Resolve warning "Unknown distribution option: 'include_data'" | from setuptools import setup, find_packages
with open('requirements.txt', 'r') as f:
requirements = f.readlines()
setup(
name='resultsdb-updater',
version='3.0.0',
description=('A micro-service that listens for messages on the message '
'bus and updates ResultsDB'),
license='GPLv2... | from setuptools import setup, find_packages
with open('requirements.txt', 'r') as f:
requirements = f.readlines()
setup(
name='resultsdb-updater',
version='3.0.0',
description=('A micro-service that listens for messages on the message '
'bus and updates ResultsDB'),
license='GPLv2... |
Add blank line between README and CHANGES in long_description | import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
version=version,
d... | import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.append('\n')
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
versi... |
Update barrow in furness coords from council | from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "BAR"
addresses_name = "2021-03-08T19:54:15.110811/Barrow in Furness Democracy Club - Polling Districts (2).csv"
stations_name = "2021-03-08T19:54:15.110811/Barrow in F... | from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "BAR"
addresses_name = "2021-03-08T19:54:15.110811/Barrow in Furness Democracy Club - Polling Districts (2).csv"
stations_name = "2021-03-08T19:54:15.110811/Barrow in F... |
Update authtoken latest Django 1.7 migration | # encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name... |
Make sure that the error code is returned properly | from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs a... | from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs a... |
Add a query string static patch |
import os
import time
from django.contrib.staticfiles import finders
from django.templatetags.static import StaticNode
def get_media(path):
result = finders.find(path, all=True)
return [os.path.realpath(path) for path in result]
def new_url(self, context):
"""Add a query string to invalidate cached file... | |
Add tools to package data | #!/usr/bin/env python
from distutils.core import setup
import fedex
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Op... | #!/usr/bin/env python
from distutils.core import setup
import fedex
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Op... |
Use readme in long description | from setuptools import setup, find_packages
setup(
name='django-txtlocal',
packages=find_packages(),
include_package_data=True,
install_requires=['requests>=1.2.3'],
version='0.2',
description='App for sending and receiving SMS messages via http://www.textlocal.com',
author='Incuna Ltd',
... | from setuptools import setup, find_packages
setup(
name='django-txtlocal',
packages=find_packages(),
include_package_data=True,
install_requires=['requests>=1.2.3'],
version='0.2',
description='App for sending and receiving SMS messages via http://www.textlocal.com',
long_description=open(... |
Add whoosh as test dependancy | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
tests_require = [
'django',
'django-celery',
'south',
'django-haystack',
]
setup(
name='djang... | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
tests_require = [
'django',
'django-celery',
'south',
'django-haystack',
'whoosh',
]
setup(
... |
Use HTTPS url for MathJax script | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MA... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MA... |
Add login required mixin to user profile | from django.views.generic import View
from django.shortcuts import render
class MemberProfileView(View):
template_name = 'accounts/profile.html'
def get(self, request):
return render(request, self.template_name) | from django.views.generic import View
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
class MemberProfileView(LoginRequiredMixin, View):
login_url = '/accounts/login/'
redirect_field_name = 'redirect_to'
template_name = 'accounts/profile.html'
def get(sel... |
Add resource paths to python launcher script (proxy) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import alfanousDesktop.Gui
alfanousDesktop.Gui.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
# The paths should be generated by setup script
sys.argv.extend(
'-i', '/usr/share/alfanous-indexes/',
'-l', '/usr/locale/',
'-c', '/usr/share/alfanous-config/')
from alfanousDesktop.Gui import *
main()
|
Remove test settings to see if it fixes jenkins. | from .base import *
try:
from .local import *
except ImportError, exc:
exc.args = tuple(['%s (did you rename settings/local.py-dist?)'
% exc.args[0]])
raise exc
import sys
if sys.argv[1] == 'test':
try:
from .test import *
except ImportError:
pass
| from .base import *
try:
from .local import *
except ImportError, exc:
exc.args = tuple(['%s (did you rename settings/local.py-dist?)'
% exc.args[0]])
raise exc
"""
import sys
if sys.argv[1] == 'test':
try:
from .test import *
except ImportError:
pass
"""
|
Add Python 3 only classifier | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
readme = f.read()
setup(
name='manuale',
version='1.0.1.dev0',
license='MIT',
description="A fully manual Let's Encr... | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
readme = f.read()
setup(
name='manuale',
version='1.0.1.dev0',
license='MIT',
description="A fully manual Let's Encr... |
Read twitter tokens from .env | # -*- coding: utf-8 -*-
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ['OPS_KEY']
OPS_SECRET = os.environ['OPS_SECRET']
| # -*- coding: utf-8 -*-
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ['OPS_KEY']
OPS_SECRET = os.environ['OPS_SECRET']
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS ... |
Add tinyurl.com as a minifier | # -*- coding: utf-8 -*-
#
# This file is part of tofbot, a friendly IRC bot.
# You may redistribute it under the Simplified BSD License.
# If we meet some day, and you think this stuff is worth it,
# you can buy us a beer in return.
#
# Copyright (c) 2012 Etienne Millon <etienne.millon@gmail.com>
from BeautifulSoup im... | # -*- coding: utf-8 -*-
#
# This file is part of tofbot, a friendly IRC bot.
# You may redistribute it under the Simplified BSD License.
# If we meet some day, and you think this stuff is worth it,
# you can buy us a beer in return.
#
# Copyright (c) 2012 Etienne Millon <etienne.millon@gmail.com>
from BeautifulSoup im... |
Allow different input files to be specified. | '''
Created on Feb 20, 2013
@author: crisr
'''
import xml.etree.ElementTree as ET
import os
from Simulation import Simulation
debug = True
if __name__ == '__main__':
#open the XML
try:
inputFile = 'test.xml' #sys.argv[1]
except:
raise IOError ('input file not provided')
workingDir = os.getcwd()
if ... | '''
Created on Feb 20, 2013
@author: crisr
'''
import xml.etree.ElementTree as ET
import os
from Simulation import Simulation
import sys
debug = True
if __name__ == '__main__':
#open the XML
try:
if len(sys.argv) == 1:
inputFile = 'test.xml'
else:
inputFile = sys.argv[1]
except:
raise ... |
Move QGL import inside function | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined i... | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL im... |
Allow nodes not to have related environment | from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, pr... | from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, pr... |
Remove `objects' group as useless | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... |
Use StringIO object from 'io' module instead of deprecated 'StringIO' module | """
Logging
=======
"""
import logging
import colorlog
def init_logger(level, printout=True):
"""
Initialize app logger to configure its level/handler/formatter/etc..
Todo:
* A mean to raise click.Abort or sys.exit when CRITICAL is used;
Args:
level (str): Level name (``debug``, ``i... | """
Logging
=======
"""
import logging
import colorlog
def init_logger(level, printout=True):
"""
Initialize app logger to configure its level/handler/formatter/etc..
Todo:
* A mean to raise click.Abort or sys.exit when CRITICAL is used;
Args:
level (str): Level name (``debug``, ``i... |
Change Form to FlaskForm (previous is deprecated) | from flask_wtf import Form
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(Form):
email = StringField('Email', validators=[
... | from flask_wtf import FlaskForm
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(FlaskForm):
email = StringField('Email', valida... |
Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello. | import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField(jsl.StringField(), max_items=2)
rsync = jsl.ArrayField(jsl.StringField(), max_items=2)
containers = jsl.ArrayField([
jsl.StringField(),
jsl.ArrayField(jsl.StringField())
])
| import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
rsync = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
containers = jsl.Array... |
Change to more generic variable names in _fill_queue | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... |
Move revoke events to DocumentedRuleDefault | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
Change scale range to normalization with source and target min max | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = N... | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = N... |
Add temporary bootstrapping to get the service working with how the charm presently expects to run the app. | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "capomastro.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
# This bootstraps the virtualenv so that the system Python can use it
app_root = os.path.dirname(os.path.realpath(__file__))
activate_this = os.path.join(app_root, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
if __name__ == "__main__":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.