Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use socket connection to get own IP. | import sh
from sh import docker
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
intf = sh.ifconfig.eth0()
return sh.perl(intf, "-ne", 's/dr:(\S+)/print $1/e')
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.... | import sh
from sh import docker
import socket
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def cleanup_inside(name):
"""
Clean the... |
Add a bunch of mostly-empty method stubs. | import sublime, sublime_plugin | import sublime, sublime_plugin
class DiffListener(sublime_plugin.EventListener):
"""Listens for modifications to the view and gets the diffs using Operational Transformation"""
def __init___(self):
self.buffer = None
self.last_buffer = None
def on_modified_async(self, view):
"""Li... |
Use more optimal method of getting multiples | def sum_of_multiples(limit, factors):
return sum(filter(lambda n: n < limit,
{f*i for i in range(1, limit) for f in factors}))
| def sum_of_multiples(limit, factors):
return sum({n for f in factors for n in range(f, limit, f)})
|
Add new configuration setting for log_directory | # General Settings
timerestriction = False
debug_mode = True
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Services Auth
basic_auth = 'ba... | # General Settings
timerestriction = False
debug_mode = True
log_directory = './logs'
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Servi... |
Make script consistent with instructions. | import argparse
import PIL
from PIL import Image
import subprocess
import os
import glob
def get_image(filename):
p = Image.open(filename)
docker_image = p.info['im2sim_image']
return subprocess.call('docker pull {}'.format(docker_image), shell=True)
print('Pulled docker image {}'.format(docker_image)... | import argparse
import PIL
from PIL import Image
import subprocess
import os
import glob
def get_image(filename):
p = Image.open(filename)
docker_image = p.info['im2sim_image']
return subprocess.call('docker pull {}'.format(docker_image), shell=True)
print('Pulled docker image {}'.format(docker_image)... |
Fix tests for new quiet attribute | import os.path
import pytest
import rain.compiler as C
def ls(*path):
path = os.path.join(*path)
for file in os.listdir(path):
yield os.path.join(path, file)
def lsrn(*path, recurse=False):
for file in ls(*path):
if os.path.isfile(file) and file.endswith('.rn') and not file.endswith('_pkg.rn'):
yi... | import os.path
import pytest
import rain.compiler as C
def ls(*path):
path = os.path.join(*path)
for file in os.listdir(path):
yield os.path.join(path, file)
def lsrn(*path, recurse=False):
for file in ls(*path):
if os.path.isfile(file) and file.endswith('.rn') and not file.endswith('_pkg.rn'):
yi... |
Change the Error show in command window. | # -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWi... | # -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWi... |
Enable authentication for rest api | import json
from restless.dj import DjangoResource
from restless.resources import skip_prepare
from django.conf.urls import patterns, url
from harvest.models import Job
from harvest.jobstatemachine import JobStatemachine
from borg_utils.jobintervals import Triggered
class JobResource(DjangoResource):
def is_a... | import json
from restless.dj import DjangoResource
from restless.resources import skip_prepare
from django.conf.urls import patterns, url
from harvest.models import Job
from harvest.jobstatemachine import JobStatemachine
from borg_utils.jobintervals import Triggered
class JobResource(DjangoResource):
def is_a... |
Fix import error after removal of old csv table mixin | __version__ = '1.2.0'
try:
from django.conf import settings
getattr(settings, 'dummy_attr', 'dummy_value')
_LOAD_PACKAGES = True
except:
# Just running sdist, we think
_LOAD_PACKAGES = False
if _LOAD_PACKAGES:
from mixins import (TablesMixin, EditTablesMixin, FilteredListView,
... | __version__ = '1.2.0'
try:
from django.conf import settings
getattr(settings, 'dummy_attr', 'dummy_value')
_LOAD_PACKAGES = True
except:
# Just running sdist, we think
_LOAD_PACKAGES = False
if _LOAD_PACKAGES:
from mixins import TablesMixin, EditTablesMixin, FilteredListView
from column im... |
Fix code style issues with Black | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
run... |
Add autoreload on settings default true | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import parse_command_line, define, options
define('port', default=8888)
define('template_path', default='templates')
define('PROJECT_PATH', default=os.path.join(
os.pat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import parse_command_line, define, options
define('port', default=8888)
define('template_path', default='templates')
define('PROJECT_PATH', default=os.path.join(
os.pat... |
Use log level info for HTTP statuses 500, 502, 503, 504. | import logging
from scrapy.spidermiddlewares.httperror import HttpError
logger = logging.getLogger(__name__)
class FeedsHttpErrorMiddleware:
@classmethod
def from_crawler(cls, crawler):
return cls()
def process_spider_exception(self, response, exception, spider):
if isinstance(exceptio... | import logging
from scrapy.spidermiddlewares.httperror import HttpError
logger = logging.getLogger(__name__)
class FeedsHttpErrorMiddleware:
@classmethod
def from_crawler(cls, crawler):
return cls()
def process_spider_exception(self, response, exception, spider):
if isinstance(exceptio... |
Add check to ensure that we're in the same OS thread | import guv
guv.monkey_patch()
from guv import gyield, sleep
import threading
import greenlet
greenlet_ids = {}
def debug(i):
print('{} greenlet_ids: {}'.format(i, greenlet_ids))
def f():
greenlet_ids[1] = greenlet.getcurrent()
debug(2)
print('t: 1')
gyield()
print('t: 2')
gyield()
... | import guv
guv.monkey_patch()
from guv import gyield, patcher
import threading
import greenlet
threading_orig = patcher.original('threading')
greenlet_ids = {}
def check_thread():
current = threading_orig.current_thread()
assert type(current) is threading_orig._MainThread
def debug(i):
print('{} gre... |
Change versioning to be PEP compatible | __author__ = 'Abraham Othman'
__copyright__ = 'Copyright 2014, Abraham Othman'
__version__ = '1.0'
__maintainer__ = 'Abraham Othman'
__email__ = 'aothman@cs.cmu.edu'
from .engine import create, HiScoreEngine, Point
from .errors import MonotoneError, MonotoneBoundsError, ScoreCreationError | __author__ = 'Abraham Othman'
__copyright__ = 'Copyright 2014, Abraham Othman'
__version__ = '1.0.0'
__maintainer__ = 'Abraham Othman'
__email__ = 'aothman@cs.cmu.edu'
from .engine import create, HiScoreEngine, Point
from .errors import MonotoneError, MonotoneBoundsError, ScoreCreationError |
Make view to handle saving and displaying of preferences form | from django.shortcuts import render
from django.views.generic.edit import FormView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.forms import PreferencesForm
class EmailRegistrationView(RegistrationView):
form_class ... | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.peopl... |
Add ID support for subscription/ URLs. | # Copyright (C) 2014 Linaro Ltd.
#
# This program 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 (at your option) any later version.
#
# This program is distribute... | # Copyright (C) 2014 Linaro Ltd.
#
# This program 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 (at your option) any later version.
#
# This program is distribute... |
Add first batch of team endpoints | from src.endpoints.base import Base
class Teams(Base):
endpoint = '/teams'
def create_team(self, options=None):
return self.client.post(
self.endpoint,
options
)
def get_teams(self, query=None, options=None):
query_string = self.build_query(query)
return self.client.get(
self.endpoint + query_s... | |
Use the correct env variable name | # -*- coding: utf-8 -*-
import os
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
from listener import Listener
ckey = os.environ['CKEY']
consumer_secret = os.environ['CONSUMER_KEY']
access_token_key = os.environ['ACCESS_TOKEN_KEY']
access_to... | # -*- coding: utf-8 -*-
import os
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API
from tweepy.streaming import StreamListener
from listener import Listener
ckey = os.environ['CKEY']
consumer_secret = os.environ['CONSUMER_SECRET']
access_token_key = os.environ['ACCESS_TOKEN_KEY']
access... |
Fix error determining current version in other working directories. | from __future__ import absolute_import
__author__ = 'katharine'
import os
import subprocess
from pebble_tool.exceptions import MissingSDK
from pebble_tool.util import get_persist_dir
def sdk_path():
path = os.getenv('PEBBLE_SDK_PATH', None) or os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')... | from __future__ import absolute_import
__author__ = 'katharine'
import os
import subprocess
from pebble_tool.exceptions import MissingSDK
from pebble_tool.util import get_persist_dir
def sdk_path():
path = os.getenv('PEBBLE_SDK_PATH', None) or os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')... |
Check for ioflo-flavored OrderedDicts as well when outputting YAML | # -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
# pylint: disable=W0232
# class has no __init__ method
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import ... | # -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
# pylint: disable=W0232
# class has no __init__ method
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import ... |
Remove input from fab test | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder... | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder... |
Add the choose test and take test to URLs | from django.conf.urls import patterns, url
from examsys import views
urlpatterns = patterns('',
# (r'^$', lambda r: HttpResponseRedirect('examsys/'))
url(r'^$', views.index, name='index'),
url(r'^login/', views.login, name='login'),
url(r'^logout/', views.logout, name='logout'),
url(r'^register/', v... | from django.conf.urls import patterns, url
from examsys import views
urlpatterns = patterns('',
# (r'^$', lambda r: HttpResponseRedirect('examsys/'))
url(r'^$', views.index, name='index'),
url(r'^login/', views.login, name='login'),
url(r'^logout/', views.logout, name='logout'),
url(r'^register/', v... |
Change from MySQL to SQLite3 | import os
import peewee
APP_DIR = os.path.dirname(__file__)
try:
import urlparse
import psycopg2
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
database = peewee.PostgresqlDatabase(database=url.path[1:],
user=ur... | import os
import peewee
APP_DIR = os.path.dirname(__file__)
try:
import urlparse
import psycopg2
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
database = peewee.PostgresqlDatabase(database=url.path[1:],
user=ur... |
Fix path to seminar repository. | # -*- coding: utf-8 -*-
GIT_SEMINAR_PATH = 'data/seminar-test/'
TASK_MOOSTER_PATH = 'task-mooster/'
| # -*- coding: utf-8 -*-
GIT_SEMINAR_PATH = 'data/seminar/'
TASK_MOOSTER_PATH = 'task-mooster/'
|
Set config logging in init to debug | import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db = SQLAlchemy(app)
def configure_logging(obj):
logger = logging.getLogger(obj.__class__.__name__)
logg... | import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db = SQLAlchemy(app)
def configure_logging(obj):
logger = logging.getLogger(obj.__class__.__name__)
logg... |
Watch the docs/ dir for changes | from fabric.api import execute, local, settings, task
@task
def preprocess_header():
local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true')
@task
def docs():
local('make -C docs/ html')
@task
def autodocs():
auto(docs)
@task
def test():
local('nosetests')
@task
def autotest():
... | from fabric.api import execute, local, settings, task
@task
def preprocess_header():
local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true')
@task
def docs():
local('make -C docs/ html')
@task
def autodocs():
auto(docs)
@task
def test():
local('nosetests')
@task
def autotest():
... |
Call Darksky API with TCX run time Use simpler GET request to Darksky API rather than a third party Python wrapper | import tcxparser
from darksky import forecast
from configparser import ConfigParser
# Darksky weather API.
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')
tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
pri... | import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky... |
Revert "Updated function to work on bytes rather than binascii functions." | """Set 01 - Challenge 01."""
import base64
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a bas... | """Set 01 - Challenge 01."""
import binascii
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a b... |
Change singletons to instantiate locks per-class | import threading
class SingletonMixin(object):
__singleton_lock = threading.Lock()
__singleton_instance = None
@classmethod
def instance(cls, *args, **kwargs):
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
... | import threading
class SingletonMixin(object):
__singleton_lock = None
__singleton_instance = None
@classmethod
def instance(cls, *args, **kwargs):
if not cls.__singleton_lock:
cls.__singleton_lock = threading.Lock()
if not cls.__singleton_instance:
with cls._... |
Add names to each url | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
(r'^(... | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r... |
Increment version number to 0.4.0 | __version__ = '0.3.2'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... | __version__ = '0.4.0'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation... |
Make topic_* field on public body search index optional | from __future__ import print_function
from django.conf import settings
from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import PublicBody
PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {})
class PublicBodyIndex(CelerySearchIndex, indexes.Indexa... | from __future__ import print_function
from django.conf import settings
from haystack import indexes
from celery_haystack.indexes import CelerySearchIndex
from .models import PublicBody
PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {})
class PublicBodyIndex(CelerySearchIndex, indexes.Indexa... |
Write test that attempts to unpack invalid archive | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
import sys
import pytest
@pytest.mark.trylast
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test th... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
import sys
import pytest
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version f... |
Switch order of store URLs | from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from oscar.app import shop
from stores.app import application as stores_app
from stores.da... | from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from oscar.app import shop
from stores.app import application as stores_app
from stores.da... |
Make it possible to eval() output instead of execing another shell. | import argparse
from awscli.customizations.commands import BasicCommand
import os
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShell(session)
def get_exec_args... | import argparse
import os
import shlex
import textwrap
from awscli.customizations.commands import BasicCommand
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShe... |
Add email and API template | # Enter the password of the email address you intend to send emails from
password = "" | # Enter the password of the email address you intend to send emails from
email_address = ""
email_password = ""
# Enter the login information for the EPNM API Account
API_username = ""
API_password = ""
|
Remove optional lock input (I can't see when it would be useful) Document when Listener should be used | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type, lock=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Parameters:
topic_name (str): name of topic to... | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming beh... |
Use bare WSGI application for testing and benchmarking | import guv
guv.monkey_patch()
import json
import bottle
import guv.wsgi
import logger
logger.configure()
app = bottle.Bottle()
@app.route('/')
def index():
data = json.dumps({'status': True})
return data
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(serve... | import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', co... |
Test math and cmath module. | print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
| print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
import cmath
print cmath.sqrt(-1)
import math
print math.floor(32.8)
|
Fix crash if view returns no valid path | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... |
Add install command (import from ARCTasks) | from runcommands.commands import show_config # noqa: F401
from arctasks.base import lint # noqa: F401
from arctasks.python import show_upgraded_packages # noqa: F401
from arctasks.release import * # noqa: F401,F403
| from runcommands.commands import show_config # noqa: F401
from arctasks.base import install, lint # noqa: F401
from arctasks.python import show_upgraded_packages # noqa: F401
from arctasks.release import * # noqa: F401,F403
|
Declare imageNames with var, use .format() instead of %, remove tab before closing bracket | #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('imageNames = [\n')
js_file.write(',\n'.join(['\t"%s"' % name for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n\t];\n')
js_file.close()
| #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('var imageNames = [\n')
js_file.write(',\n'.join(['\t"{}"'.format(name) for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n];\n')
js_file.close()
|
Add a has_expired() method to the Timer class. | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, ... | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callbac... |
Change ValidTime to a mixbox Entity | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicato... | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "... |
Clean up, comments, liveness checking, robust data transfer | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(... |
Update data explorations data sets to samples | # importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
ord... | # importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_produc... |
Remove debug print and log properly | import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not ... | import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
... |
Fix bug with campaign id | from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
... | from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
... |
Fix newlines in copying of errors | # A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QA... | # A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action ... |
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns | # These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData ... | # These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData ... |
Decrease the needed matplotlib to 1.3, to make it easier to get installed. | import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklear... | import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklear... |
Change assert(False) to assert(True) to avoid having test fail no matter what | # __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def... | # __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def... |
Remove index file created in test | #!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'... | #!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'... |
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS. | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitema... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitema... |
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least. | #!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
| #!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component)... |
Use of product.template instead of product.product in bundle line | # -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fie... | # -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fie... |
Add some tests for stringport | """
Unittests for opal.utils
"""
from django.test import TestCase
from django.db.models import ForeignKey, CharField
from opal import utils
class StringportTestCase(TestCase):
def test_import(self):
import collections
self.assertEqual(collections, utils.stringport('collections'))
class Itersubc... | """
Unittests for opal.utils
"""
from django.test import TestCase
from django.db.models import ForeignKey, CharField
from opal import utils
class StringportTestCase(TestCase):
def test_import(self):
import collections
self.assertEqual(collections, utils.stringport('collections'))
def test_im... |
Change path for the module ClusterEvaluation | from pygraphc.clustering.ClusterDistance import *
from pygraphc.clustering.ClusterEvaluation import *
from pygraphc.clustering.ClusterUtility import *
from pygraphc.clustering.ConnectedComponents import *
from pygraphc.clustering.KCliquePercolation import *
from pygraphc.clustering.MaxCliquesPercolation import *
impor... | import pygraphc.clustering.ClusterDistance
import pygraphc.clustering.ClusterUtility
import pygraphc.clustering.ConnectedComponents
import pygraphc.clustering.KCliquePercolation
import pygraphc.clustering.MaxCliquesPercolation
from pygraphc.clustering.ClusterDistance import *
from pygraphc.clustering.ClusterUtility imp... |
Correct default passphrase length following d9913ce | # -*- coding: utf-8 -*-
"""Utility for generating memorable passwords"""
from __future__ import absolute_import
from __future__ import print_function
import argparse
import sys
import niceware
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description=... | # -*- coding: utf-8 -*-
"""Utility for generating memorable passwords"""
from __future__ import absolute_import
from __future__ import print_function
import argparse
import sys
import niceware
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description=... |
Add types to top-level import to simplify porting from h5py | from . import core
from . import plugin_interface
from . import plugins
from .core import File, validation
# TODO remove versioneer
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# core.plugin.load_plugins()
| from . import core
from . import plugin_interface
from . import plugins
from .core import File, validation, Attribute, Dataset, Group, Raw, Object
# TODO remove versioneer
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# core.plugin.load_plugins()
|
Add link to queue graphs for `CeleryAliveCheck` result. | from __future__ import absolute_import
from time import time
from sentry import options
from .base import StatusCheck, Problem
class CeleryAliveCheck(StatusCheck):
def check(self):
last_ping = options.get('sentry:last_worker_ping') or 0
if last_ping >= time() - 300:
return []
... | from __future__ import absolute_import
from time import time
from django.core.urlresolvers import reverse
from sentry import options
from sentry.utils.http import absolute_uri
from .base import Problem, StatusCheck
class CeleryAliveCheck(StatusCheck):
def check(self):
last_ping = options.get('sentry:l... |
Add ports and fix bug | chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'pyth... | chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
chatbot_goaloriented = {
'socket_address': '127.0.0.1',
'socket_port': 8889
... |
Use explicit related-lookup syntax in ban search. | from django.contrib import admin
from users.models import UserBan
class UserBanAdmin(admin.ModelAdmin):
fields = ('user', 'by', 'reason', 'is_active')
list_display = ('user', 'by', 'reason')
list_filter = ('is_active',)
raw_id_fields = ('user',)
search_fields = ('user', 'reason')
admin.site.reg... | from django.contrib import admin
from users.models import UserBan
class UserBanAdmin(admin.ModelAdmin):
fields = ('user', 'by', 'reason', 'is_active')
list_display = ('user', 'by', 'reason')
list_filter = ('is_active',)
raw_id_fields = ('user',)
search_fields = ('user__username', 'reason')
admi... |
Add character replacements for RT search | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... |
Clean up any left over browser processes in the RecreateSKPs buildstep. | #!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run the webpages_playback automation script."""
import os
import sys
from build_step import BuildStep
from utils import shel... | #!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run the webpages_playback automation script."""
import os
import sys
from build_step import BuildStep
from utils import shel... |
Add support for component initialization that returns lists | from importlib import import_module
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
... | from importlib import import_module
from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components config... |
Use list comprehensions to format all errors where message is not a dict |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_fr... |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_fr... |
Add a function returning js bytecode. | import pyjsparser
from space import Space
import fill_space
from byte_trans import ByteCodeGenerator
from code import Code
from simplex import MakeError
import sys
sys.setrecursionlimit(100000)
pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg))
def eval_js_vm(js):
a = By... | import pyjsparser
from space import Space
import fill_space
from byte_trans import ByteCodeGenerator
from code import Code
from simplex import MakeError
import sys
sys.setrecursionlimit(100000)
pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg))
def get_js_bytecode(js):
a ... |
Tidy up list of tests to write. | """
log of integration tests to write:
write test_switch_branches_restarts_containers
command:
docker-compose up -d (in a directory with appropriate docker-compose.yml file)
expected behaviour:
docker containers are started with dvol accordingly
XXX this doesn't seem to work at the moment
command:
do... | """
log of integration tests to write:
write test_switch_branches_restarts_containers
command:
docker-compose up -d (in a directory with appropriate docker-compose.yml file)
expected behaviour:
docker containers are started with dvol accordingly
command:
docker run -ti --volume-driver dvol -v hello:/data... |
Switch to StringIO for fake config data | # coding=utf-8
# Filename: test_config.py
"""
Test suite for configuration related functions and classes.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.testing import TestCase, BytesIO
from km3pipe.config import Config
CONFIGURATION = BytesIO("\n".join((
"[DB]",
"username... | # coding=utf-8
# Filename: test_config.py
"""
Test suite for configuration related functions and classes.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.testing import TestCase, StringIO
from km3pipe.config import Config
CONFIGURATION = StringIO("\n".join((
"[DB]",
"userna... |
Add python to install script | #!/usr/bin/env python
import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "instal... | #!/usr/bin/env python
import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "instal... |
Add a local asTwistedVersion implementation to Axiom, so as to not add another setup-time dependency on Epsilon | # -*- test-case-name: axiom.test -*-
from axiom._version import __version__
from epsilon import asTwistedVersion
version = asTwistedVersion("axiom", __version__)
| # -*- test-case-name: axiom.test -*-
from axiom._version import __version__
from twisted.python import versions
def asTwistedVersion(packageName, versionString):
return versions.Version(packageName, *map(int, versionString.split(".")))
version = asTwistedVersion("axiom", __version__)
|
Add X509 support only when pyOpenSSL is installed | import sys
__version__ = '0.9.1'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... | import sys
__version__ = '0.9.2'
ENCODINGS = ['Base64',
'Base64 URL',
'Base32',
'Hex',
'URL',
'HTML',
'Rot13',
'UTF8',
'UTF16']
COMPRESSIONS = ['Gzip',
'Bz2']
HASHS = ['MD5',
'SHA1',
... |
Fix docstring for module (minor) | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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/lice... | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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/lice... |
Disable code made for old engine model | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
class Series(Item):
pass
Series.options.register("color", True)
Series.options.register("lineWidth", False)
Series.options.register("lineStyle", False)
class TestOptionsResolving(unittest.TestCase):... | import unittest
from protoplot.engine.item import Item
from protoplot.engine.item_container import ItemContainer
# class Series(Item):
# pass
#
# Series.options.register("color", True)
# Series.options.register("lineWidth", False)
# Series.options.register("lineStyle", False)
class TestOptionsResolving(unittes... |
Add config option for weeks to truncate and default to 2 weeks | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgres_transactions,
with_single_... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgre... |
Increase permessable interval to +- 5 min | # допустимое отклонение от начала часа для фиксации замера
PERMISSIBLE_PREC = 3
| # допустимое отклонение от начала часа для фиксации замера
PERMISSIBLE_PREC = 5
|
Add verbose error for a meddling middleware | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
from django.conf.urls.defaults import patterns, url, include
except ImportError:
from django.conf.urls import patterns, url, include # pragma: no cover
from django.core.management.base import BaseCommand
from dj... |
Return keywords instead of summary | # Team nameSpace@HINT2017
#
# This script contains a function which takes a URL as input
# and returns the content of the content in the webpage
# 'newspaper' library is used here to extract only the main
# content in a webpage
from flask import Flask,render_template
import urllib
from newspaper import Article
app =... | # Team nameSpace@HINT2017
#
# This script contains a function which takes a URL as input
# and returns the content of the content in the webpage
# 'newspaper' library is used here to extract only the main
# content in a webpage
from flask import Flask,render_template
import urllib
from newspaper import Article
app =... |
Remove HTML table (our mail cannot send HTML) | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def ma... |
Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import *
@login_required
def index(request):
return render(request, 'satsound/index.html')
@login_required... |
Update config name verify script to work with the .bat files. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
config_name = content.split('"')[1]
expe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure filenames for test-*.bash scripts match the config name registered
inside them.
"""
from __future__ import print_function
import os.path
import re
import sys
for line in sys.stdin.readlines():
filename, content = line.split(':', 1)
filename_parts = os... |
Rename column "Hash" to "Commit". |
import subprocess
import sys
from githistorydata.csv import Csv
from githistorydata.expand_commits import expand_authors, expand_lines
from githistorydata.git import Git
from githistorydata.rawgit import RawGit
def main( argv, out, err ):
try:
git = Git( RawGit() )
csv = Csv(
out,
... |
import subprocess
import sys
from githistorydata.csv import Csv
from githistorydata.expand_commits import expand_authors, expand_lines
from githistorydata.git import Git
from githistorydata.rawgit import RawGit
def main( argv, out, err ):
try:
git = Git( RawGit() )
csv = Csv(
out,
... |
Make test compatible with Python 2.6. | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2013 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
import os
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
class PhotosEndpointTestCase(BaseAuthenti... |
Fix MySQL command executing (MySQL commit). | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#==============================================================================
# Script for creating MySQL user
#==============================================================================
import os
import sys
import mysql.connector
from mysql.connector import errorco... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#==============================================================================
# Script for creating MySQL user
#==============================================================================
import os
import sys
import mysql.connector
from mysql.connector import errorco... |
Add color to python prompt | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
from math import log,ceil
def clog2(num):
return int(ceil(log(num,2)))
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in thi... | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
from math import log,ceil
sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002'
sys.ps2 = '\001\033[96m\002... \001\033[0m\002'
def clog2(num):
return int(ceil(log(num,2)))
if (sys.version_info > (3, 0)):
# Python 3 code in t... |
Handle FileNotFound and Permission errors gracefully | """
Log file parsers provided by Sentry Logs
"""
import tailer # same functionality as UNIX tail in python
from ..helpers import send_message
class Parser(object):
"""Abstract base class for any parser"""
def __init__(self, filepath):
self.filepath = filepath
self.logger = self.__doc__.stri... | """
Log file parsers provided by Sentry Logs
"""
import tailer # same functionality as UNIX tail in python
from ..helpers import send_message
try:
(FileNotFoundError, PermissionError)
except NameError: # Python 2.7
FileNotFoundError = IOError # pylint: disable=redefined-builtin
PermissionError = IOErro... |
Set package version to 0.4.2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend
"""
# Application manifest
VERSION = (0, 4, 1)
__application__ = u"Alignak_Backend"
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015 - %s" % __author__
__license__ = u"GNU Affero ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend
"""
# Application manifest
VERSION = (0, 4, 2)
__application__ = u"Alignak_Backend"
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015 - %s" % __author__
__license__ = u"GNU Affero ... |
Remove duplicate setting of config variable | # -*- coding: utf8 -*-
import sys
import os
import libcrowds_statistics as plugin
# Use the PyBossa test suite
sys.path.append(os.path.abspath("./pybossa/test"))
os.environ['STATISTICS_SETTINGS'] = '../settings_test.py'
def setUpPackage():
"""Setup the plugin."""
from default import flask_app
with flas... | # -*- coding: utf8 -*-
import sys
import os
import libcrowds_statistics as plugin
# Use the PyBossa test suite
sys.path.append(os.path.abspath("./pybossa/test"))
os.environ['STATISTICS_SETTINGS'] = '../settings_test.py'
def setUpPackage():
"""Setup the plugin."""
from default import flask_app
with flas... |
Update test now that response is iterable |
from unittest import TestCase, main
from antfarm import App, Response
from antfarm.response import STATUS
BASE_ENV = {
'REQUEST_METHOD': 'GET',
}
class AppTest(TestCase):
def test_001_basic(self):
app = App(root_view=lambda r: Response('true'))
def start_response(s, h):
self.as... |
from unittest import TestCase, main
from antfarm import App, Response
from antfarm.response import STATUS
BASE_ENV = {
'REQUEST_METHOD': 'GET',
}
class AppTest(TestCase):
def test_001_basic(self):
app = App(root_view=lambda r: Response('true'))
def start_response(s, h):
self.as... |
Add multiple permissions to a single export | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... |
Add method to encrypt files | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.text.pack()
menu = Menu(master)
root.config(menu=menu)
... | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
GPG = 'gpg2'
SERVER_KEY = '' # replace with gpg key ID of server key
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.tex... |
Make the Environment object available to build.bfg files | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_al... | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_al... |
Fix encoding issue when test lcd | from ev3.ev3dev import Lcd
# -*- coding: utf-8 -*-
import unittest
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... | # -*- coding: utf-8 -*-
import unittest
from ev3.ev3dev import Lcd
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... |
Add test for solver/proofread pair | import os
import threading
import numpy as np
import pytest
from skimage import io
from gala import serve, evaluate as ev
D = os.path.dirname(os.path.abspath(__file__))
os.chdir(os.path.join(D, 'example-data/snemi-mini'))
@pytest.fixture
def data():
frag, gt, pr = map(io.imread, sorted(os.listdir('.')))
r... | |
Fix import to support Python3 | # -*- coding: utf-8 -*-
#
# escpos/impl/__init__.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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.... | # -*- coding: utf-8 -*-
#
# escpos/impl/__init__.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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.... |
Fix weird distutils.log reloading/caching situation | import sys
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibilty with distutil... | import sys
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibilty with distutil... |
Remove tracker field from ParsedBug. Add _tracker_name | import scrapy.item
class ParsedBug(scrapy.item.Item):
# Fields beginning with an underscore are not really part of a
# bug, but extra information that can be exported.
_project_name = scrapy.item.Field()
# These fields correspond to bug data
title = scrapy.item.Field()
description = scrapy.ite... | import scrapy.item
class ParsedBug(scrapy.item.Item):
# Fields beginning with an underscore are not really part of a
# bug, but extra information that can be exported.
_project_name = scrapy.item.Field()
_tracker_name = scrapy.item.Field()
# These fields correspond to bug data
title = scrapy.i... |
Add FTPSHook in _hooks register. | # Imports the hooks dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils import import_module_attrs as _import_module_attrs
_hooks = {
'ftp_hook': ['FTPHook'],
'vertica_hook': ['VerticaHook'],
'ssh_hook': ['SSHHook'],
'bigquery_hook': ['BigQueryHook']... | # Imports the hooks dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils import import_module_attrs as _import_module_attrs
_hooks = {
'ftp_hook': ['FTPHook'],
'ftps_hook': ['FTPSHook'],
'vertica_hook': ['VerticaHook'],
'ssh_hook': ['SSHHook'],
'b... |
Make imports compliant to PEP 8 suggestion | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESS... | import turtle as t
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
t.fillcolor(FARBE)
t.shape(SHAPE)
def zeichneKerze(brennt):
t.pd()
t.begin_fill()
t.forward(GROESSE*100)
t.left(90)
t.forward(GROESSE*400)
t.left(90)
t.forward(GROESSE*100)
t.right(90)
t.forward(GROESSE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.