Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add example model of Steiner Triple Systems
# Steiner Triple Systems # The ternary Steiner problem of order n consists of finding a set of n(n-1)/6 # triples of distinct integer elements in {1,...,n} such that any two triples # have at most one common element. It is a hypergraph problem coming from # combinatorial mathematics where n modulo 6 has to be equ...
Add heatmap with working ish pseudocode
import plotly as py import plotly.graph_objs as go import datetime from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) h = 12 w = len(raw_data) start_time = 3 grid = [[0] * w for i in range(0, h)] #def datetime_to_coords(dt): # x = 0 # temp # y = round((dt.h...
Add Python function to build phylo.xml from MSA with Biopython
"""Generate a phylo.xml from a MUSCLE MSA.fasta""" import argparse ##### PARSE ARGUMENTS ##### argparser = argparse.ArgumentParser() argparser.add_argument("msa", help="path to the MUSCLE MSA.fasta") argparser.add_argument("phyloxml", help="path to an output phylo.xml") args = argparser.parse_args() args = vars(arg...
Add script to find removables from PubChem
"""This script helps identify entries in PubChem.tsv that systematically lead to incorrect groundings and should therefore be removed.""" import os import re from indra.databases import chebi_client if __name__ == '__main__': # Basic positioning here = os.path.dirname(os.path.abspath(__file__)) kb_dir = o...
Add migration file for samples app
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-26 20:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('samples', '0012_auto_20170512_1138'), ] operations =...
Add a test for the validate-collated script
# -*- coding: utf-8 -*- # ### # Copyright (c) 2016, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import mimetypes import os.path import tempfile import unittest try: from unittest import mock except ...
Add data migration to deduplicate users
""" deduplicate users Revision ID: c519ecaf1fa6 Revises: a6ff4a27b063 Create Date: 2018-09-26 16:45:13.810694 """ # from alembic import op import sqlalchemy as sa # Revision identifiers, used by Alembic. revision = 'c519ecaf1fa6' down_revision = 'a6ff4a27b063' branch_labels = None depends_on = None def upgrade():...
Add an unit test for vim.py
# -*- coding: utf-8 -*- import unittest from code2html.vim import vim_command class VimCommandTest(unittest.TestCase): def test_vim_command(self): vimrc_file = '/tmp/temporary-vimrc' expected = 'vim -u /tmp/temporary-vimrc -c TOhtml -c wqa' self.assertEqual(expected, ' '.join(vim_command...
Add tests to validate vendor tornado usage
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import, unicode_literals import os import re import logging # Import Salt Testing libs from tests.support.unit import TestCase, skipIf from tests.support.runtests import RUNTIME_VARS # Import Salt libs import salt.modules.cmdmod import salt...
Add failing test for desired behavior
from django.test import override_settings from corehq import privileges from corehq.apps.accounting.models import SoftwarePlanEdition from corehq.apps.accounting.tests.base_tests import BaseAccountingTest from corehq.apps.accounting.tests.utils import DomainSubscriptionMixin from corehq.apps.accounting.utils import do...
Add custom dm upload script to be used by the android framework
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Upload DM output PNG files and JSON summary to Google Storage.""" import datetime import os import shutil import sys import tempfi...
Add a file to extract error strings
from __future__ import with_statement import os, sys, tempfile, subprocess, re __all__ = ["has_error", "get_error_line_number", "make_reg_string", "get_coq_output"] DEFAULT_ERROR_REG_STRING = 'File "[^"]+", line ([0-9]+), characters [0-9-]+:\n([^\n]+)' DEFAULT_ERROR_REG_STRING_GENERIC = 'File "[^"]+", line ([0-9]+), ...
Add test which checks for growing memory usage for block funcs
import lz4.block import pytest test_data = [ (b'a' * 1024 * 1024), ] @pytest.fixture( params=test_data, ids=[ 'data' + str(i) for i in range(len(test_data)) ] ) def data(request): return request.param def test_block_decompress_mem_usage(data): tracemalloc = pytest.importorskip('tra...
Add Python script for running VGG_Face demo.
# Xiang Xiang (eglxiang@gmail.com), March 2016, MIT license. import numpy as np import cv2 import caffe import time img = caffe.io.load_image( "ak.png" ) img = img[:,:,::-1]*255.0 # convert RGB->BGR avg = np.array([129.1863,104.7624,93.5940]) img = img - avg # subtract mean (numpy takes care of dimensions :) img = ...
Write test for reduced framerate.
try: from unittest import mock except ImportError: import mock from sensor_msgs.msg import Image from reduce_framerate import FramerateReducer def test_callback(): r = FramerateReducer() with mock.patch.object(r, "image_publisher", autospec=True) as mock_pub: for i in range(16): ...
Test suggestions for missing activity
from indra.statements import * from bioagents.mra.model_diagnoser import ModelDiagnoser drug = Agent('PLX4720') raf = Agent('RAF') mek = Agent('MEK') erk = Agent('ERK') def test_missing_activity1(): stmts = [Activation(raf, mek), Phosphorylation(mek, erk)] md = ModelDiagnoser(stmts) suggs = md.get_missing...
Add script to print results.
from __future__ import division import argparse import h5py def main(): parser = argparse.ArgumentParser() parser.add_argument('results_hdf5_fname', type=str) parser.add_argument('dset_keys', nargs='*', type=str, default=[]) args = parser.parse_args() f = h5py.File(args.results_hdf5_fname, 'r') ...
Add conf file for Canope Guyane with Moodle and Etherpad card
from .idb import * # pragma: no flakes CUSTOM_CARDS = [ { # Must be one of create, discover, info, learn, manage, read 'category': 'create', 'url': 'http://etherpad.ideasbox.lan', 'title': 'Etherpad', 'description': 'A collaborative text editor', # The name of a Fon...
Add some ugly code to make pretty and more efficient
def pretty_function(string_to_count): raise NotImplementedError() def Ugly_Function(string_to_count): Cpy_Of_String = str(string_to_count) Result = {}#holds result for c in Cpy_Of_String: if (c in Result.keys()) == False: Result[c] = [c] elif (c in Result.k...
Add kernel construction based on kernels
"Functions to create kernels from already existing kernels." import numpy as np def normalize(kernel, *args, **kwargs): """Return the normalized version. This correspond to the new kernel .. math:: K(x_1, x_2) = \frac{kernel(x_1, x2)}\ {sqrt(kernel(x_1, x_1) kernel(x_2, x_2))}...
Add support for MySQL-Connector python driver.
try: import mysql.connector as mysql_connector except ImportError: mysql_connector = None from peewee import ImproperlyConfigured from peewee import MySQLDatabase class MySQLConnectorDatabase(MySQLDatabase): def _connect(self): if mysql_connector is None: raise ImproperlyConfigured('M...
Add python script to diplay webcam video stream
import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break
Add alembic migration script for dark theme
"""Add dark_theme entry Revision ID: 3b85eb7c4d7 Revises: 3d4136d1ae1 Create Date: 2015-08-06 03:34:32.888608 """ # revision identifiers, used by Alembic. revision = '3b85eb7c4d7' down_revision = '3d4136d1ae1' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('user', Column('dark_the...
Add function to read 3d direct access Fortran binary files into NumPy arrays.
#!/usr/bin/python #Author: Scott T. Salesky #Created: 12.6.2014 #Purpose: Collection of functions, routines to use #Python for scientific work #----------------------------------------------
Add tests for new shortcuts.
from nose.tools import * from lctools.shortcuts import get_node_or_fail class TestShortCuts(object): def setup(self): class MyNode(object): def __init__(self, id): self.id = id class MyConn(object): def __init__(self, nodes): self.nodes =...
Add a unit test for CDN-downloads
import unittest import os from io import BytesIO from random import randint from hashlib import sha256 from telethon import TelegramClient # Fill in your api_id and api_hash when running the tests # and REMOVE THEM once you've finished testing them. api_id = None api_hash = None if not api_id or not api_hash: rai...
Add diagnostic comparing aviationweather.gov to IEM
""" Compare our PIREPs data against what is at aviation wx JSON service """ import json import urllib2 import datetime import psycopg2 pgconn = psycopg2.connect(database='postgis', user='nobody', host='iemdb') cursor = pgconn.cursor() avwx = urllib2.urlopen("http://aviationweather.gov/gis/scripts/AirepJSON.php") av...
Add a proof of concept for reading and writing from github api
from hammock import Hammock as Github import json import base64 from pprint import pprint # Let's create the first chain of hammock using base api url github = Github('https://api.github.com') user = 'holtzermann17' # In the future this will be running on a server # somewhere, so password can just be hard coded passw...
Add ida script to convert ida anim to python anim
from collections import namedtuple from struct import unpack import sark ImagePosition = namedtuple('ImagePosition', 'spritesheet image_number y collide x') def hex_to_sign(value): if value >= 0x8000: value -= 0x10000 return value def byte_to_sign(value): if value >= 0x80: value -= 0x...
Add unit support for spacers
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (ca...
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * from styles import adjustUnits def parseRaw(data): """Parse and process a simple DSL to handle creation of f...
Move original to this folder
from exchanges import helpers from exchanges import bitfinex from exchanges import bitstamp from exchanges import okcoin from exchanges import cex from exchanges import btce from time import sleep from datetime import datetime import csv # PREPARE OUTPUT FILE # tell computer where to put CSV filename = datetime.now(...
Make powerline autodoc add all Segments
# vim:fileencoding=utf-8:noet from sphinx.ext import autodoc from inspect import formatargspec from powerline.lint.inspect import getconfigargspec from powerline.lib.threaded import ThreadedSegment try: from __builtin__ import unicode except ImportError: unicode = lambda s, enc: s # NOQA def formatvalue(val): if...
# vim:fileencoding=utf-8:noet from sphinx.ext import autodoc from inspect import formatargspec from powerline.lint.inspect import getconfigargspec from powerline.segments import Segment try: from __builtin__ import unicode except ImportError: unicode = lambda s, enc: s # NOQA def formatvalue(val): if type(val) i...
Change to use `featx` in package
__all__ = [] from lib.exp.featx.base import Featx from lib.exp.tools.slider import Slider class SlideFeatx(Featx, Slider): def __init__(self, root, name): Featx.__init__(self, root, name) Slider.__init__(self, root, name) def get_feats(self): imgl = self.get_slides(None, gray=True, r...
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.prepare import Prepare class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self...
Add base class for KQueen UI views
from flask import flash, session from flask.views import View from kqueen_ui.api import get_kqueen_client, get_service_client import logging logger = logging.getLogger(__name__) class KQueenView(View): """ KQueen UI base view with methods to handle backend API calls. """ def _get_kqueen_client(self)...
Check we are using LDA correctly
import gensim import gensim.matutils import logging import sys import numpy import sklearn.feature_extraction.text as text import scipy.sparse from exp.util.PorterTokeniser import PorterTokeniser from gensim.models.ldamodel import LdaModel from exp.util.SparseUtils import SparseUtils from apgl.data.Standardiser im...
Add tests for prefix Q expression
from unittest import TestCase from django.db.models import Q from binder.views import prefix_q_expression from binder.permissions.views import is_q_child_equal from .testapp.models import Animal class TestPrefixQExpression(TestCase): def test_simple_prefix(self): self.assertTrue(is_q_child_equal( prefix_q_e...
Test tourney match comments retrieval as JSON
""" :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.services.tourney import match_comment_service, match_service def test_view_for_match_as_json(api_client, api_client_authz_header, match, comment): url = f'/api/tourney/matches/{match.id}...
Add py solution for 452. Minimum Number of Arrows to Burst Balloons
from operator import itemgetter class Solution(object): def findMinArrowShots(self, points): """ :type points: List[List[int]] :rtype: int """ points.sort(key=itemgetter(1)) end = None ans = 0 for p in points: if end is None or end < p[0]: ...
Add py solution for 720. Longest Word in Dictionary
class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ words = sorted(words, key=lambda w:(len(w), w)) prefix_dict = set() max_word = '' for w in words: if len(w) == 1 or w[:-1] in prefix_dict: ...
Add a script that will use pyinstaller to create an exe.
""" Build (freeze) the versionhero program. """ import os def main(): """ Run this main function if this script is called directly. :return: None """ os.system('pyinstaller --onefile versionhero.py') if __name__ == "__main__": main()
Add API test for receiver list
# 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...
Create an object for create post request
from django import forms from blog_posting import models class CreatePost(forms.ModelForm): class Meta: model = models.Post exclude = ("created_at", "modified_at", "published")
Add initial test of assess_cloud_combined.
from mock import call, Mock, patch from assess_cloud import assess_cloud_combined from deploy_stack import BootstrapManager from fakejuju import fake_juju_client from tests import ( FakeHomeTestCase, observable_temp_file, ) class TestAssessCloudCombined(FakeHomeTestCase): def backend_call(self, cli...
Add test case for "use_default".
# 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"); you may not use th...
Add a client to migrate from ResultParent.user_agent_list to ResultParent.user_agent_pretty
#!/usr/bin/python2.4 # # Copyright 2009 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 or ...
Add tests for PropertyModTracker plugin
import sqlalchemy as sa from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin from tests import TestCase class TestPropertyModificationsTracking(TestCase): plugins = [PropertyModTrackerPlugin] def create_models(self): class User(self.Model): __tablename__ = 'text_item' ...
Add tests for Bioregistry module
from indra.databases import bioregistry def test_get_ns_from_bioregistry(): assert bioregistry.get_ns_from_bioregistry('xxxx') is None assert bioregistry.get_ns_from_bioregistry('noncodev4.rna') == 'NONCODE' assert bioregistry.get_ns_from_bioregistry('chebi') == 'CHEBI' def test_get_ns_id_from_bioregist...
Add test module for IPFGraph
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest import os, sys cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__))) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) import ipf.ipf import ipf.ipfblock.rgb2gray import cv class TestIPFGraph(unittest.TestCase): def...
Modify Pypo -> Download files from cloud storage
import os import logging import ConfigParser import urllib2 from libcloud.storage.types import Provider, ContainerDoesNotExistError, ObjectDoesNotExistError from libcloud.storage.providers import get_driver CONFIG_PATH = '/etc/airtime/airtime.conf' class CloudStorageDownloader: def __init__(self): config...
Add 5010 generic ISA facade tests.
import datetime import os import unittest from tigershark.facade.common import IdentifyingHeaders from tigershark.parsers import IdentifyingParser class TestIdentifyingHeaders(unittest.TestCase): def parse_file(self, name): with open(os.path.join('tests', name)) as f: parsed = IdentifyingPar...
Add test for failing commands because of n_args
#!/usr/bin/env python # encoding: utf-8 """Fail commands because of arguments test for vimiv's test suite.""" from unittest import main from vimiv_testcase import VimivTestCase class FailingArgTest(VimivTestCase): """Failing Argument Tests.""" @classmethod def setUpClass(cls): cls.init_test(cls)...
Install wkhtmltox from the pkgs on sourceforge
""" wkhtmltopdf Blueprint blueprints: - blues.wkhtmltopdf """ from fabric.decorators import task from refabric.context_managers import sudo from refabric.contrib import blueprints from . import debian __all__ = ['setup', 'configure'] blueprint = blueprints.get(__name__) @task def setup(): """ Install...
""" wkhtmltopdf Blueprint .. code-block:: yaml blueprints: - blues.wkhtmltopdf settings: wkhtmltopdf: # wkhtmltopdf_version: 0.12.2.1 """ from fabric.decorators import task from refabric.context_managers import sudo, settings from refabric.contrib import blueprints from refabric...
Add tests for queue implementation
import unittest from queue import Queue class TestStringMethods(unittest.TestCase): def test_enqueue_to_empty_queue(self): queue = Queue() self.assertEqual(queue.size, 0, "Queue should be empty") queue.enqueue(1) self.assertEqual(queue.size, 1, "Queue should contain one element") ...
Make all models visible in Admin
from django.contrib import admin from .models import Voter, Flag, Vote admin.site.register(Voter) admin.site.register(Flag) admin.site.register(Vote)
Add py solution for 374. Guess Number Higher or Lower
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ L, U = 0, n + 1 ...
Use xml.sax.saxutils.escape in place of xmlrpclib.escape
# vim:fileencoding=utf-8:noet from powerline.renderer import Renderer from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from xmlrpclib import escape as _escape class PangoMarkupRenderer(Renderer): '''Powerline Pango markup segment renderer.''' @staticmethod def hlstyle(*args, **kwargs): ...
# vim:fileencoding=utf-8:noet from powerline.renderer import Renderer from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from xml.sax.saxutils import escape as _escape class PangoMarkupRenderer(Renderer): '''Powerline Pango markup segment renderer.''' @staticmethod def hlstyle(*args, **kwa...
Add more time to mqtt.test.client
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
Patch to remove 'Add Recipients' button from Email Digest form
def execute(): import webnotes webnotes.conn.sql(""" DELETE FROM tabDocField WHERE parent = 'Email Digest' AND label = 'Add Recipients' AND fieldtype = 'Button'""")
Add functional test for listing profile_type
# 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 tool to update method names.
#!/bin/env python3 import os import re import sys if len(sys.argv) < 2 :#or sys.argv[1] == "--help": print("rename_code.py <source_code_directory>") print("Update python code to new style.") sys.exit(0) old_names = set() class_names = set() for (dir, dirs, files) in os.walk(sys.argv[1]): if dir == "....
Add script to sort graphics
import os, shutil def copyFile(src, dest): try: shutil.copy(src, dest) # eg. src and dest are the same file except shutil.Error as e: print('Error: %s' % e) # eg. source or destination doesn't exist except IOError as e: print('Error: %s' % e.strerror) sourcefavicon = "/opt/...
Add a United States ATIN module
# atin.py - functions for handling ATINs # # Copyright (C) 2013 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) ...
ADD Network setup unit tests
def test_initial_setup(client): result = client.post("/setup/", data={"setup": "setup_configs_sample"}) assert result.status_code == 200 assert result.get_json() == {"msg": "Running initial setup!"} def test_get_setup(client): result = client.get("/setup/") assert result.status_code == 200 as...
Change the version of module.
# -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '8.0.1.0.1', 'depends': [ ...
# -*- coding: utf-8 -*- # Copyright (C) 2009 Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation ZIP Codes', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '9.0.1.0.0', 'depends': [ ...
Add commandline command for creating accounting data.
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.utils.translation import activate from kirppu.accounting import accounting_receipt class Command(BaseCommand): help = 'Dump accounting CSV to standard output' def add_arguments(self, parser): parser.add_argument(...
Use dictionary lookup only once
from __future__ import absolute_import import six from sentry.api.serializers import Serializer, register from sentry.models import Commit, CommitFileChange from sentry.api.serializers.models.release import get_users_for_commits @register(CommitFileChange) class CommitFileChangeSerializer(Serializer): def get_a...
from __future__ import absolute_import import six from sentry.api.serializers import Serializer, register from sentry.models import Commit, CommitFileChange from sentry.api.serializers.models.release import get_users_for_commits @register(CommitFileChange) class CommitFileChangeSerializer(Serializer): def get_a...
Fix naming of location in meeting
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-11 16:58 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mainapp', '0009_auto_20170911_1201'), ] operations = [ migrations.RenameField( ...
Switch myisam to innodb for fulltext_record_properties
"""Switch fulltext_record_properties to innodb Revision ID: 53bb0f4f6ec8 Revises: 63fc392c91a Create Date: 2014-09-30 09:20:05.884100 """ # revision identifiers, used by Alembic. revision = '53bb0f4f6ec8' down_revision = '63fc392c91a' from alembic import op def upgrade(): op.drop_index('fulltext_record_propert...
Set postage for all existing templates to service default
""" Revision ID: 0253_set_template_postage Revises: 0252_letter_branding_table Create Date: 2019-01-30 16:47:08.599448 """ from alembic import op import sqlalchemy as sa revision = '0253_set_template_postage' down_revision = '0252_letter_branding_table' def upgrade(): # ### commands auto generated by Alembic ...
Clean up an old index in sentry_groupedmessage
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'GroupedMessage', fields ['logger', 'view', 'checksum'] db.delete_unique('sentry_gr...
Add sound recording tool with arecord and lame
# coding: utf-8 import os import re import shlex from subprocess import Popen, PIPE def available_devices(): devices =[] os.environ['LANG'] = 'C' command = 'arecord -l' arecord_l = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE) arecord_l.wait() if arecord_l.returncode != 0: p...
Add command line tool to import metadata
#!/usr/bin/python # -*- coding: utf-8 -*- import os import csv from django.core.management.base import BaseCommand from emgapimetadata import models as m_models class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('importpath', type=str) def handle(self, *args, **optio...
Add tests for password hashing and checking
import hashlib from virtool.utils import random_alphanumeric from virtool.users import hash_password, check_password, check_legacy_password class TestHashPassword: def test_basic(self): assert check_password("hello_world", hash_password("hello_world")) class TestLegacyHashPassword: def test_basic...
Add Python 3.8 f-string debugging specifier.
""" Python 3.8 にて導入された f-string での {xxx=} 表記についてのサンプルです。 REFERENCES:: http://bit.ly/2NlJkSc """ from trypython.common.commoncls import SampleBase class Sample(SampleBase): def exec(self): # ------------------------------------------------------------ # f-string debugging specifier # ...
Create new utility module for drawing
from PIL import Image, ImageColor, ImageDraw, ImageFont import utility.logger logger = utility.logger.getLogger(__name__ ) BLACK = ImageColor.getrgb("black") # def draw_rotated_text(canvas: Image, text: str, font: ImageFont, xy: tuple, fill: ImageColor=BLACK, angle: int=-90): def draw_rotated_text(canvas, text, font,...
Add migration for meta names
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-04 17:55 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20170704_1028'), ] operations = [ migrations.AlterModelOptions( ...
Add command to get number of preregistrations by schema
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from osf.models import Registration, MetaSchema PREREG_SCHEMA_NAMES = [ 'Prereg Challenge', 'AsPredicted Preregistration', 'OSF-Standard Pre-Data Collection Registration', 'Replication Recipe (Brandt et al., 2013): Pre-Registra...
Initialize and declare class Node
class Node: def __init__(self): self.name = '' self.weight = 0 self.code = '' def initSet(self, name, weight): self.name = name self.weight = weight
Add watchdog that monitors scripts editing
import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class ScriptModifiedHandler(PatternMatchingEventHandler): patterns = ['*.py'] def __init__(self): super(ScriptModifiedHandler, self).__init__() # you can add some init code here def proc...
Test health check URL response
from tests.BaseTestWithDB import BaseTestWithDB from django.urls import reverse class HealthCheckURLTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.language = 'en' def test_valid_health_check_request(self): response = self.client.get(...
Add basic tests for expected links on main site homepage
from web_test_base import * class TestIATIStandard(WebTestBase): requests_to_load = { 'IATI Standard Homepage - no www': { 'url': 'http://iatistandard.org' }, 'IATI Standard Homepage - with www': { 'url': 'http://www.iatistandard.org' } } def test_co...
Increase max length of url field.
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-01 11:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20160901_2303'), ] operations = [ migrations.AlterField( ...
Add some simple tests for bug_submitted
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from DebianChangesBot.mailparsers import BugSubmittedParser as p class TestMailParserBugSubmitted(unittest.TestCase): def setUp(self): self.headers =...
Add test for memoization in N-dimensional pooling kernel generator.
import unittest import mock import chainer from chainer import testing from chainer.testing import attr from chainer.functions.pooling import pooling_nd_kernel @testing.parameterize(*testing.product({ 'ndim': [2, 3, 4], })) @attr.gpu class TestPoolingNDKernelMemo(unittest.TestCase): def setUp(self): ...
Use json_handler to force ugettext_lazy
import json from datetime import datetime from django.core.management import BaseCommand, CommandError from corehq.apps.importer.tasks import do_import from corehq.apps.importer.util import ImporterConfig, ExcelFile from corehq.apps.users.models import WebUser class Command(BaseCommand): help = "import cases from...
import json from datetime import datetime from django.core.management import BaseCommand, CommandError from dimagi.utils.web import json_handler from corehq.apps.importer.tasks import do_import from corehq.apps.importer.util import ImporterConfig, ExcelFile from corehq.apps.users.models import WebUser class Command(B...
Add a migration to replace notifications_template foreign key
""" Revision ID: 0136_notification_template_hist Revises: 0135_stats_template_usage Create Date: 2017-11-08 10:15:07.039227 """ from alembic import op revision = '0136_notification_template_hist' down_revision = '0135_stats_template_usage' def upgrade(): op.drop_constraint('notifications_template_id_fkey', 'no...
Add solution to exercise 4.4.
# 4-5. Summing a Million numbers = list(range(1, 1000001)) print("min = ", min(numbers)) print("max = ", max(numbers)) print("sum = ", sum(numbers))
Set FlowRun.respnoded to be non-nullable
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('flows', '0045_populate_responded'), ] operations = [ migrations.AlterField( mod...
Add migration to resolve inconsistency between python2 and python3 strings
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('django_mailbox', '0003_auto_20150409_0316'), ] operations = [ migrations.AlterField( model_name='message', ...
Fix matching currency being different then target currency
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-11-16 14:40 from __future__ import unicode_literals from django.db import migrations from django.db.models import F def fix_matching_currencies(apps, schema_editor): Funding = apps.get_model('funding', 'Funding') Funding.objects.update(amount_matc...
Add inet read file tests
# -*- coding: utf-8 -*- import pytest import csv from inet.inet import Inet class TestInet(): """Test the Inet class functions as expected""" def test_no_data_file(self): with pytest.raises(AttributeError): Inet(data_file=None) def test_wrong_file_type(self, tmpdir): with py...
Add a tiny helper script to shutdown the chrome frame helper process.
# Copyright (c) 2010 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. '''This is a simple helper script to shut down the Chrome Frame helper process. It needs the Python Win32 extensions.''' import pywintypes import sys imp...
Test assignment of permissions to roles
""" :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.authorization import service from tests.base import AbstractAppTestCase class PermissionToRoleAssignmentTestCase(AbstractAppTestCase): def setUp(self): super().setUp() self....
Add a management command to generate hashes for all streams that need them.
#!/usr/bin/python from django.core.management.base import BaseCommand from zerver.lib.utils import generate_random_token from zerver.models import Stream class Command(BaseCommand): help = """Set a token for all streams that don't have one.""" def handle(self, **options): streams_needing_tokens = St...
Add corporation flag in blueprints
"""add corporation flag Revision ID: d03236a0cda4 Revises: 47e567919169 Create Date: 2017-04-12 13:21:03.482000 """ # revision identifiers, used by Alembic. import sqlalchemy as sa from alembic import op from lazyblacksmith.models import Blueprint from lazyblacksmith.models import db revision = 'd03236a0cda4' dow...
Add a sensor feedback sample
#!/usr/bin/env python #coding: utf-8 import sys,time j1,j2,j3,j5,j6 = 0,60,0,0,0 while True: # $B%m%\%C%H$N3QEY$NFI$_9~$_<~4|$O(B20ms$B!J%"%P%&%H$G$9!K(B time.sleep(0.05) ch0 = 0 delta = 0 #$B%A%c%s%M%k(B0$B$N(BAD$B%3%s%P!<%?$NCM$rFI$_9~$`!J5wN%%;%s%5!K(B with open("/run/shm/adconv...
Put internal paths in one place.
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2017 Eddie Antonio Santos <easantos@ualberta.ca> # # 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/licens...
Upgrade ldap3 0.9.9.1 => 0.9.9.2
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', '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.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU...
Add K Means clustering algorithm
import numpy as np class KMeans(object): def __init__(self, inputs, clusters): self.inputs = np.array(inputs) if self.inputs.ndim == 1: self.inputs = self.inputs.reshape(self.inputs.shape[0], 1) self.test_cases = self.inputs.shape[0] self.num_clusters = clusters self.clusters = self.inputs[np.random.cho...
Add script for writing virus names to txt file
import json names = list() with open("viruses.json", "r") as f: names = [virus["name"] for virus in json.load(f)] names = sorted(names) with open("names.txt", "w") as f: f.write("\n".join(names))