Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add module for global debug variables. | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 03 10:28:37 2015
@author: Jens von der Linden
global variables all_f and all_g save value of f,g and r each time an f_func, or
g_func is called.
In the form [r, f].
To call fs convert to numpy array and all_f[:, 1] for rs all_f[:, 0].
Used for debugging.
"""
... | |
Add script to load peaks from csv | #!./venv/bin/python
import argparse
import csv
import datetime
import sys
import re
from collections import namedtuple
from blag import create_app, db
from blag.models import HikeDestination, Hike
DATE_FORMAT = '%d.%m.%Y'
COORDINATE_FORMAT = re.compile(r'^([0-9.-]+),\s*([0-9.-]+)$')
METHOD_MAP = {
'fots': 'foot'... | |
Disable failing testSmoke on cros. | # 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.
import os
from telemetry.unittest import page_set_smoke_test
class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):
def testSmoke(self):
page... | # 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.
import os
from telemetry import decorators
from telemetry.unittest import page_set_smoke_test
class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):... |
Add deploy script using Fabric | """
Deploy Freesound Explorer to labs.freesound.org (required Pythons's fabric installed)
"""
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.files import put
env.hosts = ['ffont@fs-labs.s.upf.edu']
remote_dir = '/homedtic/ffont/apps/freesound-explorer'
def __copy_static():
wi... | |
Add tests for noncommutative symbols. | """Tests for noncommutative symbols and expressions."""
from sympy import (
conjugate,
expand,
factor,
radsimp,
simplify,
symbols,
I,
)
from sympy.abc import x, y, z
A, B, C = symbols("A B C", commutative=False)
X, Y = symbols("X Y", commutative=False, real=True)
Z = X + I*Y
def test_comp... | |
Add first admin levels script | #!/usr/bin/env python
import csv
import json
states = set()
with open('2015_06_29_NNHS_2015_Selected EA_Final.xlsx - EA_2015.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
for row in reader:
state = row[0]
if not state:
continue
states.add(s... | |
Add Arduino USB Vendor and product IDs |
ARDUINO_SENSOR_TYPE="arduino"
SIMULATED_SENSOR_TYPE="simulated"
AUTO_DETERMINE_SENSOR="auto"
# TODO - put this as a CNAME and an SRV record in DNS instead
IN_PROCESS_DESTINATION="local"
UDP_TRANSPORT_TYPE="udp"
#DEFAULT_DESTINATION_PORT="_sensors._udp"
#DEFAULT_DESTINATION_HOST="192.168.56.1"
DEFAULT_DESTINATION_HOST... |
ARDUINO_SENSOR_TYPE = "arduino"
SIMULATED_SENSOR_TYPE = "simulated"
AUTO_DETERMINE_SENSOR = "auto"
# TODO - put this as a CNAME and an SRV record in DNS instead
IN_PROCESS_DESTINATION = "local"
UDP_TRANSPORT_TYPE = "udp"
#DEFAULT_DESTINATION_PORT = "_sensors._udp"
#DEFAULT_DESTINATION_HOST = "192.168.56.1"
DEFAULT_DE... |
Structure for density ratio estimators | # -*- coding: utf-8 -*-
#
# Carl is free software; you can redistribute it and/or modify it
# under the terms of the Revised BSD License; see LICENSE file for
# more details.
"""Density ratio estimators."""
| |
Add helpers to create websocket requests | # Oxypanel
# File: util/web/websockets.py
# Desc: helpers to make authed websocket requests
from uuid import uuid4
import config
from app import redis_client
from util.web.user import get_current_user
def make_websocket_request(websocket, websocket_data):
# Generate request key
request_key = str(uuid4())
... | |
Add unit tests for EnvironmentBase class | """Tests for the csdms.dakota.environment.base module."""
from nose.tools import raises, assert_true, assert_equal
from csdms.dakota.environment.base import EnvironmentBase
class Concrete(EnvironmentBase):
"""A subclass of EnvironmentBase used for testing."""
def __init__(self):
EnvironmentBase.__i... | |
Resolve migration conflict via merge | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('survey', '0021_auto_20150506_1922'),
('survey', '0021_auto_20150506_1406'),
]
operations = [
]
| |
Add example for filter search | """Module giving some examples how to use PyDOV to query boreholes."""
def get_description():
"""The description gives information about the Boring type."""
from pydov.search.grondwaterfilter import GrondwaterFilterSearch
gwfilter = GrondwaterFilterSearch()
print(gwfilter.get_description())
def get_... | |
Migrate report_qweb_element_page_visibility module to 9.0 | # -*- coding: utf-8 -*-
#########################################################################
# #
# Copyright (C) 2015 Agile Business Group #
# #
... | |
Add test for email account export | from django.test import TestCase
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_action_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
| |
Add stub for Subscriptions API testing | """
Tests for the Subscriptions API class.
"""
import unittest
import mws
from .utils import CommonRequestTestTools
class SubscriptionsTestCase(unittest.TestCase, CommonRequestTestTools):
"""
Test cases for Subscriptions.
"""
# TODO: Add remaining methods for Subscriptions
def setUp(self):
... | |
Initialize alov parsing code with main block | """A script for parsing the Alov bounding box `.ann` files."""
import sys
import os
import itertools
import pandas as pd
import xml.etree.ElementTree as ET
if __name__ == '__main__':
bbox_dir = sys.argv[1]
output_filepath = sys.argv[2]
ann_files_by_dir = (i[2] for i in os.walk(bbox_dir))
bbox_ann_f... | |
Add decorator to test url against checkamte | """View decorators to integrate with checkmate's API."""
import logging
from checkmatelib import CheckmateClient, CheckmateException
from pyramid.httpexceptions import HTTPTemporaryRedirect
logger = logging.getLogger(__name__)
def checkmate_block(view, url_param="url", allow_all=True):
"""Intended to be used as... | |
Add a performance test for concrete execution. |
# Performance tests on concrete code execution without invoking Unicorn engine
import os
import time
import logging
import angr
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests'))
def test_tight_loop(arch):
b = angr.Project(os.path.join(test_locatio... | |
Add plugin for PHP5 FPM | #!/usr/bin/env python
#
# igcollect - PHP5 FPM
#
# This is the data collector for the PHP5 FPM status page. It makes a
# HTTP request to get the page, and formats the output. All the numeric
# values of the requested pool is printed.
#
# Copyright (c) 2016, InnoGames GmbH
#
from __future__ import print_function
imp... | |
Add command for bulk adding talks | from django.core.management.base import BaseCommand
from events.models import Event
from cfp.models import PaperApplication
from talks.models import Talk
class Command(BaseCommand):
help = "Bulk add talks from application ids"
def add_arguments(self, parser):
parser.add_argument('event_id', type=int... | |
Add script to fetch the binary pieces from Apple. | import urllib2
import os
pieces = """
Security.hdrs.tar.gz
Security.root.tar.gz
SecurityTokend.hdrs.tar.gz
SecurityTokend.root.tar.gz
libsecurity_cdsa_client.hdrs.tar.gz
libsecurity_cdsa_client.root.tar.gz
libsecurity_cdsa_utilities.hdrs.tar.gz
libsecurity_cdsa_utilities.root.tar.gz
libsecurity_utilities.root.tar.gz
... | |
Add missing S3 boto storage classes | from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')
| |
Add a python test file | import imap_cli
from imap_cli import config
from imap_cli import search
connect_conf = config.new_context_from_file(section='imap')
display_conf = config.new_context_from_file(section='display')
imap_account = imap_cli.connect(**connect_conf)
display_conf['format_list'] = u'{uid:>5} : {from:<40} : {subject}'
for tr... | |
Change kamerstuk id from integer to string | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-19 20:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('document', '0007_auto_20160518_1825'),
]
operations = [
migrations.AlterMode... | |
Add code that makes many images being clear memory. | # coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import os
from tqdm import trange
os.makedirs('./images/', exist_ok=True)
i = 0
for i in trange(10000, desc='saving images'):
img = np.full((64, 64, 3), 128)
plt.imshow(img / 255.)
plt.axis('off')
plt.tick_params(labelbottom=False, labelleft=Fals... | |
Add feature extraction (transfer learning) for Inception 1k model for cat/dog/mouse dataset (no training). | from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deepwater import H2ODeepWaterEstimator
import urllib
def deepwater_inception_bn_feature_extraction():
if not H2ODeepWaterEstimator.available(): return
... | |
Add config for Zephyr port of 96Boards Carbon. | from machine import Signal
# 96Boards Carbon board
# USR1 - User controlled led, connected to PD2
# USR2 - User controlled led, connected to PA15
# BT - Bluetooth indicator, connected to PB5.
# Note - 96b_carbon uses (at the time of writing) non-standard
# for Zephyr port device naming convention.
LED = Signal(("GPIOA... | |
Add small script to retrieve lexers from pygments | #!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
| |
Add a benchmark report to show the speed performance. | '''
Make a report showing the speed of some critical commands
Check whether it is fast enough for your application
'''
from __future__ import print_function
from unrealcv import client
import docker_util
import time
import pytest
def run_command(cmd, num):
for _ in range(num):
client.request(cmd)
if __nam... | |
Add test for default_db schema | # -*- mode: python; coding: utf-8 -*-
# Copyright 2016 the HERA Collaboration
# Licensed under the 2-clause BSD license.
"""
Test that default database matches code schema.
"""
from sqlalchemy.orm import sessionmaker
from hera_mc import mc, MCDeclarativeBase
from hera_mc.db_check import is_sane_database
def test_def... | |
Add Sniffer thread class sketch | import threading
from time import sleep
class Sniffer(threading.Thread):
def __init__(self, arg):
# Set thread to run as daemon
self.daemon = True
# Initialize object variables with parameters from arg dictionary
self.arg = arg
# Thread has not come to life yet
se... | |
Add ean check free code | #!environment python
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gen... | |
Add a test file which tests the various decorator functions. |
import py.test
from tiddlyweb.model.policy import UserRequiredError
from tiddlywebplugins.utils import (entitle, do_html, require_role,
require_any_user)
STATUS = ''
HEADERS = []
def start_responser(status, headers, exc_info=None):
global STATUS
global HEADERS
STATUS = status
HEADERS = head... | |
Add a management command to dump all messages on public streams for a realm. | from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.models import Message, Realm, Stream, Recipient
import datetime
import time
class Command(BaseCommand):
default_cutoff = time.time() - 60 * 60 * 24 * 30 # 30 days.
option_list = BaseCommand.option_list + (
... | |
Add a data migration to iterate over forks and find where the last log is a fork log and set the last_logged date on the node to the date of that log. | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-10-29 17:01
from __future__ import unicode_literals
from django.db import migrations
from django.db.models import OuterRef, Subquery
from osf.models import NodeLog, Node
from django_bulk_update.helper import bulk_update
def untransfer_forked_date(state, s... | |
Add unit tests for write module | #!/usr/bin/env python
#
# Tests for dakota_utils.write.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.file import touch, remove
from dakota_utils.write import *
nonfile = 'fbwiBVBVFVBvVB.txt'
def setup_mo... | |
Add a simple login test case | import pytest
from controller import db
from model.user import User
from test import C3BottlesTestCase, NAME, PASSWORD
class LoginViewTestCase(C3BottlesTestCase):
def test_login(self):
self.create_test_user()
resp = self.c3bottles.post('/login', data=dict(
username=NAME,
... | |
Add migration for zabbix tables | from django.db import migrations
TABLES = (
'monitoring_resourceitem',
'monitoring_resourcesla',
'monitoring_resourceslastatetransition',
'waldur_zabbix_usergroup',
'waldur_zabbix_item',
'waldur_zabbix_trigger',
'waldur_zabbix_host_templates',
'waldur_zabbix_template',
'waldur_zabbi... | |
Create new Direction class. Calculates distance and time from two addresses with Google Maps API | #!/usr/bin/python
import googlemaps
#api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
class Directions(object):
"""
"""
api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
def __init__(self):
self.gmaps = googlemaps.Client(self.api_key)
pass
def getData(self, orig, dest):
... | |
Add script to merge json files | #!/usr/bin/env python
import sys
import json
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
data = sys.argv[1:]
merged_data = {'data': []}
for path, tag in zip(data[0::2], data[1::2]):
with open(path, 'r') as handle:
ldata = json.load(handle)
for element in ldata[... | |
Set UserProfile.user to OneToOne instead o ForeignKey | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-16 19:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_users', '0015_userprof... | |
Add conf test for django settings | def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
SITE_ID=1,
SECRE... | |
Add function to determine if two strings are anagrams | '''
In this module, we determine if two given strings are anagrams
'''
def is_anagram_sort(string_1, string_2):
'''
Return True if the two given strings are anagrams using sorting
'''
return sorted(string_1) == sorted(string_2)
def is_anagram_counter(string_1, string_2):
'''
Return True if the two given strin... | |
Add AnalysisDefinition helper for configuring analyzers | import logging
from elasticsearch_dsl.analysis import CustomAnalyzer
logger = logging.getLogger(__name__)
class AnalysisDefinition(object):
'''
This defines a helper class for registering search analyzers.
Analyzers can be defined as callables, hence ensuring io/cpu bound analysis
configuration can ... | |
Add a point in polygon routine | """A collection of tools for spatial data and GIS tasks.
"""
def point_in_poly(pnt, poly):
"""Calculate whether a point lies inside a polygon
Algorithm is based on the ray-tracing procedure described at
http://geospatialpython.com/2011/01/point-in-polygon.html
Parameters
----------
pnt : seq... | |
Add logistic regression without batch | #!/usr/bin/env python
import numpy as np
def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
def test_sigmoid():
x = 0
print("Input x: {}, the sigmoid value is: {}".format(x, sigmoid(x)))
def main():
# Prepare dataset
train_features = np.array([[1, 0, 26], [0, 1, 25]], dtype=np.float)
train_labels = np.arr... | |
Fix review and user pk in postgresql | from django.db import migrations
ALTER_REVIEW_PROPOSAL_ID = """
ALTER TABLE "reviews_review" alter COLUMN "proposal_id"
SET DATA TYPE bigint;
"""
ALTER_REVIEW_REVIEWER_ID = """
ALTER TABLE "reviews_review" alter COLUMN "reviewer_id"
SET DATA TYPE bigint;
"""
class Migration(migrations.Migrat... | |
Change to import gravity constant from constants file. | #!/usr/bin/python
import numpy as N
def u_star(u,v,w):
'''
Compute the friction velocity, u_star, from the timeseries of the velocity \
components u, v, and w (an nD array)
'''
from metpy.bl.turb.fluxes import rs as R
rs = R(u,v,w)
uw = rs[3]
vw = rs[4]
us = N.power(N.power(uw,2)+N.power(v... | #!/usr/bin/python
import numpy as N
def u_star(u,v,w):
'''
Compute the friction velocity, u_star, from the timeseries of the velocity \
components u, v, and w (an nD array)
'''
from metpy.bl.turb.fluxes import rs as R
rs = R(u,v,w)
uw = rs[3]
vw = rs[4]
us = N.power(N.power(uw,2)+N.power(v... |
Add concrete class `WORLD` that implements `Analyzer` and `Synthesizer` | # coding: utf-8
from vctk import Analyzer, Synthesizer, SpeechParameters
import world
class WORLD(Analyzer, Synthesizer):
"""
WORLD-based speech analyzer & synthesizer
TODO:
support platinum
"""
def __init__(self,
period=5.0,
fs=44100,
f0_... | |
Add a basic test to make sure acquisition works | import pytest
@pytest.fixture
def testdir_with_map(testdir):
testdir.makefile('.yaml', map='''
version: 1
environments:
mock_env:
roles:
mock:
- mocker.example:
greeting: Hello World
''')
testdir.makepyfile(mocker=''... | |
Add a test for loading files as a stream | #!/usr/bin/env python
import cle
import nose
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
def test_stream():
dirpath = os.path.join(test_location, "x86_64")
filepath = os.path.join(dirpath, "fauxware")
filestream = open(filepath, 'rb')
... | |
Set up Code Fights knapsack light problem | #!/usr/local/bin/python
# Code Fights Knapsack Problem
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
else:
return max([v for v, w in zip((value1, value2), (weight1, weight2))
if w <= maxW] + [0])
def main():... | |
Add missing files from Mac | from __future__ import absolute_import, division, print_function, unicode_literals
class Openable(object):
def __init__(self):
self.is_open = True
def close(self):
self.is_open = False
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
| |
Add test skeleton for resource_parameters unit tests | class ResourceParametersTest(BaseTest):
def test_resource_parameter_base_process_requested_values(self):
pass
def test_resource_parameter_base_process_value(self):
pass
def test_resource_parameter_base_html_element(self):
pass
def test_single_valued_parameter_process_requeste... | |
Read the data and output to terminal | #!/usr/bin/python3
import smbus
import time
import sys
# Get I2C bus
bus = smbus.SMBus(1)
# number of channels the monitoring board has
no_of_channels = 1
# PECMAC125A address, 0x2A(42)
# Command for reading current
# 0x6A(106), 0x01(1), 0x01(1),0x0C(12), 0x00(0), 0x00(0) 0x0A(10)
# Header byte-2, command-1, start... | |
Add sample app calling SPL functions | # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
import sys
import string
from streamsx.topology.topology import Topology
from streamsx.topology import spl_ops
from streamsx.topology.spl_ops import *
from streamsx.topology.spl_types import *
from streamsx.topology.schema import *
import streamsx.topolo... | |
Add data migration to build ForeignKey on Person.uuid field | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-17 20:19
from __future__ import unicode_literals
from django.db import migrations
def link_person_model(apps, schema_editor):
Person = apps.get_model('competition', 'Person')
for person in Person.objects.all():
person.clubassociation_set.... | |
Add migrate on shell script | from django.db import connection
from vpr_content import models
def removeDuplicatedTitleInMaterial():
cur = connection.cursor()
qr0 = 'select id from vpr_content_material'
qr1 = 'select text from vpr_content_material where id=%d'
qr2 = 'update vpr_content_material set text=\'%s\' where id=%d'
pt0 ... | |
Add shutdown at end to make sure that we dont crash on shutdown. | import sys
import _jpype
import jpype
from jpype.types import *
from jpype import JPackage, java
import common
import pytest
try:
import numpy as np
except ImportError:
pass
class ZZZTestCase(common.JPypeTestCase):
def setUp(self):
common.JPypeTestCase.setUp(self)
def testShutdown(self):
... | |
Add extrusion test for points and lines | # -*- coding: utf-8 -*-
"""Create several entities by extrusion, check that the expected
sub-entities are returned and the resulting mesh is correct.
"""
import pygmsh
import numpy as np
def test():
kernels = [pygmsh.built_in, pygmsh.opencascade]
for kernel in kernels:
geom = kernel.Geometry()
... | |
Add a class for management of thermal throttling | # Copyright (c) 2012 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 logging
class ThermalThrottle(object):
"""Class to detect and track thermal throttling
Usage:
Wait for IsThrottled() to be False before ... | |
Add command to cleanup commtrack forms | from django.core.management.base import BaseCommand
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs
from corehq.apps.commtrack.models import SupplyPointCase
class Command(BaseCommand):
startkey = ['ipm-senegal', 'by_type', 'XFormInstance']
endkey = startkey + [{}]... | |
Add new script for welcome messaging | """
instabot example
Workflow:
Welcome message for new followers.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], '../'))
from instabot import Bot
NOTIFIED_USERS_PATH = 'notified_users.txt'
MESSAGE = 'Thank you for a script, sudoguy!'
parse... | |
Add min and max heap sort | __author__ = 'harsh'
LT = 0
GT = 1
def compare_ele(comp_type, ele1, ele2):
if comp_type == LT:
return ele1 < ele2
elif comp_type == GT:
return ele1 > ele2
raise Exception("Compare type Undefined")
def heapsort(lst, comp_type=LT):
"""
:param lst:
"""
#heapify
for sta... | |
Add basic tests for `geographic_distance()` | # -*- coding: utf-8 -*-
import pytest
from skylines.lib.geo import geographic_distance
from skylines.model.geo import Location
@pytest.mark.parametrize(
"loc1,loc2,expected",
[
(
Location(latitude=0.0, longitude=0.0),
Location(latitude=0.0, longitude=0.0),
0.0,
... | |
Add login provides in session module. | from flask import Flask, redirect, url_for, session, request
from flask_oauth import OAuth
from config import GOOGLE_OAUTH_ID, GOOGLE_OAUTH_SECRET, \
TWITTER_OAUTH_ID, TWITTER_OAUTH_SECRET, \
FACEBOOK_OAUTH_ID, FACEBOOK_OAUTH_SECRET
oauth = OAuth()
google = oauth.remote_app('go... | |
Create new module for calculation of veg indices; add EVI | """ Functions for computing vegetation indices
"""
from __future__ import division
def EVI(red, nir, blue):
""" Return the Enhanced Vegetation Index for a set of np.ndarrays
EVI is calculated as:
.. math::
2.5 * \\frac{(NIR - RED)}{(NIR + C_1 * RED - C_2 * BLUE + L)}
where:
- :math:... | |
Add 30 Days of Code Day 0 in Python. | # Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)
| |
Change related name for SuppleirPart.supplier | # Generated by Django 2.2.10 on 2020-04-13 08:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('company', '0019_auto_20200413_0642'),
]
operations = [
migrations.AlterField(
model_name='supp... | |
Add collection mac tool for ilo | #!/usr/bin/python
import pexpect
import re
import sys
from optparse import OptionParser
macs=[]
err=0
op=OptionParser("fancheck [options] ip")
op.add_option("-l","--log",action="store_true",dest="log",default=False,help="whole logs to stdout")
op.add_option("-u","--user",action="store",dest="user",type="string",defa... | |
Add a simple experiment script | from toolbox.datasets.sr import load_data
from toolbox.models import srcnn
from toolbox.training import train
(x_train, y_train), (x_test, y_test) = load_data()
model = srcnn(x_train.shape[1:], f1=9, f2=1, f3=5)
train(model, x_train, y_train, validation_data=(x_test, y_test),
nb_epoch=2, resume=True, save_dir='... | |
Add command to generate metadata | import logging
from optparse import make_option
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from projects.models import Project
log = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
queryset ... | |
Add tests for improved loading functionality. | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: y... | |
Test TemplateLookup dirs are not cleared during lms startup. | """Tests for the lms module itself."""
from django.test import TestCase
from edxmako import add_lookup, LOOKUP
from lms import startup
class TemplateLookupTests(TestCase):
"""
Tests for TemplateLookup.
"""
def test_add_lookup_to_main(self):
"""Test that any template directories added are not... | |
Add management script to rename the default site | from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
class Command(BaseCommand):
def handle(self, *args, **options):
site = Site.objects.get()
site.domain = 'website.jongedemocraten.nl'
site.name = 'Landelijk'
site.save()
| |
Add script to count the lines in a corpus | """Script to count the lines in a corpus of texts.
This information can be used to normalize the results.
Input: directory containing text files
Output: csv containing <text_id>, <# lines>
Usage: python count_lines.py <dir in> <file out>
"""
import argparse
import glob
import os
import codecs
import pandas as pd
i... | |
Add a script to visualize detection matfiles. | #!/usr/bin/env python
import argparse
import os
import sys
import cv2
from vdetlib.vdet.dataset import imagenet_vdet_class_idx
from vdetlib.utils.common import imread, imwrite
from vdetlib.utils.protocol import proto_load, proto_dump, frame_path_at, frame_top_detections
from vdetlib.utils.visual import add_bbox
from v... | |
Add missing DataDependency objects for duplicates | # Generated by Django 3.1.7 on 2021-10-12 10:39
from django.db import migrations, models
def create_duplicate_dependencies(apps, schema_editor):
Data = apps.get_model("flow", "Data")
DataDependency = apps.get_model("flow", "DataDependency")
duplicates = Data.objects.filter(duplicated__isnull=False)
du... | |
Allow user to solve district court captcha | import cookielib
import os
import re
import sys
import urllib
import urllib2
import webbrowser
from bs4 import BeautifulSoup
from time import sleep
user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; " + \
u"rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11"
# Get cookie and list of courts
cookieJar = ... | |
Add script to plot signal figure. | """
A script to plot signals
"""
import sys
import os
import getopt
import json
import matplotlib.pyplot as plt
CMD_USAGE = """
"""
MAX_PLOT_SIZE = 5000
def plot_signal(signal):
with open(signal, "rb") as json_file:
json_data = json.load(json_file)
beacons = json_data['interestedBeacons']
... | |
Add simple example web cralwer | import guv
guv.monkey_patch()
import requests
def get_url(url):
print('get_url()')
return requests.get(url)
def main():
urls = ['http://httpbin.org/delay/1'] * 10
pool = guv.GreenPool()
results = pool.imap(get_url, urls)
for i, resp in enumerate(results):
print('{}: done, length: {}... | |
Add download/forward tests for imagenet pretrainedmodels | import pytest
import torch
import torch.nn as nn
from torch.autograd import Variable
import pretrainedmodels as pm
import pretrainedmodels.utils as utils
pm_args = []
for model_name in pm.model_names:
for pretrained in pm.pretrained_settings[model_name]:
if pretrained in ['imagenet', 'imagenet+5k']:
... | |
Add command line test for cosym.py | from __future__ import absolute_import, division, print_function
import os
import pytest
import procrunner
def test_cosym(regression_data, run_in_tmpdir):
reg_path = regression_data("multi_crystal_proteinase_k").strpath
command = ['dials.cosym']
for i in [1, 2, 3, 4, 5, 7, 8, 10]:
command.append(os.path.j... | |
Add N0Q check for iem21 to run | """
Check the production of N0Q data!
"""
import json
import datetime
import sys
j = json.load( open('/home/ldm/data/gis/images/4326/USCOMP/n0q_0.json') )
prodtime = datetime.datetime.strptime(j['meta']['valid'], '%Y-%m-%dT%H:%M:%SZ')
radarson = int(j['meta']['radar_quorum'].split("/")[0])
gentime = j['meta']['process... | |
Add a script to extract a minidump from a crash dump | #!/usr/bin/env python
# Copyright 2013 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.
"""A tool to extract minidumps from dmp crash dumps."""
import os
import sys
from cgi import parse_multipart
def ProcessDump(dump_fi... | |
Add better glowing line script; uses alpha to create the line out of solid green; handles intersections well | from PIL import Image, ImageDraw
import random
W = 500
im = Image.new('RGB', (W, W))
NCOLORS = 19
NLINES = 15
def make_line_mask(im):
mask = Image.new('L', im.size, color=0)
grays = []
v = 255.0
for i in range(NCOLORS):
grays.append(int(v))
v *= 0.91
grays.reverse()
draw=ImageDraw.Draw(mask)
... | |
Clear old Pollination Mapper results | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def clear_old_results(apps, schema_editor):
Scenario = apps.get_model('modeling', 'Scenario')
Scenario.objects.all().update(
results='[]',
modification_hash='',
inputmod_hash='',
)
... | |
Add a templatetag to convert language code to language name | from urllib import quote
from django.template import Library
register = Library()
from ehriportal.portal import utils
@register.filter
def langname(code):
"""Creates a haystack facet parameter in format:
&selected_facets=<name>_exact:<value>"""
return utils.language_name_from_code(code)
| |
Add an example of rdoinfo frontend usage | #!/usr/bin/env python
"""
An example script that uses rdopkg.actionmods.rdoinfo to output a list of
currently maintained RDO projects.
"""
from rdopkg.actionmods import rdoinfo
def list_projects():
inforepo = rdoinfo.get_default_inforepo()
info = inforepo.get_info()
pkgs = info['packages']
pkg_filte... | |
Add script to convert data into sql | # -*- coding: utf-8 -*-
"""
Rongxin Yin, 11/2/2016
"""
import pandas as pd
import seaborn as sns
a = [1,2,3]
df = pd.DataFrame(a,['a','b','c'])
print("Done")
| |
Change description for task types | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-20 09:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0006_auto_20160720_1058'),
]
operations = [
migrations.AlterField(
... | |
Add lots of unit tests for teuthology.suite | import requests
from datetime import datetime
from pytest import raises
from teuthology.config import config
from teuthology import suite
class TestSuite(object):
def test_name_timestamp_passed(self):
stamp = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
name = suite.make_name('suite', 'ceph', 'ke... | |
Add test for fake data generation | from yunity.utils.tests.abc import BaseTestCase
from yunity.utils.tests.fake import faker as default_faker, Faker
from yunity.utils.validation import Validator, OfType, HasKey, IsReasonableLengthString
class ValidLocation(Validator):
def __call__(self, location):
(HasKey('description') & IsReasonableLengt... | |
Add some polynomial-related functions. These will be useful later. | # -*- coding: utf-8 -*-
from sympy import Poly, legendre_poly, diff
from sympy.abc import x
from mpmath import polyroots
def gauss_legendre_points(n):
"""Returns the Gauss-Legendre quadrature points for order *n*
These are defined as the roots of P_n where P_n is the n'th
Legendre polynomial.
"""
... | |
Allow doctest runner to keep going after failures | #!/usr/bin/env python
import doctest
import sys
if hasattr(doctest, "testfile"):
print("=== Test file: README ===")
failure, tests = doctest.testfile('README', optionflags=doctest.ELLIPSIS)
if failure:
sys.exit(1)
print("=== Test file: test.rst ===")
failure, tests = doctest.testfile('test/... | #!/usr/bin/env python
import doctest
import sys
if hasattr(doctest, "testfile"):
total_failures, total_tests = (0, 0)
print("=== Test file: README ===")
failure, tests = doctest.testfile('README', optionflags=doctest.ELLIPSIS)
total_failures += failure
total_tests += tests
print("=== Test file... |
Add test for GeoJSON serializer | import json
from django.test import TestCase
from django.core.serializers import serialize
from frontend.models import PCT
from api.geojson_serializer import as_geojson_stream
class GeoJSONSerializerTest(TestCase):
fixtures = ['orgs']
def test_output_is_the_same_as_core_serializer(self):
fields = ... | |
Add migration for the is_draft column | """Add is_draft status to queries and dashboards
Revision ID: 65fc9ede4746
Revises:
Create Date: 2016-12-07 18:08:13.395586
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
from sqlalchemy.exc import ProgrammingError
revision = '... | |
Add solution to challenge 2. | import base64
def fixed_xor(hex_a, hex_b):
decoded_a = base64.b16decode(hex_a, True)
decoded_b = base64.b16decode(hex_b, True)
xor_result = [chr(ord(a) ^ ord(b)) for a, b in zip(decoded_a, decoded_b)]
return base64.b16encode(''.join(xor_result))
if __name__ == '__main__':
hex_a = raw_input("hex_a... | |
Solve problem 2 in Python | def is_palindrome(number):
reversed_number = 0
n = number
while(n):
reversed_number = reversed_number * 10 + (n % 10)
#print("reversed_number:", reversed_number)
n //= 10
#print("n:", n)
return number == reversed_number
largest_palindrome = -1
for i in range(100, 1000):
#print("i:", i)
... | |
Add directory for tests of removing unit rules | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 24.08.2017 11:32
:Licence GNUv3
Part of grammpy-transforms
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.