Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add negative tempest API test for cluster_delete
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Add api v2 license, add license accessibility attachment
# Generated by Django 3.1.14 on 2022-04-25 09:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0025_auto_20220425_0850'), ] operations = [ migrations.AlterModelOptions( name='lice...
Add solution for problem 36, after long time...
#!/usr/bin/python from math import pow LIMIT = 1000000 palindrome_sum = 0 def is_palindrome(res): return res == res[::-1] def binary(x): res = [] while(x): res.insert(0, x % 2) x //= 2 return res for palindrome in range(1, LIMIT): if(is_palindrome(list(str(palindrome)))): binary_n = binary(palindrome) ...
Add missing migration for User
# Generated by Django 3.2.13 on 2022-06-22 14:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kerrokantasi', '0004_auto_20200225_1349'), ] operations = [ migrations.AlterField( model_name='user', name='first_n...
Add solution to the problem Mini-Max Sum
#!/bin/python3 # https://www.hackerrank.com/challenges/mini-max-sum/problem """ The algorithm used to solve this problem is the following: 1. Get the minimum element of the array 2. Get the maximum element of the array 3. Get the sum of all the elements in the array 4. Calculate the min sum -> sum(arr) - max_element ...
Add simple tests for kernel spec machinery
import json import os from os.path import join as pjoin import unittest from IPython.utils.tempdir import TemporaryDirectory from IPython.kernel import kernelspec sample_kernel_json = {'argv':['cat', '{connection_file}'], 'display_name':'Test kernel', 'language':'bash', ...
Add an example of a long running publisher
# -*- coding: utf-8 -*- # pylint: disable=C0111,C0103,R0205 import threading from time import sleep from pika import ConnectionParameters, BlockingConnection, PlainCredentials class Publisher(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.daemon = Tr...
Add a simple command to generate automatic regressions
import bandicoot as bc from os.path import dirname, abspath, join if __name__ == '__main__': empty_user = bc.User() empty_user.attributes['empty'] = True empty_path = join(dirname(abspath(__file__)), 'samples/empty_user.json') bc.io.to_json(bc.utils.all(empty_user, summary='extended', flatten=True), em...
Add py2app script to todos_app
from distutils.core import setup import sys import os import shutil def tree(src): return [(root, map(lambda f: os.path.join(root, f), filter(lambda f: os.path.splitext(f)[1] != ".map", files))) for (root, dirs, files) in os.walk(os.path.normpath(src))] APP = ['index.py'] DATA_FILES = tree('assets') OPTIONS_OS...
Add OBSolve class and from_json methods
# -*- coding: utf-8 -*- import os import sys import json import qutip as qu from maxwellbloch import ob_atom # Main class OBSolve(object): """docstring for OBSolve""" def __init__(self, ob_atom={}, t_min=0.0, t_max=1.0, t_steps=100, method='mesolve', opts={}): self.build_ob...
Add python script to print Linux information.
#!/usr/bin/env python # # Print information about the current computer. # import os import re from socket import gethostname from platform import linux_distribution def gethost(): '''Extract host name''' try: return gethostname() except: return "NA" def processor(): '''Extract first pr...
Add database dump convert tool.
from sys import argv from xml.dom.minidom import parse from base64 import b64decode def Escape(text): text = text.replace('\\', '\\\\') for sample, replace in {'\'': '\\\'', '"': '\\"', '\n': '\\n', '\r': '\\r', '\x00': '\\0', '\x1a': '\\Z'}.iteritems(): text = text.replace(sample, replace); return text if len(...
Add a tool to convert hdf5 to bigfile.
import h5py import bigfile import logging import argparse ap = argparse.ArgumentParser('h5tobigfile') ap.add_argument("hdf5") ap.add_argument("bigfile") ap.add_argument("--verify", action='store_true', default=False) ap.add_argument("--include", action="append") ap.add_argument("--exclude", action="append") def trave...
Add django command for updating ERF areas
import os import argparse from django.core.management.base import BaseCommand from firecares.firestation.models import FireDepartment from firecares.tasks.update import update_parcel_department_effectivefirefighting_rollup class Command(BaseCommand): help = """Updates the Effective Response Force (ERF) areas for t...
Add missing migration needed to support Variable value encryption
"""add is_encrypted column to variable table Revision ID: 1968acfc09e3 Revises: bba5a7cfc896 Create Date: 2016-02-02 17:20:55.692295 """ # revision identifiers, used by Alembic. revision = '1968acfc09e3' down_revision = 'bba5a7cfc896' branch_labels = None depends_on = None from alembic import op import sqlalchemy a...
Add example on subclassing commands.Context
import random import discord from discord.ext import commands class MyContext(commands.Context): async def tick(self, value): # reacts to the message with an emoji # depending on whether value is True or False # if its True, it'll add a green check mark # otherwise, it'll add a re...
Add functions to test LIF IO
import os from lesion import lifio from numpy.testing.decorators import skipif from numpy.testing import assert_equal, assert_allclose currdir = os.path.abspath(os.path.dirname(__file__)) test_lif = os.path.join(currdir, 'mouse-kidney.lif') test_lif_unavailable = not os.path.isfile(test_lif) @skipif(test_lif_unavai...
Check that mideu package config exists (assumes that home and current dir do not have config present)
from __future__ import absolute_import import unittest import os from mciutil.cli.common import get_config_filename class CliCommonTests(unittest.TestCase): def test_get_config_filename(self): """ check that package default config exists, otherwise fail this will show up on remote build w...
Write a simple adapter in functest project to run TESTON JIRA:FUNCTEST-46
""" Description: This file include basis functions lanqinglong@huawei.com """ import logging import os import time class foundation: def __init__(self): self.dir = os.path.join( os.getcwd(), 'log' ) def log (self, loginfo): """ Record log in log directory for deploying test e...
Add test for empty LogEndogTransformer
# -*- coding: utf-8 -*- import numpy as np from numpy.testing import assert_array_almost_equal from scipy import stats import pytest from pmdarima.preprocessing import LogEndogTransformer from pmdarima.preprocessing import BoxCoxEndogTransformer def test_same(): y = [1, 2, 3] trans = BoxCoxEndogTransformer()...
Add script to make the .num.txt.gz file from the fastq
import gzip from sys import argv if __name__ == "__main__": fastq = gzip.open(argv[1], 'rt') base, _ = argv[1].rsplit('.remap', 1) num = gzip.open(base+'.to.remap.num.gz', 'wt') line = next(fastq) last = '' while line: curr, counts = line.strip().rsplit(':', 1) if curr != last: ...
Implement the quick sort algorithm.
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Quick Sort. It is an application of divide and conquer strategy. Best, Average: O(nlogn), Worst: O(n^2). ''' def partion(array, left, right, pivot, order): p = left pv = array[pivot] array[right], array[pivot] = array[pivot], array[right] if order...
Test for problems in hash.
# ***************************************************************************** # Copyright 2019 Karl Einar Nelson # # 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...
Test for the rentals list
from django.contrib.auth.models import User from depot.models import Depot, Organization from rental.models import Rental from verleihtool.test import ClientTestCase from datetime import datetime class RentalsTestCase(ClientTestCase): def create_rental(self, depot, firstname, lastname, state): return Ren...
Add test stub module for backend tools
import unittest from pymanopt.tools import flatten_arguments class TestArgumentFlattening(unittest.TestCase): def _test_flatten_arguments( self, arguments, correctly_flattened_arguments): flattened_arguments = flatten_arguments(arguments) self.assertEqual(flattened_arguments, correctl...
Create the package with metadatas
"""CKEditor for Django-blog-zinnia""" __version__ = '1.0' __license__ = 'BSD License' __author__ = 'Fantomas42' __email__ = 'fantomas42@gmail.com' __url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-ckeditor'
Add module to retrieve disk space
#!/usr/bin/env python """ Return disk usage statistics about the given path as a (total, used, free) namedtuple. Values are expressed in bytes. """ # Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com> # License: MIT import os import collections _ntuple_diskusage = collections.namedtuple('usage', 'total used ...
Add basic framework for LDA
import sys import logging from os.path import isdir, isfile from gensim import models from corpus import Corpus logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) class LDACorpus(Corpus): def __init__(self, dict_loc, vec_loc, no_topics=100, update=1, chunksize=10000, pass...
Convert hdx_portal to a boolean value
try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config is_hdx = config.get('hdx_portal') if is_hdx: from ckanext.hdx_search.controllers.search_controller import HDXSearchController as PackageController else: from ckan.contr...
try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config from paste.deploy.converters import asbool is_hdx = asbool(config.get('hdx_portal', False)) if is_hdx: from ckanext.hdx_search.controllers.search_controller\ impor...
Add test with live database, disabled by default such that all test complete when using master
# from unittest import TestCase # from elasticsearch import Elasticsearch # from query import Match, Range # # # def get_docs(ret): # return ret['hits']['hits'] # # # class TestLive(TestCase): # es = None # # @staticmethod # def query(query): # return TestLive.es.search('test_index', 'test_doc',...
Add basic test for OTPS code
from stompy.model.otps import read_otps import six six.moves.reload_module(read_otps) modfile="data/DATA/Model_OR1km" def test_read_otps(): times=np.arange( np.datetime64('2010-01-01 00:00'), np.datetime64('2010-01-10 00:00'), np.timedelta64(15,'m') ) pred_h,pred_u,...
Add tests for SCP operations.
import unittest from jarn.mkrelease.scp import SCP class HasHostTests(unittest.TestCase): def test_simple(self): scp = SCP() self.assertEqual(scp.has_host('foo:bar'), True) def test_slash(self): scp = SCP() self.assertEqual(scp.has_host('foo:bar/baz'), True) def test_no...
Add Anytown Maps utils library
"""Functions to retrieve images for the maps.""" def _retrieve_google_maps_image_url(coords, zoom_level): lat, lng = coords return ( 'http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom={2}' '&scale=false&size=600x300&maptype=roadmap&format=png' '&markers=size:small%7Ccol...
Add a (user_id, role_id) index to dcc_role_users table.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('django_comment_common', '0007_discussionsidmapping'), ] operations = [ migrations.RunSQL( 'CREATE INDEX dcc_role_users_u...
Add management command to identify stale custom modules
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import csv from collections import defaultdict from django.apps import apps from django.core.management import BaseCommand from django.conf import settings from importlib import import_module from cor...
Add test that spawns of primitive generators produce the same elements as the original
import pytest from .exemplar_generators import EXEMPLAR_PRIMITIVE_GENERATORS @pytest.mark.parametrize("g", EXEMPLAR_PRIMITIVE_GENERATORS) def test_spawn_primitive_generators(g): """ Test that primitive generators can be spawned and the spawned versions produce the same elements. """ num_items = 50 ...
Add a test for general object behavior as it seems to be changed by python 3 patch
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import pycurl import unittest import sys class PycurlObjectTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_set_attribute(self): assert not h...
Add a class for getting meta info from a songlist
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import re import requests from lxml import html class Songlist(object): def __init__(self, url): self.url = url response = requests.get(url) self.tree = html.fromstring(response.text) def _get_num...
Add test case for tinyMCE (WYSIWYG editor).
from . import TheInternetTestCase from helium.api import click, Text, press, CONTROL, COMMAND, write from sys import platform class WYSIWYGEditorTest(TheInternetTestCase): def get_page(self): return "http://the-internet.herokuapp.com/tinymce" def test_use_wysiwyg_editor(self): self.assertTrue(Text("Your content ...
Tag using alchemy api. As request by costaclayton
import copy import requests from urllib import quote_plus from optparse import OptionParser from pocketpy.auth import auth from pocketpy.pocket import retrieve KEYWORD_URL = "http://access.alchemyapi.com/calls/url/URLGetRankedKeywords" def get_keywords_from_alchemy(access_token, item_url): params = {"url": ite...
Implement a test to make sure output_dir is passed along to generate_files
# -*- coding: utf-8 -*- import pytest from cookiecutter import main @pytest.fixture def context(): """Fixture to return a valid context as known from a cookiecutter.json.""" return { u'cookiecutter': { u'email': u'raphael@hackebrot.de', u'full_name': u'Raphael Pierzina', ...
Add unit tests for cli.task
""" Copyright (c) 2021 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import flexmock from atomic_reactor.cli import task from atomic_reactor.tasks import orchestrator, worker, sources, common TASK_ARGS = { ...
Write a test for the command line tool
import pytest import sys import binascii import base64 from unittest import mock from io import StringIO, BytesIO, TextIOWrapper import cbor2.tool def test_stdin(monkeypatch, tmpdir): f = tmpdir.join('outfile') argv = ['-o', str(f)] inbuf = TextIOWrapper(BytesIO(binascii.unhexlify('02'))) with monkey...
Delete obsolete Whois model from the datastore.
#!/usr/bin/env python import os import sys import time import getpass import datetime from common.appenginepatch.aecmd import setup_env setup_env() import ADNS from adns import rr from google.appengine.ext import db from google.appengine.ext.remote_api import remote_api_stub from google.appengine.api.datastore_erro...
Create a pip installable project
from distutils.core import setup setup( name='python-evrythng', version='0.1', packages=['evrythng', 'evrythng.entities'], package_dir={'': 'src'}, url='https://github.com/GooeeIOT/python-evrythng', license='MIT', author='Lyle Scott, III', author_email='lyle@digitalfoo.net', descrip...
Add message format conversion utility script
import json import argparse import heapq import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from src.model.message import Message from datetime import datetime from collections import namedtuple # For storing messages in an object that the heap can sort MessageTuple = namedtuple('Messa...
Add tests for new CA post api
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests for PUT and POST requests for objects with custom attributes These tests include: - Creating an object with custom attributes (POST request). - Editing existing custom attributes on an object. - Ad...
Add some tests for the LineReader class
import glob from mrs.fileformats import LineReader import sys try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO PY3 = sys.version_info[0] == 3 def test_dickens(): with open('tests/data/dickens/split1.txt', 'rb') as f: reader = LineReader(f) lines =...
Add tests for '/' and '/status'
# coding: utf-8 # Copyright (c) 2001-2019, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to...
Add implementation of RANSAC algorithm
import numpy as np def ransac(X, y, estimator_cls, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_n_inliers=np.inf, stop_score=1, estimator_kwargs={}): """Fit a model to data with the RANSAC (random sample consensus) algorithm. """ be...
Solve Code Fights find email domain problem
#!/usr/local/bin/python # Code Fights Find Email Domain Problem def findEmailDomain(address): index = max([i for i, char in enumerate(address) if char == "@"]) return address[index + 1:] def main(): tests = [ ["prettyandsimple@example.com", "example.com"], ["<>[]:,;@\"!#$%&*+-/=?^_{}| ~....
Add iTunes script for making year playlists
#!/usr/bin/env python3 from collections import defaultdict from dateutil.parser import parse from pathlib import Path import xml.etree.ElementTree as ET LIBRARY = Path.home() / "Music/iTunes/iTunes Library.xml" def plist_iter(iterable, all_dicts=False): a = iter(iterable) for k, v in zip(a, a): asse...
Add tool to detect multiple use of a negative unit
# JN 2016-04-08 """ First read do_sort_neg.txt, CheetahLogFile_*.csv, and channel_names.csv. Then check if any channel in do_sort_neg.txt are using the same reference. Warning: This assumes that all channels have been renamed to the CSCxy.ncs format """ from __future__ import print_function, division, absolute_imp...
Add script demonstrating preparing PCA parameters computed by train_pca.py
import cPickle as pkl import base64 import numpy as np from lopq.model import eigenvalue_allocation def main(args): params = pkl.load(open(args.pca_params)) P = params['P'] E = params['E'] mu = params['mu'] # Reduce dimension E = E[-args.D:] P = P[:,-args.D:] # Balance variance acro...
Add tests for fuzzy ranking adjustments.
from __future__ import unicode_literals import pytest from prompt_toolkit.completion import Completion from prompt_toolkit.document import Document @pytest.fixture def completer(): import pgcli.pgcompleter as pgcompleter return pgcompleter.PGCompleter() def test_ranking_ignores_identifier_quotes(completer):...
Add venv利用時のsys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix の値の違いについてのサンプル追加
""" sys モジュールについてのサンプルです. venv 環境での - sys.prefix - sys.exec_prefix - sys.base_prefix - sys.base_exec_prefix の値について. REFERENCES:: http://bit.ly/2Vun6U9 http://bit.ly/2Vuvqn6 """ import sys from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr, hr class Sam...
Create script to convert from old FAST{A,Q} name format to new one (as of Casava 1.8).
#!/usr/bin/env python import functools import re import argparse from khmer import ReadParser resub_read_1 = functools.partial( re.sub, r"^(.*)/1$", r"\1 1:N:0:NNNNN" ) resub_read_2 = functools.partial( re.sub, r"^(.*)/2$", r"\1 2:N:0:NNNNN" ) def setup_cl_parser( ): parser = \ argparse.ArgumentParser...
Add unit tests for latex output
""" unit tests of the latex writer """ import unittest import subprocess import tempfile import os import sys import BeautifulSoup from pyth.plugins.latex.writer import LatexWriter from pyth.plugins.python.reader import * class TestWriteLatex(unittest.TestCase): def test_basic(self): """ Try to...
Add in setup application file to handle the app setup so that it can be used with browser testing as well
from flask import Flask, g from inspect import getmembers, isfunction from happymongo import HapPyMongo from config import config from adminbp import bp as admin_bp from manage_globals import bp as manage_bp from engine import bp as engine_bp import context_functions import views import template_filters def create_...
Remove redirect_invalid_to option and use settings.LOGIN_URL instead. When redirect the user, also forward the next parameter.
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='te...
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='te...
Add drop hints script from Noto
#!/usr/bin/env python3 # # Copyright 2014 Google Inc. All rights reserved. # Copyright 2021 The Google Font Tools Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
Add tests for rest api
from rest_framework.test import APITestCase def has(d, key): if d.get(key) is not None: return True else: return False class TestApi(APITestCase): def test_root(self): """Test api root URL is accessible""" request = self.client.get('/api/', format='json') self.as...
Add management command to generate SQL constraints for SHARE versioning
from django.apps import apps from django.core.management.base import BaseCommand from django.db.migrations import Migration from django.db.migrations import operations from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader from django.db.migrations.st...
Add script to assist in packaging.
"""This tool sets up a distribution of the software by automating several tasks that need to be done. The directory should be in pristine condition when this is run (i.e., devoid of files that need to be removed before packaging begins). It is best to run this on a fresh check out of the repository.""" import os impo...
Add ExceptionLoggingMiddleware: Useful for debugging.
class ExceptionLoggingMiddleware(object): """ Small middleware that logs exceptions to the console. Useful in local development. """ def process_exception(self, request, exception): import traceback print traceback.format_exc()
Add a little script to register a list of pods
#!/bin/env python ## Utils script to call a list of pods import subprocess pods = open('/tmp/pods.txt', 'r') for pod in pods: print pod.strip('\n\r') subprocess.call('wget http://pods.jasonrobinson.me/register/'+pod.strip('\n\r')+' -O /dev/null', shell=True)
Add Point class based on GEOS package
class Point(object): def __init__(self, x, y=None): """ The Point object may be initialized with either a tuple, or individual parameters. For Example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple """ if isinstance(x, (tuple, list)): #...
Add initial tests for ccm cli
from . import TEST_DIR from . import ccmtest from ccmlib.cluster import Cluster import subprocess from six import print_ CLUSTER_PATH = TEST_DIR class TestCCMCmd(ccmtest.Tester): def __init__(self, *args, **kwargs): ccmtest.Tester.__init__(self, *args, **kwargs) class TestCCMCreate(TestCCMCmd): de...
Add test case for geolocation.
from . import TheInternetTestCase from helium.api import click, get_driver, S class AbTestingTest(TheInternetTestCase): def get_page(self): return "http://the-internet.herokuapp.com/geolocation" def test_fake_geolocation(self): get_driver().execute_script( 'window.navigator.geolocation.getCurrentPosition = ' ...
Add plot for trial durations, needs more work!
import climate import collections import lmj.plot import numpy as np import database import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), ) def main(root, pattern='*.csv.gz'): data = collections.defaultdict(lamb...
Add a python script to generate the many-images.yaml benchmark.
# 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/. SIZE = 8 with open("../benchmarks/many-images.yaml", "w") as text_file: text_file.write("root:\n") text_file.wr...
Add trace config for pox l2_learning switch
from config.experiment_config_lib import ControllerConfig from sts.topology import StarTopology, BufferedPatchPanel, MeshTopology, GridTopology, BinaryLeafTreeTopology from sts.controller_manager import UserSpaceControllerPatchPanel from sts.control_flow.fuzzer import Fuzzer from sts.control_flow.interactive import Int...
Add unittest for creation of tips
from twisted.internet.defer import inlineCallbacks from twisted.trial import unittest from globaleaks.settings import transact from globaleaks.jobs import delivery_sched from globaleaks.tests import helpers from globaleaks.handlers.receiver import get_receiver_tip_list from globaleaks.handlers.submission import final...
Add a quicky Abbyy recogniser node. Doesn't seem to work yet, but can't be sure 'cos our license has run out of pages...
""" Cuneiform Recogniser """ from nodetree import node, manager from ocradmin import plugins from ocradmin.plugins import stages, generic_nodes import types import os import shutil import tempfile import subprocess as sp NAME = "Abbyy" class AbbyyRecognizerNode(generic_nodes.CommandLineRecognizerNode): """ ...
Add a function to say whether or not chef is the current host.
#!/usr/bin/env python2 def is_this_chef(): from socket import gethostname return gethostname() == 'chef.compbio.ucsf.edu' def require_chef(): if not is_this_chef(): raise SystemExit("This script must be run on chef.")
Implement h264 and png as ext hooks
import os from . import hooks from .viewport import playblast def default_handler(data, options): _, ext = os.path.splitext(data['filename']) is_qt = ext == '.mov' kwargs = dict( camera=data['camera'], state=data['state'], width=data['width'], height=data['height'], )...
Add functions for reading MNIST dataset int numpy arrays.
# this file defines function for parsing the MNIST dataset as available to # download here: # http://yann.lecun.com/exdb/mnist/index.html # The extracted files are expected to reside in a subfolder called Data/MNIST/ import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import os ...
Add a warning things have been moved back.
raise DeprecationWarning("""DEPRECATED: After Popular request and decision from the BDFL: `IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell` during the beta cycle (after IPython 5.0.beta3) Sorry about that. This file will be removed in 5.0 rc or final. """)
Fix missing quoting module for schema.
## # Copyright (c) 2016 MagicStack Inc. # All rights reserved. # # See LICENSE for details. ## import re from .parser.grammar import keywords _re_ident = re.compile(r'(?:[^\W\d]|\$)(?:\w|\$)*') def quote_literal(text): return "'" + text.replace("'", R"\'") + "'" def dollar_quote_literal(text): quote = ...
Add a short script for plotting successive trials.
import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) ax = lmj.plot.axes(111, projection='3d', aspect='equal') for i, block in enumerate(subj.blocks): trial = block.trials[0] trial.load() x, y, z = trial.marker('r-fing-index') ax.plo...
Add trivial pricing handler - Product/Variant field getter
from django.db.models import Min, Max from ...pricing import Price class FieldGetter(object): def __init__(self, field_name='price', currency=None): self.currency = currency self.field_name = field_name class ProductFieldGetter(FieldGetter): def get_variant_price(self, variant, currency, quan...
Add unit test for packager.core.flavor.py
#! /usr/bin/python from packager.core.flavor import debian_check from nose.tools import * from subprocess import call def test_debian_check(): ret = call(["test", "-f", "/etc/debian_version"]) == 0 assert debian_check() == ret
Add tests for permutation group class
"""Tests for the permutation group class.""" import pickle from drudge import Perm, Group def test_s3_group_correct_and_serializable(): """Test the S3 group. Since the permutation group objects are mostly opaque, here it is tested by its new arguments, which is also further verified to work with pickle...
Add project for chapter 6 Automate the Boring Stuff
#!/urs/local/bin/python # pw.py - an insecure password locker program import sys import pyperclip PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345'} if len(sys.argv) < 2: print('Usage: python pw.py [account] - copy acco...
Add tool for creating a separate backoff node for inword positions
#!/usr/bin/env python3 import argparse import sys def main(inf, outf, word_map): iw_backoff_outgoing = [] iw_backoff_incoming = [] iw_ending_nodes = set() max_node = 0 for line in inf: parts = line.strip("\n").split("\t") if len(parts) < 3: print("\t".join(parts...
Correct some issues with the stats methods
from django.template.defaultfilters import slugify from debug_toolbar.middleware import DebugToolbarMiddleware class DebugPanel(object): """ Base class for debug panels. """ # name = Base has_content = False # If content returns something, set to true in subclass # We'll maintain a local ...
from django.template.defaultfilters import slugify from debug_toolbar.middleware import DebugToolbarMiddleware class DebugPanel(object): """ Base class for debug panels. """ # name = Base has_content = False # If content returns something, set to true in subclass # We'll maintain a local ...
Add 02-task sample test v2.
import unittest import solution as s class SampleTest(unittest.TestCase): def test_five_plus_three(self): plus = s.create_operator('+', lambda lhs, rhs: lhs + rhs) x = s.create_variable('x') y = s.create_variable('y') added_expression = s.create_expression((x, plus, y)) sel...
Add test cases for zipping galleries
# -*- coding:utf-8 -*- import os import glob import zipfile from sigal.gallery import Gallery from sigal.settings import read_settings CURRENT_DIR = os.path.dirname(__file__) SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample') SAMPLE_SOURCE = os.path.join(SAMPLE_DIR, 'pictures', 'dir1') def make_gallery(**kwargs): ...
Fix bug with updated auth backend
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: ...
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: ...
Add simple tests for shub deploy
#!/usr/bin/env python # coding=utf-8 import unittest from shub import deploy from click.testing import CliRunner from mock import Mock class DeployTest(unittest.TestCase): def setUp(self): self.runner = CliRunner() def test_fails_when_deploy_is_invoked_outside_of_a_scrapy_project(self): # g...
Add mgmt cmd to generate anonymized ID mapping
import csv import sys from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from student.models import unique_id_for_user class Command(BaseCommand): # It appears that with the way Rake invokes these commands, we can't # have more than one arg passed th...
Add validation test for adding node label
import pytest from .common import * # NOQA def test_add_node_label(): client, cluster = get_global_admin_client_and_cluster() test_label = "foo" nodes = client.list_node(clusterId=cluster.id) assert len(nodes.data) > 0 node_id = nodes.data[0].id node = client.by_id_node(node_id) # Make s...
Add script to transform CT result to trace list
import csv import sys def csv_to_traces(infile, outfile): traces = [] with open(infile) as inf: results = csv.DictReader(inf) for r in results: for t in r['trace'].split(','): traces.append(t) with open(outfile, 'w') as outf: for trace in traces: outf.write(trace + '\n') def mai...
Attach LTOP as the attribute and remove index
def handle_ltop_links(dmrs_xml): ''' Remove LTOP links from DMRS and add LTOP attribute to the DMRS entity :param dmrs_xml: Input DMRS XML :return: Modified DMRS XML ''' ltop = '-1' links_to_remove = list() for entity in dmrs_xml: if entity.tag == 'link': link = en...
Add py solution for 521. Longest Uncommon Subsequence I
class Solution(object): def findLUSlength(self, a, b): """ :type a: str :type b: str :rtype: int """ if a == b: return -1 else: return max(len(a), len(b))
Add Raspberry PI Alexa control server
from flask import Flask from flask_ask import Ask, statement, convert_errors import logging from rfsend import rf_send GPIO.setmode(GPIO.BCM) app = Flask(__name__) ask = Ask(app, '/') logging.getLogger("flask_ask").setLevel(logging.DEBUG) @ask.intent('LocationControlIntent', mapping={'status': 'status', 'location':...
Add a binary to convert model to tflite supported foramt.
# Copyright 2019 The TensorFlow Authors. 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 by applica...
Add line position to TSV file.
#!/usr/bin/env python import csv from itertools import tee import nltk MATCH_FILE = 'data/6705bigrams-PopewDryden.txt' OUTPUT_FILE = 'data/6705bigrams-Output.txt' def tokenize(text): """This handles tokenizing and normalizing everything.""" return [ token.lower() for token in nltk.wordpun...
Add template loader for clients
from django.template.loader import BaseLoader from django.db import connection from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils._os import safe_join from django.template.base import TemplateDoesNotExist class TenantTemplateLoader(BaseLoader): is_usable = T...
Update SNS per 2019-11-21 changes
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), ...
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), ...