Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Test for very basic operations
from __future__ import nested_scopes from twisted.internet import reactor import unittest from twistedsnmp.test import basetestcase from twistedsnmp import tableretriever, agentproxy from twistedsnmp.pysnmpproto import v2c,v1, error class BasicProxyTests( basetestcase.BaseTestCase ): version = 'v2c' def testBulkRequ...
Add improved script for extracting sentence patts
#!/usr/bin/env python """ Usage: extract-patterns.py FILE Print patterns in the structure of parse trees in FILE """ from sexp import sexps, tokenize, isterminal import re import sys filename = sys.argv[1] def remove_coindex(s): return re.sub('-\d+$', '', s) def get_verb(sexp): if isterminal(sexp): ...
Update the example via boto3
import os import boto3 import botocore from boto3.core.session import Session os.environ['AWS_CONFIG_FILE'] = "/etc/profiles.cfg" orig_owner = "" shared_owner = "" region = "us-west-2" session = botocore.session.get_session() session.profile = 'beta' session = Session(session=session) ec2_conn = session.connect_to(...
Make pylpfile path more readable
""" Some useful functions for using paths. Copyright (C) 2017 The Pylp Authors. This file is under the MIT License. """ import os.path # Make a path more "readable" def make_readable_path(path): home = os.path.expanduser("~") if path.startswith(home): path = "~" + path[len(home):] return path...
Add script to convert old language files
#!/usr/bin/env python ################################################################################ # ConvertLanguage.py - converts an old 3RVX version 2.X language file to the new # 3.X format. A 'template' file is used to provide the missing strings that # didn't exist in the old 2.X translations. # # Matthew Male...
Add the .py file to the repo.
# drawing out a hello world with the python turtle library! # extension: different modules for each turtle so letter color, etc. can be easily changed. # TODO: fix angle errors, draw the rest of the letters import turtle wn = turtle.Screen() h = turtle.Turtle() # move module to the left side of the screen h.penup() ...
Add tests for city generation.
import unittest import mock from geometry.point import Point from models.street import Street from models.trunk import Trunk from models.ground_plane import GroundPlane from models.building import Building from models.block import Block from models.city import City class CityModelTest(unittest.TestCase): def te...
Move JavaTransMap to another module
import datetime # Must be completed # tuple is '(implem_type, use_type_as_factory, default_value)' javaTransMap = { 'int': (int, False, 0), 'boolean': (bool, False, False), 'byte': (int, False, 0), 'short': (int, False, 0), 'long': (int, False, 0), 'float': (float, False, 0.0), 'char': (str...
Add testing for Excel writer
import numpy as np import pandas as pd from skan import io from skimage._shared._tempfile import temporary_file def test_write_excel_tables(): num_sheets = np.random.randint(1, 4) num_cols = np.random.randint(1, 5, size=num_sheets) num_rows = np.random.randint(20, 40, size=num_sheets) tables = [] ...
Add a syntax check script.
#!/usr/bin/env python """ Run lint checks for Synapse. Requires pycodestyle to be installed. Forked from https://gist.github.com/810399 Updated from https://github.com/cbrueffer/pep8-git-hook """ from __future__ import print_function import os import subprocess import sys # don't fill in both of these # good codes s...
Add rudimentary initial placement RR controller
from logs import sonarlog from workload.timeutil import * # @UnusedWildImport import conf_domains import conf_nodes import initial_placement # Setup logging logger = sonarlog.getLogger('initial_placement') class RRPlacement(initial_placement.InitialPlacement): def execute(self): # Execute super code ...
Add initial URL history importer
#!/usr/bin/env python # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
Test for previous ResourceGroup change.
import ckanext.archiver.model as archiver_model try: from ckan.tests.helpers import reset_db from ckan.tests import factories as ckan_factories except ImportError: from ckan.new_tests.helpers import reset_db from ckan.new_tests import factories as ckan_factories from ckan import model Archival = archiv...
Migrate prefix SMS setting to be true or false
import os from app import config """ Revision ID: 0133_set_services_sms_prefix Revises: 0132_add_sms_prefix_setting Create Date: 2017-11-03 15:55:35.657488 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = '0133_set_services_sms_prefix' down_revision = '0132_add...
Make sure region name is uppercase.
from st2actions.runners.pythonrunner import Action import pyrax __all__ = [ 'PyraxBaseAction' ] class PyraxBaseAction(Action): def __init__(self, config): super(PyraxBaseAction, self).__init__(config) self.pyrax = self._get_client() def _get_client(self): username = self.config['u...
import pyrax from st2actions.runners.pythonrunner import Action __all__ = [ 'PyraxBaseAction' ] class PyraxBaseAction(Action): def __init__(self, config): super(PyraxBaseAction, self).__init__(config) self.pyrax = self._get_client() def _get_client(self): username = self.config[...
Add script to set angle of attack
#!/usr/bin/env python import sys alpha_deg = sys.argv[1] with open("system/fvOptions", "w") as f: with open("system/fvOptions.template") as template: txt = template.read() f.write(txt.format(alpha_deg=alpha_deg))
Add a script for instantiating dif_template.tpl.h
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # make_new_dif.py is a script for quickly applying replacement operations to # dif_template.h.tpl. See sw/device/lib/dif/dif_template.h.tpl for more ...
Add a test for Python 3.3 bdist_egg issue
import sys import os import tempfile import unittest import shutil import copy CURDIR = os.path.abspath(os.path.dirname(__file__)) TOPDIR = os.path.split(CURDIR)[0] sys.path.insert(0, TOPDIR) from distribute_setup import (use_setuptools, _build_egg, _python_cmd, _do_download, _install, D...
Use relative import to allow vendoring
# Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
Add some tests for crypto/aes
#/usr/bin/python # -*- coding: utf-8 -*- # Run from Cryptchat # python -m unittest discover import unittest from ..crypto.aes import AESCipher class testAESCipher(unittest.TestCase): def test_encrypt_decrypt(self): key = "TTTcPolAhIqZZJY0IOH7Orecb/EEaUx8/u/pQlCgma8=" cipher = AESCipher(key) ...
Add 1 check, unlucky days
#!/usr/bin/env python from datetime import date def checkio(year): day_count = 0 for month in range(1, 13): day = date(year, month, 13) # Day = ISO8601 1..7 for Mon -> Sun if day.isoweekday() == 5: day_count += 1 return day_count def test_function(): # These "ass...
Add tests for multiple hashes
# -*- coding: utf-8 -*- # Import sorbic libs import sorbic.db # Import python libs import os import shutil import unittest import tempfile try: import libnacl.blake HAS_BLAKE = True except ImportError: HAS_BLAKE = False class TestDB(unittest.TestCase): ''' ''' def _run_test(self, key_hash): ...
Add utility to remove un-needed rules
import glob import os import re def process(text, start=None): # Full Definition # ((.*) =\s+([\s\S]*?)\s*;\n) # Group1 is the full rule definition # Group2 is only the name of the rule # Group3 is the definition of the rule # Definitions within this definition # (?<!')\b\w+\b(?!') # ...
Add report kernel with API for Spacewalk
''' # ..######. # .##....## # .##...... # ..######. # .......## # .##....## # ..######. ################################################################################ # # Script: List of running kernel of spacewalk client # ################################################################################ ''' from _...
Add missing migrations for removing default from Card.source_id
# Generated by Django 2.0 on 2017-12-03 01:21 from django.db import migrations import djstripe.fields class Migration(migrations.Migration): dependencies = [ ('djstripe', '0012_card_customer_from_source'), ] operations = [ migrations.AlterField( model_name='card', ...
Add test for SwapSpace max size
import test_compat # pylint: disable=unused-import import six import unittest from blivet.devices.storage import StorageDevice from blivet.errors import DeviceError from blivet.formats import get_format from blivet.size import Size class SwapNodevTestCase(unittest.TestCase): def test_swap_max_size(self): ...
Add script to remove notes
#!/usr/bin/env python3 from bs4 import BeautifulSoup import sys with open(sys.argv[1], "r") as f: tree = BeautifulSoup(f, 'html.parser') for note in tree.find_all("div", class_ = "notes"): note.decompose() print(tree)
Add solution for problem 30
#!/usr/bin/python power_sum = 0 # Upper limit is a 6 digits number for i in range(2, (9 ** 5) * 6): # I'm loving Python sugar if sum(int(j) ** 5 for j in str(i)) == i: # If you want to see the numbers # print(i) power_sum += i print(power_sum)
Add tests for the fields updated in ee3cd62
# -*- coding: utf-8 -*- import pytest import iso3166 def test_country_list(): country_list = iso3166.countries assert len(country_list) > 100 assert all(isinstance(c, iso3166.Country) for c in country_list) def test_by_name(): table = iso3166.countries_by_name assert len(table) >= len(iso3166.c...
Remove preview field from DB
# Generated by Django 3.1.7 on 2021-04-27 18:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('museum_site', '0049_auto_20210324_1957'), ] operations = [ migrations.RemoveField( model_name='article', name='preview', ...
Send request for bbt username
import requests from bs4 import BeautifulSoup username = raw_input('Enter your username: ') print username payload = {'UserName': username, 'input': 'Go'} r = requests.post("https://online.bbt.com/auth/pwd.tb", data = payload) print (r.text)
Add some tests of instantiation
# -*- coding: utf-8 -*- import unittest import datac class Instantiation(unittest.TestCase): """ Test instantiation works according to spec """ def test_params_non_dict(self): """ Datac instantiation should fail is params is not a dict """ params = None abscissae...
Add script to fetch demographics.
from sqlalchemy.orm import sessionmaker # scraping modules from scrapy.crawler import CrawlerProcess, Crawler from demographic_scraper.demographic_scraper.spiders.alexa_spider import AlexaSpider from scrapy.utils.project import get_project_settings from models import db_connect, WebsitesContent def main(): """I...
Add test for crop function
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr class TestCrop(unittest.TestCase): axes = [1, 2] def setUp(self): self.x0_data = numpy.random.uniform(-1...
Add a course following predictor
from users.models import User from catalog.models import Course import collections from django.contrib.contenttypes.models import ContentType from actstream.models import Follow def distance(v1, v2): absolute_difference = [abs(c1 - c2) for c1, c2 in zip(v1, v2)] distance = sum(absolute_difference) return ...
Add create (dataset) table sample script
#!/usr/bin/env python ''' Create dataset table (w/ sample schema) ''' import httplib2 from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials from apiclient.errors import HttpError from config import Credential as gc dataset_id = 'DATASET-ID-HERE' new_table_id = 'NEW-TABL...
Add debugging to find issue.
from flask import render_template, redirect, jsonify, session from flask_login import login_user from app.main import main from app.main.dao import users_dao, verify_codes_dao from app.main.forms import TwoFactorForm @main.route("/two-factor", methods=['GET']) def render_two_factor(): return render_template('vie...
import traceback from flask import render_template, redirect, jsonify, session from flask_login import login_user from app.main import main from app.main.dao import users_dao, verify_codes_dao from app.main.forms import TwoFactorForm @main.route("/two-factor", methods=['GET']) def render_two_factor(): return re...
Add browse image setup test.
# coding=utf-8 from __future__ import absolute_import from eodatasets import browseimage, drivers, type as ptype from tests import write_files, assert_same def test_create_typical_browse_metadata(): class TestDriver(drivers.DatasetDriver): def browse_image_bands(self, d): return '5', '1', '3'...
Add a simple transform helper class.
""" DataTransformer :Authors: Berend Klein Haneveld """ from vtk import vtkImageReslice class DataTransformer(object): """DataTransformer is a class that can transform a given dataset""" def __init__(self): super(DataTransformer, self).__init__() def TransformImageData(self, imageData, transform): """ :t...
Add script to process log outputs and do Mean Value Analysis (MVA).
#!/usr/bin/python3 import sys import collections sums = collections.defaultdict(lambda: 0) lens = collections.defaultdict(lambda: 0) def mva(n_a, s_lb, s_a, avg_len, clients, z): n_centers = n_a + 2 V = [2] + [1 / n_a] * n_a + [1] S = [s_lb] + [s_a] * n_a + [z] is_delay = [False] * (n_centers - 1) + ...
Update Resource migrations to reflect model changes
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-21 23:04 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resources', '0009_auto_20171020_1005'), ] ope...
Add our own check_output2 wrapper
from __future__ import absolute_import import subprocess def check_output2(args, stdin=None): p = subprocess.Popen( args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, ) out, _ = p.communicate(input=stdin) retcode = p.wait() if retcode:...
Add script for appending entries to .gitignore.
#!/usr/bin/env python # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All c...
Use to make close loop test on single axis
from SimpleCV import * import time import serial cam = JpegStreamCamera('http://192.168.1.6:8080/videofeed') disp=Display() ser=serial.Serial('/dev/ttyACM2', 9600) alpha = 0.8 time.sleep(1) previous_z = 200; while True: img = cam.getImage() myLayer = DrawingLayer((img.width,img.height)) disk_img = img.hueD...
Add a linear sample for mnist in python.
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("data/", one_hot=True) image_dim = 28 * 28 label_count = 10 graph = tf.Graph() with graph.as_default(): x = tf.placeholder("float", shape=[None, image_dim]) y_ = tf.placeholder("float", shape=[None...
Print more stock stuff in small space.
#!/usr/bin/env python import ystockquote as y x = 'SYK' a = y.get_all(x) # 'fifty_two_week_low', 'fifty_day_moving_avg', 'price', 'price_book_ratio', 'volume', 'market_cap', 'dividend_yield', 'ebitda', 'change', 'dividend_per_share', 'stock_exchange', 'two_hundred_day_moving_avg', 'fifty_two_week_high', 'price_sales_...
Add script for turning lines of JSON-LD records into chunked datasets
from __future__ import unicode_literals, print_function import sys import os import re CONTEXT_PATH = 'context.jsonld' args = sys.argv[1:] basepath = args.pop(0) if args else 'data' chunksize = int(args.pop(0)) if args else 100 * 1000 outfile = None def next_outfile(i): global outfile fpath = "{}-{}.jsonld...
Add brian's sms import scripts + test data
#!/usr/bin/env python # encoding: utf-8 """ sms-recovery.py Created by Brian DeRenzi on 2010-04-27. Copyright (c) 2010 __MyCompanyName__. All rights reserved. """ import sys import os import MySQLdb from datetime import datetime, timedelta DB_HOST = "localhost" DB_USER = "changeme" DB_PASSWORD = "changeme" DB_NAME =...
Work around site_persistence fragility. Replace a couple names as delete and recreate on these fails due to FK constraints
from alembic import op import sqlalchemy as sa """empty message Revision ID: d0b40bc8d7e6 Revises: 8ffec90e68a7 Create Date: 2017-09-20 05:59:45.168324 """ # revision identifiers, used by Alembic. revision = 'd0b40bc8d7e6' down_revision = '8ffec90e68a7' def upgrade(): # Work around site_persistence fragility...
Write migration for API keys
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def migrate_keys(apps, schema_editor): Token = apps.get_model("authtoken", "Token") ApiKey = apps.get_model("tastypie", "ApiKey") for key in ApiKey.objects.all(): Token.objects.create( use...
Add module with utility functions.
import numpy as np def centroid(x, flux): mu = np.sum(x*flux)/np.sum(flux) sd = np.sqrt(np.sum(flux * (x-mu)**2)/np.sum(flux)) return mu,sd def approx_stokes_i(Axx,Ayy): try: a = np.sqrt((Axx**2 + Ayy**2)/2.) except TypeError: a = type(Axx)() a.header = Axx.header ...
Implement async test framework for the server
# -*- coding: utf-8 import json import random import string import tornado.gen import tornado.testing import tornado.web import tornado.websocket from sidecar.connection import Connection class AsyncSockJSClient(object): def __init__(self, ws): self.ws = ws def send(self, data): self.ws.wri...
Add a Python based documentation generator, which requires libxml2 and libxlst.
#!/usr/bin/env python # -*- coding: utf-8 -*- import optparse import os import libxml2 import libxslt def generate_documentation(src_file, destination_file, stylesheet_file): stylesheet_args = dict() style = libxslt.parseStylesheetFile(stylesheet_file) document = libxml2.parseFile(src_file) result =...
Add migration for Strain.reference TreeForeignKey
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-17 12:57 from __future__ import unicode_literals from django.db import migrations import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('core', '0005_strain_reference'), ] oper...
Add unit tests for inode.
from __future__ import absolute_import import pytest import os import sys try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import struct import time prefix = '.' for i in range(0, 3): if os.path.isdir(os.path.join(prefix, 'pycdlib')): sys.path.insert(0, pre...
Add script for displaying jacobian as a matrix.
import climate import lmj.cubes import lmj.plot import numpy as np @lmj.cubes.utils.pickled def jacobian(root, pattern, frames): trial = list(lmj.cubes.Experiment(root).trials_matching(pattern))[0] trial.load() return trial.jacobian(frames) def main(root, pattern='68/*block03/*trial00', frames=10, frame...
Move Pillow to the last version
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.2.6.1', url='http://github.com/jorgeb...
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.2.6.1', url='http://github.com/jorgeb...
Add command for S3 CORS configuration.
import boto3 from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Set CORS rules on the Notice and Comment attachment bucket' def handle(self, *args, **options): session = boto3.Session( aws_access_key_id=settings.ATTACHM...
Add a conversion script to turn CSV into Lua table.
# Convert a CSV file to a Lua table script that can be imported using `dofile`. import csv def csv2lua(in_file, out_file, global_name): fp_in = open(in_file, 'r') rows = list(csv.reader(fp_in)) fp_in.close() headers = rows[0] lua_rows = [] for row in rows[1:]: cells = [] print...
Load sub-classes without using explicit names
from pkgutil import iter_modules from pathlib import Path from importlib import import_module from transformations.SentenceTransformation import SentenceTransformation def load(module, class_name): my_class_py = getattr(module, class_name) my_class = getattr(my_class_py, class_name) return my_class() c...
Add 'one script to go' support
#!/usr/bin/env python # # Windows Azure Linux Agent setup.py # # Copyright 2013 Microsoft Corporation # # 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/LI...
Test the pipeline code for genome indexing
""" .. Copyright 2017 EMBL-European Bioinformatics Institute 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 applic...
Use asyncio_mongo for the server
import os import asyncio import logging import tornado.web import tornado.httpserver import tornado.platform.asyncio from tornado.options import define from tornado.options import options import asyncio_mongo from wdim.server.api import v1 logger = logging.getLogger(__name__) define('debug', default=True, help='D...
Set up Code Fights is cool team problem
#!/usr/local/bin/python # Code Fights Is Cool Team Problem class Team(object): def __init__(self, names): self.names = names # TO DO def isCoolTeam(team): return bool(Team(team)) def main(): tests = [ [["Mark", "Kelly", "Kurt", "Terk"], True], [["Lucy"], True], [["...
Add PACKAGE_INFO to devil in Catapult
# Copyright 2016 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. import collections PackageInfo = collections.namedtuple( 'PackageInfo', ['package', 'activity', 'cmdline_file', 'devtools_socket', 'test_package']) ...
Add start of util function that will return current people
from opencivicdata.models.people_orgs import Person def get_current_people(position): if position == 'senator': return Person.objects.filter(memberships__organization__name='Florida Senate') if position == 'representative': return Person.objects.filter(memberships__organization__name='Flori...
Add Tweepy cog and application command group
from discord import app_commands from discord.ext import commands async def setup(bot): await bot.add_cog(Tweepy()) class Tweepy(commands.Cog, app_commands.Group): """Tweepy"""
Add example for creating an image from an array and an affine.
"""Create a nifti image from a numpy array and an affine transform.""" from os import path import numpy as np from neuroimaging.core.api import fromarray, save_image, load_image, \ Affine, CoordinateMap # Imports used just for development and testing. User's typically # would not uses these when creating an im...
Add Prim's algorithm for finding MST
# Prim's algorithm is a greedy algorithm that # finds a minimum spanning tree # for a weighted undirected graph. # # Time complexity: O(m * n) # Input Format: # First line has two integers, denoting the number of nodes in the graph and # denoting the number of edges in the graph. # The next lines each consist of thre...
Fix Python packaging to use correct git log for package time/version stamps (2nd try)
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): ...
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): ...
Fix __all__ usage for sympy/series
"""A module that handles series: find a limit, order the series etc. """ from order import Order from limits import limit, Limit from gruntz import gruntz from series import series O = Order __all__ = [gruntz, limit, series, O, Order, Limit]
"""A module that handles series: find a limit, order the series etc. """ from order import Order from limits import limit, Limit from gruntz import gruntz from series import series O = Order __all__ = ['gruntz', 'limit', 'series', 'O', 'Order', 'Limit']
Add script to make RDF Eidos ontology
import yaml import requests from os.path import join, dirname, abspath from rdflib import Graph, Namespace, Literal eidos_ont_url = 'https://raw.githubusercontent.com/clulab/eidos/master/' + \ 'src/main/resources/org/clulab/wm/eidos/toy_ontology.yml' eidos_ns = Namespace('http://github.com/clulab/eido...
Add William Playfair Wheat and Wages example
""" Wheat and Wages --------------- A recreation of William Playfair's classic chart visualizing the price of wheat, the wages of a mechanic, and the reigning British monarch. """ # category: case studies import altair as alt from vega_datasets import data base_wheat = alt.Chart(data.wheat.url).transform_calculate( ...
Make flake8 happy (long lines)
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
Add class file for linked list and binary tree
""" This file includes several data structures used in LeetCode question. """ # Definition for a list node. class ListNode(object): def __init__(self, n): self.val = n self.next = None def createLinkedList(nodelist): #type nodelist: list[int/float] #rtype: head of linked list linkedList = ListNode(0) head = ...
Add factory for text messages
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import factory from smsgateway.models import SMS class SMSFactory(factory.DjangoModelFactory): FACTORY_FOR = SMS content = 'This is a test' sender = factory.Sequence(lambda n: u"+32476{0:06d}".format(n)) to = factory.Sequence(lambda n:...
Set up mongodb addon to heroku app; created a test python script to connect to db
#!/usr/bin/python # Documentation: http://api.mongodb.org/python/ # A python script connecting to a MongoDB given a MongoDB Connection URI. import sys import pymongo import os ### Create seed data SEED_DATA = [ { 'decade': '1970s', 'artist': 'Debby Boone', 'song': 'You Light Up My Life',...
Add py solution for 543. Diameter of Binary Tree
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def dfs(self, cur): if cur: ldepth = self.dfs(cur.left) rdepth = self.dfs(cur.right) ...
Add one-way migration from core to bookmarks
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('bookmarks', '0004_auto_20160901_2322'), ] operations = [ migrations.RunSQL("DROP TABLE bookmarks_bookmark;"), migrations.RunSQL("ALTER TABLE core_bookmark RENAME TO bookmarks_bookmark;"), ...
Add prototype and incomplete REST interface
import md5, urllib from twisted.internet import defer from twisted.web import client from elementtree import ElementTree class FlickREST: endpoint = "http://api.flickr.com/services/rest/?" def __init__(self, api_key, secret, perms="read"): self.api_key = api_key self.secret = secret ...
Add migration script to register runners
#!/usr/bin/env python # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License...
Add tests for commands module
import json import datetime from simplekv import fs from test.base import ApiTestCase from zou.app.utils import commands def totimestamp(dt, epoch=datetime.datetime(1970, 1, 1)): td = dt - epoch return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 class CommandsTestCase(ApiTestCase):...
Remove tags field from user Model
"""Remove tag table Revision ID: ebcc92fc4d27 Revises: 444c69da7c45 Create Date: 2017-05-08 01:01:48.865909 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ebcc92fc4d27' down_revision = '444c69da7c45' branch_labels = None depends_on = None def upgrade(): ...
Add tests for utils module.
import sys import unittest import pprint from xoinvader.utils import create_logger from xoinvader.utils import InfiniteList from xoinvader.utils import Point class TestUtils(unittest.TestCase): def test_create_logger(self): logger = create_logger("test", "test.log") self.assertTrue(logger) d...
Add a management command that runs a given script taking an input file and an output file as args.
""" Run a script that takes a file input/output. """ import os import sys from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.utils import simplejson as json ...
Add test file use in the docs.
def test_parse_bool(wish): parse_bool = wish assert not parse_bool('false') assert not parse_bool('FALSE') assert not parse_bool('0') assert parse_bool('true') assert parse_bool('TRUE') assert parse_bool('1')
Add fetch data py script
import os import pandas as pd import tensorflow_datasets as tfds # Example use in another file of this directory: # import imdb_fetch_data as full_data # full_data.fetch_data() def fetch_data(): """This downloads the full dataset to pwd/data/imdb.csv""" ds = tfds.load('imdb_reviews', split='train+...
Test qlearning4k result for 2048
from __future__ import print_function import numpy as np import math np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.models import Sequential, model_from_json from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, ...
Add script to find areal units where each category is represented (and test marble)
"""neighbourhoods_categories.py Find the tracts where each category is over-represented or all cities in the dataset. """ import csv import marble as mb # # Import a list of MSA # msa = {} with open('data/names/msa.csv', 'r') as source: reader = csv.reader(source, delimiter='\t') reader.next() for rows i...
Add management command for making outgoing webhook bot.
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from zerver.lib.actions import do_rename_stream from zerver.lib.str_utils import force_text from zerver.models import Realm, Serv...
Add basic tests for rendering_markdown
"""Test functions in markdown utils""" import unittest from unittest import mock from wqflask.markdown_routes import render_markdown class MockRequests404: @property def status_code(): return 404 class MockRequests200: @property def status_code(): return 200 @property def c...
Add example for dicts as Handler structure.
import asyncio import aiozmq import aiozmq.rpc @aiozmq.rpc.method def a(): return 'a' @aiozmq.rpc.method def b(): return 'b' handlers_dict = {'a': a, 'subnamespace': {'b': b} } @asyncio.coroutine def go(): server = yield from aiozmq.rpc.start_server( handlers...
Add tests for no-args default on base class.
import pytest from flexmock import flexmock from .... import base @pytest.fixture def model_with_no_args(): flexmock(base.Model) base.Model.should_receive('_args2kwargs').and_return({}) base.Model.should_receive('_update_defaults').and_return({}) base.Model.should_receive('setup').and_return(None) ...
Create set of thing pv-slices across the disk
''' Create a set of thin PV slices ''' from spectral_cube import SpectralCube, Projection from astropy.io import fits from astropy import units as u import numpy as np from cube_analysis.disk_pvslices import disk_pvslices from paths import fourteenB_HI_data_wGBT_path, fourteenB_wGBT_HI_file_dict from galaxy_params ...
Add super model class via upload
class CWModel(object): def __init__(self, json_dict=None): if json_dict is not None: self.__dict__.update(json_dict) def __repr__(self): string = '' for k, v in self.__dict__.items(): string = ''.join([string, '{}: {}\n'.format(k, v)]) return s...
Update to work with the latest iteration
from __future__ import print_function, division, absolute_import import argparse from argparse import RawDescriptionHelpFormatter import sys from conda.cli import common description = """ Handles interacting with Conda environments. """ example = """ examples: conda env list conda env list --json """ def ...
from __future__ import print_function, division, absolute_import import argparse from argparse import RawDescriptionHelpFormatter import sys from conda.cli import common description = """ Handles interacting with Conda environments. """ example = """ examples: conda env list conda env list --json """ def ...
Add python turtle to DXF converter.
from turtle import Vec2D class Turtle(object): def __init__(self): self.position = Vec2D(0, 0) self.direction = Vec2D(1, 0) self.isDrawing = True def penup(self): self.isDrawing = False def pendown(self): self.isDrawing = True def right(self, angle): s...
Add argparse tests for ceph-deploy config
import pytest from ceph_deploy.cli import get_parser SUBCMDS_WITH_ARGS = ['push', 'pull'] class TestParserConfig(object): def setup(self): self.parser = get_parser() def test_config_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('config --help'.split...
Add empty file stub for pointing math operations.
# Copyright (c) 2015 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. import unittest import numpy as np import healpy as hp import quaternionarray as qa
Print the number of bpm y elements in the machine
import pytac.load_csv import pytac.epics def main(): lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem()) bpms = lattice.get_elements('BPM') bpms_n = 0 try: for bpm in bpms: bpm.get_pv_name('y') bpms_n += 1 print 'There exist {0} BPMy elements i...