commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3
values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
1c2ba73eb0405dcfd427574c197e6a0588390f67 | Simplify shipping template tags | oscar/templatetags/shipping_tags.py | oscar/templatetags/shipping_tags.py | from django import template
register = template.Library()
@register.assignment_tag
def shipping_charge(method, basket):
"""
Template tag for calculating the shipping charge for a given shipping
method and basket, and injecting it into the template context.
"""
return method.calculate(basket)
@... | from django import template
register = template.Library()
@register.tag
def shipping_charge(parse, token):
"""
Template tag for calculating the shipping charge for a given shipping
method and basket, and injecting it into the template context.
"""
return build_node(ShippingChargeNode, token)
@... | Python | 0 |
3ef6a9dbe2916d669d3e7e7cfab86a365237bc19 | Make octane result format match the old v8_benchmark output. | tools/perf/perf_tools/octane.py | tools/perf/perf_tools/octane.py | # 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.
from telemetry import multi_page_benchmark
from telemetry import util
class Octane(multi_page_benchmark.MultiPageBenchmark):
def MeasurePage(self, _, ... | # 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.
from telemetry import multi_page_benchmark
from telemetry import util
class Octane(multi_page_benchmark.MultiPageBenchmark):
def MeasurePage(self, _, ... | Python | 0.999996 |
238f5788211ed117ceedbb234e7404bc02716d60 | add serializer.py | apps/zblog/serializers.py | apps/zblog/serializers.py |
from rest_framework import serializers
# Serializers define the API representation.
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Article
#fields = ('title', 'content', 'hits', 'created_time', 'updated_time', 'category', 'tags')
fields = ('title', 'co... | Python | 0.000004 | |
9bf9e9ace12fe43c18ef1676681b3b6f5df65d4c | Add example for comparison of two sets of trees based on extracted morphometrics | examples/comparison.py | examples/comparison.py | # Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | Python | 0.000002 | |
4e962d97b6a9d97db915c92c5a388a3a36573d63 | add 32 | p032.py | p032.py | import itertools
matches = set()
for i in itertools.permutations('123456789', 9):
for s in xrange(1, 4):
for s2 in xrange(s + 1, (14 - s) / 2):
a = int(''.join(i[:s]))
b = int(''.join(i[s:s2]))
c = int(''.join(i[s2:]))
if a * b == c:
matches.a... | Python | 0.999999 | |
691a5873596c487eece704bad991270c6b275dde | Create Game_of_Master_Mind.py | Cracking_Coding_Interview/Game_of_Master_Mind.py | Cracking_Coding_Interview/Game_of_Master_Mind.py | class Result:
def __init__(self):
self.hit = 0
self.pseudohit = 0
def estimate(guess, solution):
if len(guess) != len(solution): return None
result = Result()
idict = {}
for i, char in enumerate(guess):
if char == solution[i]:
result.hit += 1
else:
... | Python | 0.000001 | |
b5906545121d4d5229552d3e2243a290810d1c1c | add self-connect.py | python/self-connect.py | python/self-connect.py | #!/usr/bin/python
import errno
import socket
import sys
import time
if len(sys.argv) < 2:
print "Usage: %s port" % sys.argv[0]
print "port should in net.ipv4.ip_local_port_range"
else:
port = int(sys.argv[1])
for i in range(65536):
try:
sock = socket.create_connection(('localhost', port))
print "connected... | Python | 0.000001 | |
6c16f074f273c2f040c3eadcf34307b2fbef4cda | Add transformers.py | python/transformers.py | python/transformers.py | # -*- encoding: utf-8 -*-
import weechat
import re
stripFormatting = re.compile(r"|\d{0,2}(,\d{0,2})?")
script = {
"name": "transformers",
"author": "KamiyamaKiriko",
"version": "0.2",
"license": "MIT",
"description": "Fancily fancify your fancy messages",
}
replacements = {
":V": u"<̈",
... | Python | 0.000047 | |
d4151bf2a30fc8a497f7d4cb3f6eba4b6913447e | Create tester.py | tester.py | tester.py | print("hey!")
| Python | 0.000002 | |
2d5fa61c1edc91621befe54d7fd08642f67b68f8 | add jar_dir | recipes/pilon/pilon.py | recipes/pilon/pilon.py | #!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
#
# Program Parameters
#
import os
import... | #!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
#
# Program Parameters
#
import os
import... | Python | 0.000003 |
e1ceaa62c7e6f0974b21a23105280da49e9657bf | Send push notifications | regrowl/bridge/push.py | regrowl/bridge/push.py | """
Send push notifications
Uses pushnotify to send notifications to iOS and Android devices
Requires https://pypi.python.org/pypi/pushnotify
Sample config
[regrowl.bridge.push]
label = prowl,<apikey>
other = nma,<apikey>
example = pushover,<apikey>
"""
from __future__ import absolute_import
try:
import pushn... | Python | 0 | |
f423a32dac3b3232a03e6eebdb0664d2b5cdf87e | Add test for ordinal | tests/app/utils/test_time.py | tests/app/utils/test_time.py | from app.utils.time import make_ordinal
class WhenMakingOrdinal:
def it_returns_an_ordinal_correctly(self):
ordinal = make_ordinal(11)
assert ordinal == '11th'
| Python | 0.000418 | |
5647dfbf3aa2b2c5cb7f32b60b21a47ad2ee6f20 | add google foobar exercise | solution_level1.py | solution_level1.py | #!/usr/bin/env python
# encoding: utf-8
def answer(s):
re = ''
a = ord('a')
z = ord('z')
for c in s:
ascii_code = ord(c)
if ascii_code >= a and ascii_code <= z:
tmp = chr(a + z -ascii_code)
re = re + tmp
else:
re = re + c
return re
if __... | Python | 0.000001 | |
34dca8c90ba650356c19ff7c42d19f09a050bd64 | Add file from previous commit | translatorsdesk/worker_functions.py | translatorsdesk/worker_functions.py | import subprocess
from rq import Queue
from redis import Redis
redis_conn = Redis()
q = Queue(connection=redis_conn)
#=================================================================
# Process Input File
def extract_xliff(file):
cmd = ["lib/okapi/tikal.sh", "-x", file]
p = subprocess.Popen(cmd, stdout = subproces... | Python | 0 | |
e1b23ecf168d397da373c4441c67e655da58e3e9 | Add basic Log class to represent a log record. | source/bark/log.py | source/bark/log.py | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
from collections import MutableMapping
class Log(MutableMapping):
'''Hold individual log data.'''
def __init__(self, *args, **kw):
'''Initialise log.'''
super(Log, self).__init__()
... | Python | 0 | |
8bbc983d6c1b82f5b7a9baed86c374c18894fcea | add mmdet wrapper tests | tests/modeling/test_mmdet.py | tests/modeling/test_mmdet.py | import unittest
from detectron2.layers import ShapeSpec
from detectron2.modeling.mmdet_wrapper import MMDetBackbone, MMDetDetector
try:
import mmdet.models # noqa
HAS_MMDET = True
except ImportError:
HAS_MMDET = False
@unittest.skipIf(not HAS_MMDET, "mmdet not available")
class TestMMDetWrapper(unitte... | Python | 0 | |
6c6214681ee89f2f67b09542fcf7690aa61954b9 | Add maybe_make_dir() | file/maybe_make_dir.py | file/maybe_make_dir.py | import os
# ==============================================================================
# MAYBE_MAKE_DIR
# ==============================================================================
def maybe_make_dir(path):
""" Checks if a directory path exist... | Python | 0.000001 | |
c57bfdfae235e7ed7b5f13922a7fbc64dbd112f1 | Add a missing migration | junction/proposals/migrations/0025_auto_20200321_0049.py | junction/proposals/migrations/0025_auto_20200321_0049.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2020-03-20 19:19
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('proposals', '0024_auto_20170610_1857'),
]
operations = [
migrations.AlterIndexTogether... | Python | 0.013292 | |
0779277486a6812f5b58e1fc1ab6fe1e5dc35559 | add dummy api tests | nc/tests/test_api.py | nc/tests/test_api.py | from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from nc.models import Agency
class AgencyTests(APITestCase):
def test_list_agencies(self):
"""Test Agency list"""
Agency.objects.create(name="Durham")
url = reverse('... | Python | 0.000001 | |
9a983fc4223cedc3c34c53b1241ffc71ac063a5c | Add benchmark | test/bench.py | test/bench.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Spotify AB
#
# 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 ... | Python | 0.000003 | |
9b68ee1e0ffb60ebffe0bb90da2512da4bbbeb99 | add split_from_listobj_and_tuple_it func | utils/split_listobj_and_tuple_it.py | utils/split_listobj_and_tuple_it.py |
def split_from_listobj_and_tuple_it():
return 0 | Python | 0.000018 | |
c6d70585e1266e4008e38548404a0bcffccfcecf | Create websocket server | web_ws.py | web_ws.py | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import asyncio
import os
from aiohttp.web import Application, Response, MsgType, WebSocketResponse
import argparse
import sys
sys.path.append('../')
from pyxdotool.instruction import Instruction
import json
parser = argparse.ArgumentParser(descri... | Python | 0.000001 | |
ece4598e6297ef071b1c928435efb3bee73e3ddb | Backup script. | scripts/backup.py | scripts/backup.py | import json
from app.firebase import db
"""
Backup script for saving contents at the path in Firebase.
"""
def backup(path):
backup = db().child(path).get().val()
with open("out.json", "w") as f: json.dump(backup, f)
if __name__ == '__main__':
# See app/constants for table prefixes and suffixes
path =... | Python | 0 | |
2ad0a7f50b6b120c6e769033037c0e1661d2480d | Add spacer/exp_name.py to generate names for experiments | spacer/exp_name.py | spacer/exp_name.py | #! /usr/bin/env python3
# Name for experiments directory
import sys
import words
import argparse
import os.path
from datetime import datetime
import platform
class ExpNamer(object):
def __init__(self):
self._name = 'exp_name'
self._help = 'Name experiment'
def mk_arg_parser(self, ap):
... | Python | 0.000016 | |
8b467efd1f998d05da0272a284773501f0b330ff | Add a test file which was missing from a recent branch | djangae/tests/test_meta_queries.py | djangae/tests/test_meta_queries.py | from django.db import models
from djangae.test import TestCase
from djangae.contrib import sleuth
class MetaQueryTestModel(models.Model):
field1 = models.CharField(max_length=32)
class PrimaryKeyFilterTests(TestCase):
def test_pk_in_with_slicing(self):
i1 = MetaQueryTestModel.objects.create();
... | Python | 0.000001 | |
62c04b70178f3df8a8c7cbf01de0896d3e808698 | Create __init__.py | mass_mailing_themes_boilerplate/__init__.py | mass_mailing_themes_boilerplate/__init__.py | Python | 0.000429 | ||
615247c28d58fbbff40f5e4122441d77acb19003 | Integrate notification app in settings and add basic structure of files | notification/urls.py | notification/urls.py | from django.conf.urls import url
from link.views import LinkView, LinkReactionView, LinkCommentView
urlpatterns = [
url(r'^$', LinkView.new, name='link_new'),
url(r'^(?P<post_id>[0-9]+)/add/$', LinkView.add, name='link_add'),
url(r'^(?P<post_id>[0-9]+)/react/$', LinkReactionView.react, name='link_react'),... | Python | 0 | |
cbaed75a20be4c4d7c8354a9acda97adcd2f6dc4 | Attempt to decode xattrs from within an AppleDouble file. | contrib/tools/appledouble_xattr.py | contrib/tools/appledouble_xattr.py | #!/usr/bin/env python
##
# Copyright (c) 2010 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | Python | 0.999894 | |
09c9f6ba56890a2a56eaa77eae47cda92a39965e | Add unit tests for test_url | tests/test_units/test_url.py | tests/test_units/test_url.py | import unittest
from repoze.bfg.testing import cleanUp
class TestRouteUrl(unittest.TestCase):
def setUp(self):
cleanUp()
def tearDown(self):
cleanUp()
def _callFUT(self, *arg, **kw):
from pylons.url import route_url
return route_url(*arg, **kw)
def test_with... | Python | 0 | |
ca1cfd2514d382b1187eab880014b6a611d3568d | add some testing for Resources and ResourceAttributesMixin | tests/resource.py | tests/resource.py | import mock
import unittest
import httplib2
import slumber
class ResourceAttributesMixinTestCase(unittest.TestCase):
def test_attribute_fallback_to_resource(self):
class ResourceMixinTest(slumber.ResourceAttributesMixin, slumber.MetaMixin, object):
class Meta:
authentication =... | Python | 0 | |
7f4cfe09a29202475b0941558f8ab722e63cee7e | Add MPL 2.0 to license trove | scripts/migrations/023-add-new-trove-license-category.py | scripts/migrations/023-add-new-trove-license-category.py | import sys
import logging
from ming.orm.ormsession import ThreadLocalORMSession
from allura import model as M
log = logging.getLogger(__name__)
def main():
M.TroveCategory(trove_cat_id=905,
trove_parent_id=14,
shortname='mpl20',
fullname='Mozilla Publi... | Python | 0 | |
07cccdbb7fdc6919503c5b11bca8604e1f7a0d59 | Create roman_numeral_convert.py | projects/roman_numeral_convert.py | projects/roman_numeral_convert.py |
#Roman numerals are: [i v x l c d m]
def stringer (x):
number_string = str(x)
a = number_string[0]
b = number_string[1]
c = number_string[2]
d = number_string[3]
a_list = [ I, II, III, IV, V, VI, VII, VIII, IX]
b_list = [ X, XX, XXX, XL, L, LX, LXX, LXXX, XC]
c_list = [ C, CC, CCC, CD, D, DC, DCC, DCCC... | Python | 0.000383 | |
4e02394f87bec9f73364738550c0b441beb80696 | Build Tower | Codewars/BuildTower.py | Codewars/BuildTower.py | def tower_builder(n_floors):
return [((n_floors - i)*' ' + (2*i - 1)*'*' + (n_floors - i)*' ') for i in range(1,n_floors+1)]
| Python | 0.000001 | |
b17c1bf616ad3bc1d56b106bc8a606866b8f3f1a | Create Knapsack01.py | ap/py/Knapsack01.py | ap/py/Knapsack01.py | '''
You can run it directly to see results.
'''
def knapsack01(sizes, vals, S):
#aux[i][s] is the maximal value given the first (i-1) items under the size limitation: s
aux = [[-1 for _ in range(S + 1)] for _ in vals]
for i in range(len(vals)):
for s in range(S+1):
if i == 0:
... | Python | 0 | |
8ea0238a29fe1e736d110c5ba71b3dbfdc3e4590 | test pathdropcutter | scripts/pathdropcutter_test_1.py | scripts/pathdropcutter_test_1.py | import ocl
import camvtk
import time
import vtk
import datetime
if __name__ == "__main__":
myscreen = camvtk.VTKScreen()
stl = camvtk.STLSurf("../stl/gnu_tux_mod.stl")
print "STL surface read"
myscreen.addActor(stl)
stl.SetWireframe()
stl.SetColor((0.5,0.5,0.5))
polydata = stl.s... | Python | 0 | |
acedeb97935c53d0e7f1e39b2282f8a90bf379ee | add test case | test_flask.py | test_flask.py | from pytest import fixture
from flask import Flask
from flask_slack import Slack
class App(object):
def __init__(self):
self.app = Flask(__name__)
self.app.debug = True
self.slack = Slack(self.app)
self.app.add_url_rule('/', view_func=self.slack.dispatch)
self.client = se... | Python | 0.000059 | |
6beccf0c0b4e7788403415c05ae9f31e6c0a89eb | Add tests for Generalized Procrustes Analysis (GPA) | tests/test_gpa.py | tests/test_gpa.py | import unittest
import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks
import prince
class TestGPA(unittest.TestCase):
# def setUp(self):
def __init__(self):
# Create a list of 2-D circles with different locations and rotations
... | Python | 0 | |
7ab615aa37263a38ca33fd0d9d8b7f7ec37442ca | add tests for low-level 'nacl.c' API | tests/test_raw.py | tests/test_raw.py | # Copyright 2013 Donald Stufft and individual contributors
#
# 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... | Python | 0 | |
f86da5eddec2dd37f4797ea1caf404e8fec82701 | add unit tests for query parsing | test_query.py | test_query.py | from query import parse_query
import copy
default_parsed_query = {
'from': '-24hours',
'to': 'now',
'min': None,
'max': None,
'avg_by': {},
'limit_targets': 500,
'avg_over': None,
'patterns': ['target_type=', 'unit='],
'group_by': ['target_type=', 'unit=', 'server'],
'sum_by': {... | Python | 0 | |
0baca9564c9df7b06645f71abdda0fe3090f46a6 | Add a test-case for lit xunit output | utils/lit/tests/xunit-output.py | utils/lit/tests/xunit-output.py | # Check xunit output
# RUN: %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/test-data
# RUN: FileCheck < %t.xunit.xml %s
# CHECK: <?xml version="1.0" encoding="UTF-8" ?>
# CHECK: <testsuites>
# CHECK: <testsuite name='test-data' tests='1' failures='0'>
# CHECK: <testcase classname='test-data.' name='metrics.ini' time... | Python | 0.999995 | |
aff4fbae6933f33898f1a32511d9e4cc0b44fef5 | Add permissions class (made via builder). | curious/dataclasses/permissions.py | curious/dataclasses/permissions.py | # I'm far too lazy to type out each permission bit manually.
# So here's a helper method.
def build_permissions_class(name: str="Permissions"):
# Closure methods.
def __init__(self, value: int = 0):
"""
Creates a new Permissions object.
:param value: The bitfield value of the permissi... | Python | 0 | |
e818989604ddaf34dd5730cc3b73093744b59a29 | Create themes.py | timpani/themes.py | timpani/themes.py | from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../themes"))
| Python | 0 | |
2e90787a245d6a30c733699a819a1ff888c308b7 | add simple boot script | src/japronto/__main__.py | src/japronto/__main__.py | from argparse import ArgumentParser
from importlib import import_module
import sys
from .app import Application
def main():
parser = ArgumentParser(prog='python -m japronto')
parser.add_argument('--host', dest='host', type=str, default='0.0.0.0')
parser.add_argument('--port', dest='port', type=int, defau... | Python | 0 | |
bfa84c54166a606e4c7b587aeb10e5e79a2d0e50 | Add __init__ | tmdb3/__init__.py | tmdb3/__init__.py | #!/usr/bin/env python
from tmdb_api import Configuration, searchMovie, searchPerson, Person, \
Movie, Collection, __version__
from request import set_key
from tmdb_exceptions import *
| Python | 0.000917 | |
8830c0ae6a35a68cdeebdf8a7411e63f60b22c09 | Add script to host release management tools. Currently performs a single task: makes regexes for all JIRAs included in a release by parsing the CHANGES.txt files | dev-tools/scripts/manageRelease.py | dev-tools/scripts/manageRelease.py | # Licensed to the Apache Software Foundation (ASF) 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 ... | Python | 0.000001 | |
772fdb2251b5b8b374f15f43195a5e5f1fe9671e | Create deconvolution.py | trax/layers/deconvolution.py | trax/layers/deconvolution.py | # coding=utf-8
# Copyright 2020 The Trax 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Python | 0.000008 | |
60f5dbe34884683626ca7f045fa79d2c247197fe | add test for class checks | pychecker/pychecker2/tests/class.py | pychecker/pychecker2/tests/class.py | import compiler.ast
class B(compiler.ast.Const):
def x(self):
self.inherited = 1
class A(B):
def __init__(self):
self.x = 1 # define x on A
self.w.q = 1
def f(s, self): # unusual self
print self
s.self = 1
s = 7
... | Python | 0 | |
a5e599f4a7c2f20c4f0ed79366db985cba7ae85e | Add template context debugging templatetag | pylab/website/templatetags/debug.py | pylab/website/templatetags/debug.py | from django import template
register = template.Library()
@register.simple_tag(name='pdb', takes_context=True)
def pdb(context, *args, **kwargs):
import ipdb; ipdb.set_trace()
| Python | 0 | |
e7852c457da3cea0f8a20773cc3a355f559b845e | Update version to 1.7 | src/dashboard/src/main/migrations/0047_version_number.py | src/dashboard/src/main/migrations/0047_version_number.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def data_migration(apps, schema_editor):
Agent = apps.get_model('main', 'Agent')
Agent.objects \
.filter(identifiertype='preservation system', name='Archivematica') \
.update(identifiervalue='Arch... | Python | 0 | |
a4a73ac2e5a15e53a0935987911c5905890bfab8 | Add Overwatch command. | orchard/overwatch.py | orchard/overwatch.py | """Get stats for Overwatch."""
from plumeria.command import commands, CommandError
from plumeria.command.parse import Word
from plumeria.message.lists import build_list
from plumeria.util import http
from plumeria.util.http import BadStatusCodeError
from plumeria.util.ratelimit import rate_limit
GENERAL_STATS = (
... | Python | 0.000001 | |
010dd0366ddb62e52f295ec1648c1bab38f9e437 | move python wrappers to their own file | tremendous/api.py | tremendous/api.py | from tremendous.bindings import lib
from tremendous.bindings import ffi
def apply_format(color, body):
s = lib.apply_format(color, body)
return ffi.string(s)
| Python | 0 | |
69905bbee59bb2f65e389ba3c57d8d80bcd55407 | Fix typo in setup.py | scikits/learn/setup.py | scikits/learn/setup.py | from os.path import join
import warnings
import numpy
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, BlasNotFoundError
config = Configuration('learn',parent_package,top_path)
config.add_subpackag... | from os.path import join
import warnings
import numpy
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, BlasNotFoundError
config = Configuration('learn',parent_package,top_path)
config.add_subpackag... | Python | 0.999224 |
19c5600486ea7bee68eb1098636b21757938d799 | Add is_prime python | math/is_prime/python/is_prime.py | math/is_prime/python/is_prime.py | import math
def is_prime(number):
if number <= 1: return False
if number == 2: return True
if (number % 2) == 0: return False
for i in range(3, int(math.sqrt(number)) +1,2):
if number % 1 == 0: return False
return True
number = input ("Enter number :")
if is_prime(number):
print("It is prime")
else:
... | Python | 0.999978 | |
582128f1061ab74da76d26a366bfd3c8fee8f007 | Add scripts/fill_events.py to generate mock data | scripts/fill_events.py | scripts/fill_events.py | #!/usr/bin/env python
import sys
import os
sys.path.append(os.path.join(os.path.dirname('__file__'), '..', 'src'))
from random import randint
from datetime import datetime, timedelta
from logsandra.model.client import CassandraClient
client = CassandraClient('test', 'localhost', 9160, 3)
today = datetime.now()
ke... | Python | 0.000001 | |
92ed053619e27a538b93e87905c0ccf4599808ae | add a ann investigation script | tests/investigate_ann.py | tests/investigate_ann.py | """Polting everything for investigating ANN.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
from keras.models import model_from_json
from keras import backend as K
import os
from os.path import join
import matplotlib.pyplot as plt
import numpy as np
from snntoolbox.io_utils.plotting import plot_layer_activity
n... | Python | 0 | |
a102fb888b60454d7efbe26e4afb38a59c212769 | Add script to delete spam users. | p3/management/commands/delete_spam_users.py | p3/management/commands/delete_spam_users.py | # -*- coding: utf-8 -*-
""" Delete users creating by spambots.
"""
import logging as log
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from assopy import models as amodels
###
class Command(BaseCommand):
# Options
option... | Python | 0 | |
3ebbdf64ba244097e0c78e229d0c81d393bb4460 | add msct_report file | scripts/msct_report.py | scripts/msct_report.py | import os
import shutil
import glob
from collections import OrderedDict
import msct_report_config
import msct_report_util
import msct_report_image
class Report:
def __init__(self, exists, reportDir):
self.dir = os.path.dirname(os.path.realpath(__file__));
self.reportFolder = reportDir
# T... | Python | 0 | |
8f15a2964c1cbbd85ed8301997c05a38268c79a7 | add script used during position comparison | scripts/pos_compare.py | scripts/pos_compare.py | #!/usr/bin/python
import sys
threshold = 100
for line in sys.stdin:
fields = line.split(' ')
aln_name = fields[0]
true_chr = fields[1]
true_pos = int(fields[2])
aln_chr = fields[3]
aln_pos = int(fields[4])
aln_mapq = int(fields[5])
aln_correct = 1 if aln_chr == true_chr and abs(true_p... | Python | 0.000001 | |
bb2fa19aa09e5687e13dedf40da1c7a2507c4c62 | add script to replace `@` and `.` in slugsin for input to gr1x | examples/slugsin_chars_for_gr1x.py | examples/slugsin_chars_for_gr1x.py | import argparse
def main():
p = argparse.ArgumentParser()
p.add_argument('source', type=str,
help='input file')
p.add_argument('target', type=str,
help='output file')
args = p.parse_args()
with open(args.source, 'r') as f:
s = f.read()
snew = s.rep... | Python | 0 | |
1c615be1d3da720d2d0a1974808e3856cbd9d498 | Create Virgil highlevel api implementation | virgil_sdk/api/virgil_api.py | virgil_sdk/api/virgil_api.py | # Copyright (C) 2016 Virgil Security Inc.
#
# Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of ... | Python | 0 | |
cfc37e2556dc018f1150e647253f377c3e8b75ae | Add subtree_sim.py | scripts/subtree_sim.py | scripts/subtree_sim.py | import numpy as np
from cogent import LoadTree
CLI = """
USAGE:
random_subtree <tree> <n>
Subsamples <n> taxa from the Newick tree in <tree>, preserving the branch
lengths of subsampled taxa.
"""
def main(treefile, n):
n = int(n)
tree = LoadTree(
with open(treefile) as trees:
for tree in tre... | Python | 0.000008 | |
74d7be1a5bc061b7feb8713eb1a35dfca2c168a5 | add test for snakemake rules | micronota/rules/tests/test_rules.py | micronota/rules/tests/test_rules.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... | Python | 0 | |
e81bfc0ddcfdc321af0608d553b123fa2188de38 | Consolidate implementations | datashape/user.py | datashape/user.py | from __future__ import print_function, division, absolute_import
from datashape.dispatch import dispatch
from .coretypes import *
from .predicates import isdimension
from .util import dshape
import sys
from datetime import date, time, datetime
__all__ = ['validate', 'issubschema']
basetypes = np.generic, int, float... | from __future__ import print_function, division, absolute_import
from datashape.dispatch import dispatch
from .coretypes import *
from .predicates import isdimension
from .util import dshape
import sys
from datetime import date, time, datetime
__all__ = ['validate', 'issubschema']
basetypes = np.generic, int, float... | Python | 0.000008 |
5d0c16c877fb445114d2b77ee7a4d14686320688 | Add Python solution for day 19 | day19/solution.py | day19/solution.py | import re
data = open("data", "r").read()
possibleReplacements = {}
possibleReverseReplacements = {}
for replacement in data.split("\n"):
lhs, rhs = replacement.split(" => ")
if lhs in possibleReplacements:
if rhs not in possibleReplacements[lhs]:
possibleReplacements[lhs].append(rhs)
else:
possibleReplace... | Python | 0 | |
cdfdf0646151c54001ccbc80eca5c0e8f83ff38a | add tests for Compose class | rhcephcompose/tests/test_compose.py | rhcephcompose/tests/test_compose.py | import os
import time
from rhcephcompose.compose import Compose
from kobo.conf import PyConfigParser
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class TestCompose(object):
conf_file = os.path.join(FIXTURES_DIR, 'basic.conf')
conf = PyConfigParser... | Python | 0.000001 | |
885bf944b7839e54a83ce0737b05ff11fa7d3d86 | Create selfTest.py | searchSort/selfTest.py | searchSort/selfTest.py | from random import randrange, shuffle
def quick_sort(collection, low, high):
if low < high:
p = partition(collection, low, high)
quick_sort(collection, low, p)
quick_sort(collection, p + 1, high)
def partition(collection, low, high):
pivot = collection[(low + high) // 2]
low -= 1... | Python | 0.000002 | |
20d1a1784f0831c14e6e03bbb86f5b8dd5ae49ea | Create learn.py | smalltwo/learn.py | smalltwo/learn.py | Python | 0 | ||
6090dc1539bd0701381c73128a5ca0606adc09e4 | Add SSDP unit test case (init) | tests/utils/test_ssdp.py | tests/utils/test_ssdp.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Bo Maryniuk <bo@suse.de>`
'''
from __future__ import absolute_import, print_function, unicode_literals
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch)
# Import Salt libs
imp... | Python | 0 | |
b6d3ab372f57ad9e3c8427ba8bc211136bc1037b | Set version to 0.1.9a1 | src/powerdns_manager/__init__.py | src/powerdns_manager/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of django-powerdns-manager.
#
# django-powerdns-manager is a web based PowerDNS administration panel.
#
# Development Web Site:
# - http://www.codetrax.org/projects/django-powerdns-manager
# Public Source Code Repository:
# - https://source.codetrax.org/hgroot/dja... | # -*- coding: utf-8 -*-
#
# This file is part of django-powerdns-manager.
#
# django-powerdns-manager is a web based PowerDNS administration panel.
#
# Development Web Site:
# - http://www.codetrax.org/projects/django-powerdns-manager
# Public Source Code Repository:
# - https://source.codetrax.org/hgroot/dja... | Python | 0.001588 |
70b4afc095873ad226947edc757cbc4d29daf44a | Add test_incomplete_write.py test to reproduce #173 | functests/test_incomplete_write.py | functests/test_incomplete_write.py | from __future__ import print_function
import os
import sys
import socket
import datetime
import time
import akumulid_test_tools as att
import json
try:
from urllib2 import urlopen
except ImportError:
from urllib import urlopen
import traceback
import itertools
import math
HOST = '127.0.0.1'
TCPPORT = 8282
HTTP... | Python | 0 | |
67328984667246325244c0eaba75de7413c3079f | add fibonacci example in redid-example | example/redis-example/Fibonacci.py | example/redis-example/Fibonacci.py | # import redis driver
import redis
import pymongo
# import python-cache pycache package
from pycache.Adapter import RedisItemPool
from pycache.Adapter import MongoItemPool
from pycache import cached
client = redis.Redis(host='192.168.99.100', port=32771)
pool = RedisItemPool(client)
mongo_client = pymongo.MongoClien... | Python | 0.000133 | |
e39415fbe6a325894abb8d098504150b1c515b57 | Create split-linked-list-in-parts.py | Python/split-linked-list-in-parts.py | Python/split-linked-list-in-parts.py | # Time: O(n)
# Space: O(n)
# Given a chemical formula (given as a string), return the count of each atom.
#
# An atomic element always starts with an uppercase character,
# then zero or more lowercase letters, representing the name.
#
# 1 or more digits representing the count of that element may follow if the count i... | Python | 0.000003 | |
4709a38f67c80c1516b4eae6eb7d8f54cdd985e2 | Create songsched.py | Songsched/songsched.py | Songsched/songsched.py | Python | 0.000001 | ||
9beaa2052b4e47a2fd075f4d9b7988b03a38a8ad | Create main.py | main.py | main.py | import optparse, settings
def main():
parser = optparse.OptionParser()
parser.add_option('-c',
'--charity',
dest='charity',
default=None,
action="store_true",
help='Sets whether you accept rewardl... | Python | 0.000001 | |
c36f36555b8fba183220456e51e04ccbaa08bb60 | add a data file to play with. | cno/data/ToyMMB/__init__.py | cno/data/ToyMMB/__init__.py | from cellnopt.core import XMIDAS, CNOGraph
pknmodel = CNOGraph("PKN-ToyMMB.sif")
data = XMIDAS("MD-ToyMMB.csv")
description = open("README.rst").read()
| Python | 0 | |
c1ef15e895d4f79a9ef5c83aa13964d30bc8dbff | Add main loop | main.py | main.py | from Board import *
from Player import *
def main():
board = Board()
players = (HumanPlayer('x', board), HumanPlayer('o', board))
turnNum = 0
currentPlayer = None
while not board.endGame():
currentPlayer = players[turnNum % 2]
print "%s's turn" % currentPlayer
currentPlayer.... | Python | 0 | |
9f0820f2ce03580b6f902eded043eb825b38dd4b | Add module to illuminati package for stitching functionality | tmt/illuminati/stitch.py | tmt/illuminati/stitch.py | import numpy as np
def guess_stitch_dims(max_position, more_rows_than_columns=True):
'''
Simple algorithm to guess correct dimensions of a stitched mosaic image.
Parameters
----------
max_position: int
maximum position in the stitched mosaic image
more_rows_than_columns: bool, optiona... | Python | 0 | |
f31b42ae43e7cd2af53a504c1cc2ab398bf7810d | Add api call for Premier League standings | main.py | main.py | import json
import requests
from tabulate import tabulate
BASE_URL = "http://api.football-data.org/alpha/"
soccer_seasons = "soccerseasons/"
epl_current_season = "soccerseasons/398/"
league_table = "leagueTable/"
def print_standings(table):
standings = []
for team in table:
entry = [team['position'], team['team... | Python | 0 | |
c1d5dca7c487075229b384585e0eb11cd91bbef8 | add import script for Chesterfield | polling_stations/apps/data_collection/management/commands/import_chesterfield.py | polling_stations/apps/data_collection/management/commands/import_chesterfield.py | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000034'
addresses_name = 'May 2017/ChesterfieldDemocracy_Club__04May2017a.txt'
stations_name = 'May 2017/ChesterfieldDemocracy_Club__04May2017a.txt'
ele... | Python | 0 | |
04155a80531e58422253e22635f1e496a27a5647 | add import script for South Ribble | polling_stations/apps/data_collection/management/commands/import_south_ribble.py | polling_stations/apps/data_collection/management/commands/import_south_ribble.py | from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = 'E07000126'
addresses_name = 'Properties.csv'
stations_name = 'Polling Stations.csv'
elections = ['local.lancashire.2017-0... | Python | 0 | |
e0d728519292377915983385285a3560d3207b19 | Create main.py | main.py | main.py | import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.write('Hello world!')
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
| Python | 0.000001 | |
99b4a6fa8eb96f9228635142d2686b9601f293b5 | Put main.py back | main.py | main.py | import wysiweb
import shutil
try:
shutil.rmtree('./frozen')
except:
pass
# site_path: Where are the files that will build the website
# static_path: where are the static files? has to be within site_path
# static_route: what is the route to access static files: <a href="/static/logo.jpg"> for instance.
w = wy... | Python | 0.000001 | |
62df41780706161c4e25f854de0b6cc5d2664a39 | Add test for templates in include_router path (#349) | tests/test_router_prefix_with_template.py | tests/test_router_prefix_with_template.py | from fastapi import APIRouter, FastAPI
from starlette.testclient import TestClient
app = FastAPI()
router = APIRouter()
@router.get("/users/{id}")
def read_user(segment: str, id: str):
return {"segment": segment, "id": id}
app.include_router(router, prefix="/{segment}")
client = TestClient(app)
def test_g... | Python | 0 | |
9123b90f21fc341cbb2e333eb53c5149dfda8e3b | Add Taiwan time transformed. | cttwt.py | cttwt.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Toomore Chiang, http://toomore.net/
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without... | Python | 0 | |
4b7fb1ad3cd03e0593ecd3d0626bca385fb2800d | Add scroller example. | examples/scroller/scroller.py | examples/scroller/scroller.py | # coding=utf8
#
# python-aosd -- python bindings for libaosd
#
# Copyright (C) 2010 Armin Häberling <armin.aha@gmail.com>
#
# Based on the scroller example from libaosd.
#
import sys
import aosd
def scroll(osd, width, height):
pos = 8
step = 3
osd.set_position(pos, width, height)
(x, y, _, _) =... | Python | 0 | |
a9fee0cab6899effa865c73c38baf73e5272d87e | Create main.py | main.py | main.py | ### Command line interface for functions
import freqs
import harmonize
import error
import enharmonic
import voice
# 1. Take input from file or user
# 2. Call desired function on input, specifying type of output (show, save to file, etc.)
# 3. Display result
| Python | 0.000001 | |
370d6eb7fc4adb2f2769bdf94f56df239760ef0c | Create quiz2.py | laboratorio-f/quiz2.py | laboratorio-f/quiz2.py | print("OFERTAS El Emperador")
ofer1 = 0.30
ofer2 = 0.20
ofer3 = 0.10
while clientes <5:
monto = int(input("Ingrese monto: "))
clientes += 1
if monto >= 500:
subtotal = monto * ofer1
total = monto - subtotal
print("El total es {0}: ".format(total)
if monto < 500 or monto > 200
subtotal = monto * ofer... | Python | 0.000001 | |
4cff94d70f25ab8abd446ce290167dd0be97c80f | Add basic unit tests for all object-level feature extraction functions (#428) | plugin_tests/feature_extraction_test.py | plugin_tests/feature_extraction_test.py | from tests import base
import os
import sys
import numpy as np
import skimage.io
import skimage.measure
import collections
import histomicstk.preprocessing.color_normalization as htk_cnorm
import histomicstk.preprocessing.color_deconvolution as htk_cdeconv
import histomicstk.features as htk_features
sys.path.append... | Python | 0 | |
c8e6fce132d1eaa9d789dd0c7bd2e5c53e4e5424 | Add python user exception function example (#2333) | pulsar-functions/python-examples/user_exception.py | pulsar-functions/python-examples/user_exception.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) 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
# "... | Python | 0 | |
3aaee714d59650f36e3918e184905048a83d1cfc | Add new filesystem_stat module. | lib/filesystem_stat.py | lib/filesystem_stat.py | import os
import stat
import snmpy
import time
class filesystem_stat(snmpy.plugin):
def s_type(self, obj):
if stat.S_ISDIR(obj):
return 'directory'
if stat.S_ISCHR(obj):
return 'character special device'
if stat.S_ISBLK(obj):
return 'block special device'... | Python | 0 | |
7ac6007e28740e0aff89925b10ae09fa6c0b63d3 | add tests for g.current_user | backend/geonature/tests/test_users_login.py | backend/geonature/tests/test_users_login.py | import pytest
from flask import g, url_for, current_app
from geonature.utils.env import db
from pypnusershub.db.models import User, Application, AppUser, UserApplicationRight, ProfilsForApp
from . import login, temporary_transaction
from .utils import logged_user_headers
@pytest.mark.usefixtures("client_class", "... | Python | 0.000001 | |
205bbba27a89e6f89e26164dbf25ce9763865d36 | add ping.py | ping.py | ping.py | #!/usr/bin/env python
# -*- coding:utf8 -*-
import Queue
import threading
import subprocess
import re
import sys
lock = threading.Lock()
def getip(ip):
a = re.match(r'(.*\d+)\.(\d+)-(\d+)',ip)
print a.groups()
start = int(a.group(2))
end = int(a.group(3))+1
iplist = []
for i in range(start,end... | Python | 0.000003 | |
1266fd79369634e2a0399e857107487ae589ea20 | add vpc vpc check script | plugins/aws/check_vpc_vpn.py | plugins/aws/check_vpc_vpn.py | #!/usr/bin/python
import argparse
import boto.ec2
from boto.vpc import VPCConnection
import sys
def main():
try:
conn = boto.vpc.VPCConnection(aws_access_key_id=args.aws_access_key_id, aws_secret_access_key=args.aws_secret_access_key, region=boto.ec2.get_region(args.region))
except:
print "UN... | Python | 0 | |
2d6d5c0a07a751a66c3f0495e3a3a67e4296dd77 | Create subreddits_with_zero_gildings.py | subreddits_with_zero_gildings.py | subreddits_with_zero_gildings.py | # Written by Jonathan Saewitz, released March 26th, 2016 for Statisti.ca
# Released under the MIT License (https://opensource.org/licenses/MIT)
import json, plotly.plotly as plotly, plotly.graph_objs as go
########################
# Config #
########################
graph_title="Largest Subreddits Who ... | Python | 0.00012 | |
8230ac3c1d6a56ed87fb22f5e13f9798be3aaf9b | add LineNotify.py | python/LineNotify.py | python/LineNotify.py | # -*- coding: utf-8 -*-
"""
author : JianKai Wang
description : send info to the specific line group
date : Dec 2017
Line Notify : https://notify-bot.line.me
document :
* line sticker : https://devdocs.line.me/files/sticker_list.pdf
Notice :
* Add the official account (LINE Notify) into the group
receiving the noti... | Python | 0.000001 | |
29e18ed63177dbe8306a22e3c0583342f4591464 | Exit routine for a controlled exit from ample | python/ample_exit.py | python/ample_exit.py | '''
Created on Mar 18, 2015
@author: jmht
'''
import logging
import sys
import traceback
# external imports
try: import pyrvapi
except: pyrvapi=None
def exit(msg):
logger = logging.getLogger()
#header="**** AMPLE ERROR ****\n\n"
header="*"*70+"\n"
header+="*"*20 + " "*10 + "AMPLE ERROR" + " "*1... | Python | 0 | |
fa3450a44621fab4a9a2f2ed1599d08f66860f70 | Integrate densities to check normalization | integrate_density.py | integrate_density.py | import argparse
import numpy as np
import h5py
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Integrate probability ' +
'densities to verify that they are ' +
'normalized')
parser.add_argument('data_filenames',... | Python | 0 | |
72a573c24d5234003b9eeb9e0cc487d174908a2e | Add a Trie for storage of data string tokens. | typeahead_search/trie.py | typeahead_search/trie.py | """A Trie (prefix tree) class for use in typeahead search.
Every node in the TypeaheadSearchTrie is another TypeaheadSearchTrie instance.
"""
from weakref import WeakSet
class TypeaheadSearchTrie(object):
def __init__(self):
# The children of this node. Because ordered traversals are not
# impor... | Python | 0 | |
e5dd1722911e580caca136fda9b81bb53221c65c | add table widget | ubuntui/widgets/table.py | ubuntui/widgets/table.py | # Copyright 2014, 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is dist... | Python | 0 | |
51fc613214f20738270f37280fb465aea84ed065 | test the wsgi logging | test/test_slimta_logging_wsgi.py | test/test_slimta_logging_wsgi.py |
import unittest
from testfixtures import log_capture
from slimta.logging import getWsgiLogger
class TestWsgiLogger(unittest.TestCase):
def setUp(self):
self.log = getWsgiLogger('test')
self.environ = {'var': 'val'}
@log_capture()
def test_request(self, l):
self.log.request(sel... | Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.