Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix creation of BOM when create Variant
# -*- coding: utf-8 -*- from openerp import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: custo...
# -*- coding: utf-8 -*- from openerp import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_get_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: c...
Fix aqdb rebuild to work when not using AQDCONF env variable.
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python """Test module for rebuilding the database.""" import os import __init__ import aquilon.aqdb.depends import nose import unittest from subprocess import Popen, PIPE class TestRebuild(unittest.TestCase): def testrebuild(self): env = {} for (key, valu...
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python """Test module for rebuilding the database.""" import os import __init__ import aquilon.aqdb.depends import nose import unittest from subprocess import Popen, PIPE from aquilon.config import Config class TestRebuild(unittest.TestCase): def testrebuild(self): ...
Allow for World to handle key presses.
# Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
# Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
Delete property from the interface class
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from ._function import is_nan from ._typecode import Typecode @six.add_metaclass(abc.ABCMeta) class DataPeropertyInterface(object): __slots__ = () @abc.abstractpr...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from ._function import is_nan from ._typecode import Typecode @six.add_metaclass(abc.ABCMeta) class DataPeropertyInterface(object): __slots__ = () @abc.abstractpr...
Add Image Enhance for generated image.
# -*- coding: utf-8 -*- import threading import os import shutil from PIL import Image, ImageDraw2, ImageDraw, ImageFont import random count = range(0, 200) path = './generatedNumberImages' text = '0123456789X' def start(): if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) for idx in co...
# -*- coding: utf-8 -*- import threading import os import shutil from PIL import Image, ImageDraw2, ImageDraw, ImageFont, ImageEnhance import random count = range(0, 200) path = './generatedNumberImages' text = '0123456789X' def start(): if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) ...
Make static http error code generator directory agnostic
import os, errno # Create build folder if it doesn't exist try: os.makedirs('build') except OSError as e: if e.errno != errno.EEXIST: raise template = open('./5xx.template.html', 'r') templateString = template.read() template.close() # We only use 0-11 according to # https://en.wikipedia.org/wiki/List...
import os, errno # Create build folder if it doesn't exist def get_path(relative_path): cur_dir = os.path.dirname(__file__) return os.path.join(cur_dir, relative_path) try: os.makedirs(get_path('build')) except OSError as e: if e.errno != errno.EEXIST: raise template = open(get_path('./5xx.template...
Add root URL (to serve public wishlist)
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^djadmin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^djadmin/', include(admin.site.urls)), # Root url( r'^$', 'wishlist.views.index' ), )
Set initial version for series 0.2.x
from setuptools import setup, find_packages def listify(filename): return filter(None, open(filename,'r').read().split('\n')) def remove_externals(requirements): return filter(lambda e: not e.startswith('-e'), requirements) setup( name = "vumi", version = "0.1.0", url = 'http://github.com/praekel...
from setuptools import setup, find_packages def listify(filename): return filter(None, open(filename,'r').read().split('\n')) def remove_externals(requirements): return filter(lambda e: not e.startswith('-e'), requirements) setup( name = "vumi", version = "0.2.0a", url = 'http://github.com/praeke...
Add "Pointer's Gamut" coverage computation example.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Showcases RGB colourspace volume computations. """ from __future__ import division, unicode_literals import colour from colour.utilities.verbose import message_box message_box('RGB Colourspace Volume Computations') message_box('Computing "ProPhoto RGB" RGB coloursp...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Showcases RGB colourspace volume computations. """ from __future__ import division, unicode_literals import colour from colour.utilities.verbose import message_box message_box('RGB Colourspace Volume Computations') message_box('Computing "ProPhoto RGB" RGB coloursp...
Add docstring for class Movie
# media.py class Movie(object): def __init__(self, title, storyline, poster_image_url, trailer_youtube_url, lead_actors, release_date, mpaa_rating, language, run...
# media.py class Movie(object): """ Movie class for creating a movie """ def __init__(self, title, storyline, poster_image_url, trailer_youtube_url, lead_actors, release_date, mpaa_rating, ...
Fix for empty lines in data sets
from typing import List import csv import os import random DICT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dicts") def dictionary_sample(name: str, sample: int = 1) -> List[str]: # TODO: Cache counting, and use file.seek to speed file reading. fname = os.path.join(DICT_DIR, f"{name}.cs...
from typing import List import csv import os import random DICT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dicts") def dictionary_sample(name: str, sample: int = 1) -> List[str]: # TODO: Cache counting, and use file.seek to speed file reading. fname = os.path.join(DICT_DIR, f"{name}.cs...
Remove vestigial hard coded production settings. These should be defined in a dotenv file, now.
from ._base import * SITE_PUBLIC_PORT = None # Default: SITE_PORT # DJANGO ###################################################################### CACHES['default'].update({ # 'BACKEND': 'django_redis.cache.RedisCache', 'BACKEND': 'redis_lock.django_cache.RedisCache', 'LOCATION': 'redis://redis:6379/1', ...
from ._base import * SITE_PUBLIC_PORT = None # Default: SITE_PORT # DJANGO ###################################################################### CACHES['default'].update({ # 'BACKEND': 'django_redis.cache.RedisCache', 'BACKEND': 'redis_lock.django_cache.RedisCache', 'LOCATION': 'redis://redis:6379/1', ...
Add icons on package install
#! /usr/bin/env python from distutils.core import setup from youtube_dl_gui import version setup(name='Youtube-DLG', version=version.__version__, description='Youtube-dl GUI', long_description='A cross platform front-end GUI of the popular youtube-dl written in wxPython.', license='UNLICENSE',...
#! /usr/bin/env python from distutils.core import setup from youtube_dl_gui import version name = 'Youtube-DLG' desc = 'Youtube-dl GUI' ldesc = 'A cross platform front-end GUI of the popular youtube-dl written in wxPython' license = 'UNLICENSE' platform = 'Cross-Platform' author = 'Sotiris Papadopoulos' author_email ...
Add six to the explicit dependencies
from setuptools import find_packages, setup setup( name='jupyter-notebook-gist', version='0.4.0', description='Create a gist from the Jupyter Notebook UI', author='Mozilla Firefox Data Platform', author_email='fx-data-platform@mozilla.com', packages=find_packages(where='src'), package_dir={...
from setuptools import find_packages, setup setup( name='jupyter-notebook-gist', version='0.4.0', description='Create a gist from the Jupyter Notebook UI', author='Mozilla Firefox Data Platform', author_email='fx-data-platform@mozilla.com', packages=find_packages(where='src'), package_dir={...
Declare importlib requirement on Python 2.6
import setuptools def read_long_description(): with open('README') as f: data = f.read() return data setup_params = dict( name="irc", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), use_hg_version=True, ...
import sys import setuptools def read_long_description(): with open('README') as f: data = f.read() return data importlib_req = ['importlib'] if sys.version_info < (2,7) else [] setup_params = dict( name="irc", description="IRC (Internet Relay Chat) protocol client library for P...
Upgrade django-local-settings 1.0a12 => 1.0a13
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a12', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU...
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a13', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU...
Add email (required) and packages
"""Millipede installation script https://github.com/evadot/millipede """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( ...
"""Millipede installation script https://github.com/evadot/millipede """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( ...
Remove useless requirement on Python 3.2+
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY.rst', enc...
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages import sys install_requires = [] if (sys.version_info[0], sys.version_info[1]) < (3, 2): install_requires.append('futures>=2.1.3') setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging ...
Update deps and bump version. ANL-10319
from setuptools import setup import io import os here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=encoding) as f: ...
from setuptools import setup import io import os here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=encoding) as f: ...
Use the same headline as the API
#!/usr/bin/env python """Setup script for The Coverage Space CLI.""" import setuptools from coveragespace import __project__, __version__, CLI try: README = open("README.rst").read() CHANGES = open("CHANGES.rst").read() except IOError: DESCRIPTION = "<placeholder>" else: DESCRIPTION = README + '\n' ...
#!/usr/bin/env python """Setup script for The Coverage Space CLI.""" import setuptools from coveragespace import __project__, __version__, CLI try: README = open("README.rst").read() CHANGES = open("CHANGES.rst").read() except IOError: DESCRIPTION = "<placeholder>" else: DESCRIPTION = README + '\n' ...
Fix loading of map from environment variables
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ """ import json import os from sns_utils import publish_sns_message def main(event, _): print(f'Received event:\n{event}') stream_topic_map = json.loads(os.environ["STREAM_TOPIC_MAP"]) new_image = event['Records'][0]['dynamodb']['NewImage'] topic_a...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ """ import os from sns_utils import publish_sns_message def main(event, _): print(f'Received event:\n{event}') stream_topic_map = os.environ["STREAM_TOPIC_MAP"] new_image = event['Records'][0]['dynamodb']['NewImage'] topic_arn = stream_topic_map[ev...
Include test_setquery module in distribution
#!/usr/bin/env python from setuptools import setup setup( name="setquery", version="0.1", description="Set arithmetic evaluator", author="Paul Scott", author_email="paul@duedil.com", url="https://github.com/icio/setquery", download_url="https://github.com/icio/setquery/tarball/0.1", set...
#!/usr/bin/env python from setuptools import setup setup( name="setquery", version="0.1", description="Set arithmetic evaluator", author="Paul Scott", author_email="paul@duedil.com", url="https://github.com/icio/setquery", download_url="https://github.com/icio/setquery/tarball/0.1", set...
Raise window to focus on Mac
from __future__ import print_function, division from sys import argv, stderr def run_gui(): '''Start the event loop to calucate spectra interactively''' # Import Qt functions. Do so here to handle errors better try: from PyQt4.QtGui import QApplication except ImportError: print("Cannot...
from __future__ import print_function, division from sys import argv, stderr def run_gui(): '''Start the event loop to calucate spectra interactively''' # Import Qt functions. Do so here to handle errors better try: from PyQt4.QtGui import QApplication except ImportError: print("Cannot...
Remove no longer needed references for keeping pep8 happy
from twisted.trial.unittest import TestCase from go_metrics.metrics.dummy import Fixtures, DummyMetrics, DummyBackend DummyBackend, DummyMetrics class TestFixtures(TestCase): def test_add(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(fixture...
from twisted.trial.unittest import TestCase from go_metrics.metrics.dummy import Fixtures, DummyMetrics, DummyBackend class TestFixtures(TestCase): def test_add(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(fixtures.items, [{ 'fo...
Add test for loading script.
# from django.test import TestCase # Create your tests here.
from django.test import TestCase from .models import Pregunta, Seccion, Subseccion from .load import load_data class TestLoadPreguntas(TestCase): """ Suite to test the script to load questions. """ def test_load_preguntas(self): """ Test that the script to load questions works properly. ...
Fix UUID field migration for change email request model.
from django.db import migrations import waldur_core.core.fields class Migration(migrations.Migration): dependencies = [ ('core', '0007_changeemailrequest'), ] operations = [ migrations.AddField( model_name='changeemailrequest', name='uuid', field=wald...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0007_changeemailrequest'), ] operations = [ migrations.AddField( model_name='changeemailrequest', name='uuid', field=models.UUIDField(), ), ]
Read files defined as argument
# # MIT License # Copyright (c) 2017 Hampus Tågerud # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, m...
# # MIT License # Copyright (c) 2017 Hampus Tågerud # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, m...
Fix the argument name to adapt gensim 4.0.
# -*- coding: utf-8 -*- import logging from gensim.models import word2vec def main(): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = word2vec.LineSentence("wiki_seg.txt") model = word2vec.Word2Vec(sentences, size=250) #保存模型,供日後使用 model.sa...
# -*- coding: utf-8 -*- import logging from gensim.models import word2vec def main(): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = word2vec.LineSentence("wiki_seg.txt") model = word2vec.Word2Vec(sentences, vector_size=250) #保存模型,供日後使用 m...
Make basic composite pass work
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Resources import Resources from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): def __init__(self, name, width, height): super().__init__(name...
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): ...
Make sure version is initialized
import libsinan from libsinan import handler, output, jsax class VersionCheckTaskHandler(output.SimpleTaskHandler): def object_end(self): """ We only get one object per right now so lets print it out when we get it """ if self.task == "version": if self.event_type == 'info':...
import libsinan from libsinan import handler, output, jsax class VersionCheckTaskHandler(output.SimpleTaskHandler): def __init__(self): output.SimpleTaskHandler.__init__(self) self.version = None def object_end(self): """ We only get one object per right now so lets print it ...
Update stream name to Replay
from index import app from flask import render_template, request from config import BASE_URL from query import get_callout, get_billboard SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A' #SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet #@app.route('/') #def index(): # page_url = BASE_URL + request.path # page_title = '...
from index import app from flask import render_template, request from config import BASE_URL from query import get_callout, get_billboard SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A' #SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet @app.route('/') def index(): page_url = BASE_URL + request.path page_title = 'Audi...
Change the api a little bit
from pyolite import Pyolite # initial olite object admin_repository = '~/presslabs/ansible-playbooks/gitolite-admin' olite = Pyolite(admin_repository=admin_repository) # create a repo repo = olite.repos.get_or_create('awesome_name') repo = olite.repos.get('awesome_name') repo = olite.repos.create('awesome_name') # a...
from pyolite import Pyolite # initial olite object admin_repository = '~/presslabs/ansible-playbooks/gitolite-admin' olite = Pyolite(admin_repository=admin_repository) # create a repo repo = olite.repos.get_or_create('awesome_name') repo = olite.repos.get('awesome_name') repo = olite.repos.create('awesome_name') # a...
Update the script to create EC2 instance.
import boto3 import botocore import time ec2 = boto3.resource('ec2', region_name='us-east-1') client = boto3.client('ec2') # Create a security group try: sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook') response = client.authorize_security_group_ingress(GroupName='ju...
import boto3 import botocore import time ec2 = boto3.resource('ec2', region_name='us-east-1') client = boto3.client('ec2') # Create a security group try: sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook') response = client.authorize_security_group_ingress(GroupName='ju...
Add test for command compilation
from cisco_olt_client.command import Command def test_simple_compile(): cmd_str = 'cmd --arg1=val1 --arg2=val2' cmd = Command('cmd', (('arg1', 'val1'), ('arg2', 'val2'))) assert cmd.compile() == cmd_str cmd = Command('cmd', {'arg1': 'val1', 'arg2': 'val2'}) # order is not guaranteed assert '-...
Add script to convert DET window file to VID window file.
#!/usr/bin/env python import argparse import scipy.io as sio import os import os.path as osp import numpy as np from vdetlib.vdet.dataset import index_det_to_vdet if __name__ == '__main__': parser = argparse.ArgumentParser('Convert a window file for DET for VID.') parser.add_argument('window_file') parser....
Add simple script for parsing meeting doc dirs
# KlupuNG # Copyright (C) 2013 Koodilehto Osk <http://koodilehto.fi>. # # 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 ve...
Add small example of sqlite FTS with compression.
# # Small example demonstrating the use of zlib compression with the Sqlite # full-text search extension. # import zlib from peewee import * from playhouse.sqlite_ext import * db = SqliteExtDatabase(':memory:') class SearchIndex(FTSModel): content = SearchField() class Meta: database = db @db.fun...
Add py solution for 692. Top K Frequent Words
from collections import Counter import heapq class Neg(): def __init__(self, x): self.x = x def __cmp__(self, other): return -cmp(self.x, other.x) class Solution(object): def topKFrequent_nlogk(self, words, k): """ :type words: List[str] :type k: int :rtype:...
Add script for creating SQA docs in a module
#!/usr/bin/env python from __future__ import print_function import os import shutil import argparse parser = argparse.ArgumentParser(description='Setup SQA documentation for a MOOSE module.') parser.add_argument('module', type=str, help='The module folder name') args = parser.parse_args() folder = args.module title ...
Add a client test on the users list view
#! /usr/bin/env python __author__ = 'Henri Buyse' import pytest import datetime from django.contrib.auth.handlers.modwsgi import check_password from django.contrib.auth.models import User from django.test import Client from accounts.models import VBUserProfile key_expires = datetime.datetime.strftime(datetime.da...
Remove coverage options from default test run
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'...
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'...
Create parametrized superclass for tests
import logging import unittest from elasticsearch import Elasticsearch, TransportError class ParametrizedTest(unittest.TestCase): def __init__(self, methodName='runTest', gn2_url="http://localhost:5003", es_url="localhost:9200"): super(ParametrizedTest, self).__init__(methodName=methodName) self.g...
Add simple mrequests GET example
import mrequests as requests host = 'http://localhost/' url = host + "get" r = requests.get(url, headers={"Accept": "application/json"}) print(r) print(r.content) print(r.text) print(r.json()) r.close()
Test using bezier going through 4 specific points
from __future__ import division import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # import cocos from cocos.director import director from cocos.actions import Bezier from cocos.sprite import Sprite import pyglet from cocos import path def direct_bezier(p0, p1, p2, p3): '''G...
Test program for QMessageBox formatting
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Test code for controlling QMessageBox format. """ import sys from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import (QApplication, QLabel, QWidget, QMessageBox, QSpinBox, QLineEdit, QPushButton, QHBoxLayout, ...
Add file for ipython notebook snippets
"""ipynb.py -- helper functions for working with the IPython Notebook This software is licensed under the terms of the MIT License as follows: Copyright (c) 2013 Jessica B. Hamrick Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "S...
Add missing migration for Invitation.email
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('orgs', '0011_auto_20150710_1612'), ] operations = [ migrations.AlterField( model_name='invitation', ...
Add migration for view_all_talks permission.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('talks', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='talk', options={'permi...
Add Tunnel Zone and Tunnel Zone Host API handlers
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2014 Midokura SARL. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.o...
Add a unit test for flatc
import pytest # TODO: Duplicate code # Figure out how to import from flatc.py def get_attrs_dict(attrs): attrs_dict = {x[0]: x[1] for x in attrs if len(x) == 2} ret = {x[0]: None for x in attrs} ret.update(attrs_dict) return ret def test_attrs_dict(): assert get_attrs_dict(['a', ['b', 10], 'c'])...
Add first basic unittests using py.test
""" test_validators ~~~~~~~~~~~~~~ Unittests for bundled validators. :copyright: 2007-2008 by James Crasta, Thomas Johansson. :license: MIT, see LICENSE.txt for details. """ from py.test import raises from wtforms.validators import ValidationError, length, url, not_empty, email, ip_addres...
Add template filters test cases
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import render_template_string def test_nl2br_filter(app): s = '{{ "\n"|nl2br }}' rs = render_template_string(s) assert rs == '<p><br/>\n</p>' def test_blankspace2nbsp_filter(app): s = '{{ " \t"|blankspace2nbs...
Add functions to handle temp directory for download
import os import time TMP_DIR = "/tmp/lobster" def get_tempdir(): tmp_path = TMP_DIR if not os.path.isdir(tmp_path): os.mkdir(tmp_path) return tmp_path def get_workingdir(): tmp_dir = get_tempdir() dir_name = str(int(time.time())) path = "/".join([tmp_dir, dir_name]) os.mkdir(path...
Add standings checker to prevent friendly fire
#!/usr/bin/python from eveapi import eveapi import ChatKosLookup import sys class StandingsChecker: def __init__(self, keyID, vCode): self.checker = ChatKosLookup.KosChecker() self.eveapi = self.checker.eveapi.auth(keyID=keyID, vCode=vCode) def check(self): contacts = self.eveapi.char.ContactList() ...
Add test for JSON encoding `bytes` and `bytearray`
import json from nose.tools import assert_equal from encryptit.dump_json import OpenPGPJsonEncoder def test_encode_bytes(): result = json.dumps(bytes(bytearray([0x01, 0x08])), cls=OpenPGPJsonEncoder) assert_equal('{"octets": "01:08", "length": 2}', result) def test_encode_bytearray(): result = json.du...
Allow resuse-addr at http server start
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output""" import SimpleHTTPServer import SocketServer import log try : log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)') httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.s...
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output""" import SimpleHTTPServer import SocketServer import log try : log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)') SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(('localhost', 8000), ...
Add tests for adding parser actions
'''Test the ability to add a label to a (potentially trained) parsing model.''' from __future__ import unicode_literals import pytest import numpy.random from thinc.neural.optimizers import Adam from thinc.neural.ops import NumpyOps from ...attrs import NORM from ...gold import GoldParse from ...vocab import Vocab fro...
Add a helper script for creating migrations
#!/usr/bin/env python import decimal import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( DEBUG=True, USE_TZ=True, TIME_ZONE='UTC', DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MIDDLEWARE_CLASSES=[ ...
Add template tag to render ``markdown``.
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from us_ignite.common import output register = template.Library() @register.filter(is_safe=True) @stringfilter def markdown(value): return mark_safe(output.to_html(value))
Add test for function re-definition
from numba import * import unittest class TestRedefine(unittest.TestCase): def test_redefine(self): def foo(x): return x + 1 jfoo = jit(int32(int32))(foo) # Test original function self.assertTrue(jfoo(1), 2) jfoo = jit(int32(int32))(foo) # Test re-c...
Add python data transmission example.
import serial import time class blinkyBoard: def init(self, port, baud): self.serial = serial.Serial(port, baud) self.serial.open() def sendPixel(self,r,g,b): data = bytearray() data.append(0x80 | (r>>1)) data.append(0x80 | (g>>1)) data.append(0x80 | (b>>1)) self.serial.write(data) ...
Add a helper tool which clears zookeeper test dirs
#!/usr/bin/env python import contextlib import os import re import sys top_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.insert(0, top_dir) from taskflow.utils import kazoo_utils @contextlib.contextmanager def finalize_client(client): ...
Add tempest unit test to verify the test list
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
Add a very simple test
import safe def test_simple_exception(): class MockReponse(object): def json(self): return {'status': False, 'method': 'synchronize', 'module': 'cluster', 'error': {'message': 'Example error'}} exception = safe.library.raise_from...
Add unit test to cover Mako entry point.
from unittest import TestCase from dogpile.cache import util class MakoTest(TestCase): """ Test entry point for Mako """ def test_entry_point(self): import pkg_resources for impl in pkg_resources.iter_entry_points("mako.cache", "dogpile.cache"): print im...
Add Python script to read mouse delta position events
import struct file = open ("/dev/input/mice","rb"); def getMouseEvent(): buf = file.read(3); x,y = struct.unpack("bb", buf[1:] ); print ("x:%d, y:%d\n" % (x,y)); while(1): getMouseEvent() file.close;
Add Bootstrap Google Tour example
from seleniumbase import BaseCase class MyTourClass(BaseCase): def test_google_tour(self): self.open('https://google.com') self.wait_for_element('input[title="Search"]') self.create_bootstrap_tour() # OR self.create_tour(theme="bootstrap") self.add_tour_step( "Click ...
Add unittest for concurrent redirect target create
# Copyright 2020 NOKIA # # 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...
Add script to generate website board metadata.
#!/usr/bin/env python3 import glob import json import os import sys def main(repo_path, output_path): boards_index = [] board_ids = set() for board_json in glob.glob(os.path.join(repo_path, "ports/*/boards/*/board.json")): # Relative path to the board directory (e.g. "ports/stm32/boards/PYBV11")...
Add conceptual implementation of BaseCachedTask
""" Tasks cached on data store. """ from .base import BaseTask class BaseCachedTask(BaseTask): datastore = None """ Data store instance. Child class **must** set this attribute. """ def is_finished(self): current = self.get_taskhash() cached = self.get_cached_taskhash() ...
Increment version to v0.3.91 for PyPi.
# # furl - URL manipulation made simple. # # Arthur Grunseid # grunseid.com # grunseid@gmail.com # # License: Build Amazing Things (Unlicense) __title__ = 'furl' __version__ = '0.3.9' __license__ = 'Unlicense' __author__ = 'Arthur Grunseid' __contact__ = 'grunseid@gmail.com' __url__ = 'https://github.com/gruns/furl' ...
# # furl - URL manipulation made simple. # # Arthur Grunseid # grunseid.com # grunseid@gmail.com # # License: Build Amazing Things (Unlicense) __title__ = 'furl' __version__ = '0.3.91' __license__ = 'Unlicense' __author__ = 'Arthur Grunseid' __contact__ = 'grunseid@gmail.com' __url__ = 'https://github.com/gruns/furl' ...
Convert .png endings to .jpg
""" Change image extensions from .png to .jpg EXAMPLE: >>>> echo An ![image](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png) | pandoc -F png2jpg.py """ import panflute as pf def action(elem, doc): if isinstance(elem, pf.Image): elem.url = elem.url.replace('.png', '.j...
Add testcase for search indexing of Service
from django.test import TestCase from services.tests.factories import ServiceFactory from services.models import Service from services.search_indexes import ServiceIndex class IndexingTest(TestCase): def setUp(self): self.service_ar = ServiceFactory( name_ar='Arabic', name_en='', name_fr='',...
Build a legacy distance export
import json import sys import database as db from database.model import Team from geotools import simple_distance from geotools.routing import MapPoint from webapp.cfg.config import DB_CONNECTION if len(sys.argv) == 2: MAX_TEAMS = sys.argv[1] else: MAX_TEAMS = 9 print "init db..." db.init_session(connection_...
Add serialization tests for tagger
# coding: utf-8 from __future__ import unicode_literals from ..util import make_tempdir from ...pipeline import NeuralTagger as Tagger import pytest @pytest.fixture def taggers(en_vocab): tagger1 = Tagger(en_vocab, True) tagger2 = Tagger(en_vocab, True) tagger1.model = tagger1.Model(None, None) tagg...
Add script to find destructors which are not virtual, but should be
#!/usr/bin/env python # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
Add a custom client side test runner
from tests import web_client_test setUpModule = web_client_test.setUpModule tearDownModule = web_client_test.tearDownModule class WebClientTestCase(web_client_test.WebClientTestCase): def setUp(self): super(WebClientTestCase, self).setUp() self.model('user').createUser( login='mine...
Add some unit tests for the diagonals.
#! /usr/bin/env python import numpy as np from nose.tools import assert_is, assert_is_instance from numpy.testing import assert_array_equal from landlab.grid.diagonals import create_nodes_at_diagonal def test_nodes_at_diagonal(): """Test tail and head nodes of diagonals.""" diagonals = create_nodes_at_diago...
Add a few statement comparison tests
""" Test ChatterBot's statement comparison algorithms. """ from unittest import TestCase, SkipTest from chatterbot.conversation import Statement from chatterbot import comparisons class LevenshteinDistanceTestCase(TestCase): def test_levenshtein_distance_statement_false(self): """ Falsy values s...
Add Unicode volume name test
# -*- coding: utf-8 -*- # Copyright 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
Add a script that moves files to Azure storage using Copy Blob API
import sys import time from azure.storage import BlobService from azure import WindowsAzureMissingResourceError from CREDENTIALS import account_name, account_key db = BlobService(account_name=account_name, account_key=account_key) ### bucket = 'crawl-data' in_progress = set() # existing = set([x.name for x in db.list...
Test views return response for searched query
from django.test import TestCase, Client from ..models import Category, Book class CompassTest(TestCase): @classmethod def setUpClass(cls): cls.client = Client() super(CompassTest, cls).setUpClass() def test_can_view_search_page(self): response = self.client.get('/') self...
Add test for reading and writing avro bytes to hdfs
import posixpath import subprocess import numpy as np import pandas as pd import pandas.util.testing as pdt import cyavro from utils import * avroschema = """ {"type": "record", "name": "from_bytes_test", "fields":[ {"name": "id", "type": "int"}, {"name": "name", "type": "string"} ] } """ def test_avro_mov...
Add an example of event monitoring.
import time from examples.common import print_devices import blivet from blivet.events.manager import event_manager from blivet.util import set_up_logging def print_changes(event, changes): print("***", event) for change in changes: print("***", change) print("***") print() set_up_logging(c...
Add a command that imports the 2013 election boundaries
# This script imports the boundaries for the 2013 Kenyan election into # MapIt - it uses the generic mapit_import script. import json import os import sys import urllib from tempfile import NamedTemporaryFile from optparse import make_option from django.core.management import call_command from django.core.managemen...
Test to ensure equations with line breaks are parsed correctly
import os import unittest import tempfile from io import StringIO from pysd.py_backend.xmile.xmile2py import translate_xmile class TestEquationStringParsing(unittest.TestCase): def test_multiline_equation(): with open('tests/test-models/tests/game/test_game.stmx', 'r') as stmx: contents = s...
Sort a linked list using insertion sort
#!/usr/bin/python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if None == head: ret...
Add tasks to anonymize past opt outs
from django.core.management.base import BaseCommand, CommandError from studygroups.models import Application class Command(BaseCommand): help = 'Anonymize applications that previously opted out' def handle(self, *args, **options): applications = Application.objects.filter(deleted_at__isnull=False) ...
Add beginnings of some gizmo test coverage
from unittest import TestCase from groundstation.transfer.request import Request class TestGizmoRequest(TestCase): def test_loadable_after_serializing(self): gizmo = Request("LISTALLOBJECTS") def test_rejects_invalid_verbs(self): with self.assertRaises(Exception): gizmo = Request(...
Add the GPIO proxy class for the Raspberry Pi
# The MIT License (MIT) # # Copyright (c) 2015 Frederic Jacob # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
Add tests for the stacks.yml file
import json from dmaws.stacks import Stack from dmaws.context import Context def is_true(x): assert x def is_in(a, b): assert a in b def valid_stack_json(stack): text = stack.build('stage', 'env', {}).template_body template = json.loads(text) assert 'Parameters' in template assert set(te...
Add a test that imports runlint under both python2 and python3
#!/usr/bin/env python import subprocess import unittest class TestPy2Py3Compat(unittest.TestCase): """We need to be compatible with both python2 and 3. Test that we can at least import runlint.py under both. """ def test_python2_compat(self): subprocess.check_call(['python2', '-c', 'import ...
Add udp sender for debug purpose
import socket UDP_IP = "192.168.1.1" UDP_PORT = 1234 MESSAGE = "Hello, World!" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
Print installed packages in pytest
import os import subprocess import sys def _is_pip_installed(): try: import pip # NOQA return True except ImportError: return False def _is_in_ci(): ci_name = os.environ.get('CUPY_CI', '') return ci_name != '' def pytest_configure(config): # Print installed packages ...
Fix loading root_target in migration
from __future__ import unicode_literals from django.db import migrations import logging logger = logging.getLogger(__file__) def update_comment_root_target(state, *args, **kwargs): Comment = state.get_model('osf', 'comment') comments = Comment.objects.filter(is_deleted=False) count = 0 for comment i...
from __future__ import unicode_literals import logging from django.db import migrations from django_bulk_update.helper import bulk_update logger = logging.getLogger(__file__) def update_comment_root_target(state, *args, **kwargs): Comment = state.get_model('osf', 'comment') comments = Comment.objects.exclud...
Add shim for clover package name and deprecation warning
# This is here simply to aid migration to trefoil. It will be removed in a future version! import sys import warnings import trefoil warnings.simplefilter('always', DeprecationWarning) warnings.warn( "the package name 'clover' has been deprecated; use 'trefoil' instead", DeprecationWarning) sys.modules['cl...
Add basic query string tests
import pytest from httoop import URI @pytest.mark.parametrize('query_string,query', [ (b'', ()), (b'&', ()), (b'&&', ()), # (b'=', ((u'', u''),)), # (b'=a', ((u'', u'a'),)), (b'a', ((u'a', u''),)), (b'a=', ((u'a', u''),)), (b'&a=b', ((u'a', u'b'),)), (b'&&a=b&&b=c&d=f&', ((u'a', u'b'), (u'b', u'c'), (u'd', u'f...
Add py solution for 401. Binary Watch
from operator import mul class Solution(object): def dfs(self, rem, cur, depth): if depth == 10: h = sum(map(mul, cur[:4], [1, 2, 4, 8])) m = sum(map(mul, cur[4:], [1, 2, 4, 8, 16, 32])) if h < 12 and m < 60: yield '{}:{:02d}'.format(h, m) else: ...
Add test and workaround for function.__module__ attr.
""" categories: Core,Functions description: Function objects do not have the ``__module__`` attribute cause: MicroPython is optimized for reduced code size and RAM usage. workaround: Use ``sys.modules[function.__globals__['__name__']]`` for non-builtin modules. """ def f(): pass print(f.__module__)
Add a testcase for Manual
from tests.helper import ExternalVersionTestCase class ManualTest(ExternalVersionTestCase): def test_manual(self): self.assertEqual(self.sync_get_version("example", {"manual": "Meow"}), "Meow")