commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
3373521f43b0d605bba6cc36b190c064d5a0303e | kytos/core/link.py | kytos/core/link.py | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
... | """Module with all classes related to links.
Links are low level abstractions representing connections between two
interfaces.
"""
import json
from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoi... | Define Link ID as UUID | Define Link ID as UUID
| Python | mit | kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos |
b6da3311c894ad502b32b1cb96c3b0e0a02b0b85 | blog/views.py | blog/views.py | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list, 5)
page = request.GET.get('... | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404
from django.shortcuts import render
from .models import Blog
# Create your views here.
def index(request):
blogs_list = Blog.objects.filter(published=True).order_by('-dateline')
paginator = Paginator(blogs_list... | Handle blogs with a bad URL slug | Handle blogs with a bad URL slug
| Python | bsd-3-clause | brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3,brendan1mcmanus/whartonfintech-v3 |
f01c6d22d30e175d120e5ffe10bef93378375ea7 | example/myshop/models/__init__.py | example/myshop/models/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import Ca... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
# import default models from djangoSHOP to materialize them
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.defaults.cart import Cart
from shop.models.defaults.cart_item import Ca... | Use __all__ for restricted exports | Use __all__ for restricted exports
| Python | bsd-3-clause | jrief/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,khchine5/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,awesto/django-shop,jrief/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-sho... |
e92784a36053e6708a3eb2772f4c5cd4e16cde4a | app/base/templatetags/git.py | app/base/templatetags/git.py | import subprocess
from django.template import Library
register = Library()
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
VERSION = head.stdout.readline().strip()
except:
VERSION = u'unknown'
@register.simple_tag()
def git... | import subprocess
from django.template import Library
register = Library()
GIT_VERSION = None
@register.simple_tag()
def git_version():
global GIT_VERSION
if GIT_VERSION:
return GIT_VERSION
try:
head = subprocess.Popen("git rev-parse --short HEAD",
shell... | Make GIT_VERSION on footer more robust | [REFACTOR] Make GIT_VERSION on footer more robust
| Python | mit | internship2016/sovolo,internship2016/sovolo,internship2016/sovolo |
59dd1dd68792b13ea75b4aaffc68983236d02ad3 | config/urls.py | config/urls.py | """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """ohmycommand URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | Make sure that we pass a CSRF cookie with value | Make sure that we pass a CSRF cookie with value
We need to pass a CSRF cookie when we make a GET request because
otherwise Angular would have no way of grabing the CSRF.
| Python | mit | gopar/OhMyCommand,gopar/OhMyCommand,gopar/OhMyCommand |
269670c239339bb26b61e2f9dcf0a4110b80f828 | exec_thread_1.py | exec_thread_1.py | #import spam
import filter_lta
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print THREAD_FILES
def main():
for i in THREAD_FILES:
LTA_FILES = os.chdir(... | #import spam
import filter_lta
import os
#List of all directories containing valid observations
VALID_FILES = filter_lta.VALID_OBS()
#List of all directories for current threads to process
THREAD_FILES = VALID_FILES[0:len(VALID_FILES):5]
print 'Executing this thread'
os.system('pwd')
def main():
for i in THREAD... | Add code to test running thread | Add code to test running thread
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu |
bea43abce031ab70a1f4e59e5c1e4a00af37a406 | fancypages/assets/forms/fields.py | fancypages/assets/forms/fields.py | from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
default_fields = {
'asset_pk': IntegerField,... | from django.core import validators
from django.db.models import get_model
from django.forms.fields import MultiValueField, CharField, IntegerField
from .widgets import AssetWidget
class AssetField(MultiValueField):
_delimiter = ':'
widget = AssetWidget
pk_field_name = 'id'
default_fields = {
... | Use default PK field name for Asset form field | Use default PK field name for Asset form field
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages |
64d9a15f84257988b371a2d12f1137f7b9f41b02 | python/009_palindrome_number.py | python/009_palindrome_number.py | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if ... | """
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if ... | Revise 009, add test cases | Revise 009, add test cases
| Python | mit | ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln |
0d84bed2f1254887c7e352a6b173b7f554dac5f7 | timepiece/context_processors.py | timepiece/context_processors.py | from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
... | from django.conf import settings
from timepiece import models as timepiece
from timepiece.forms import QuickSearchForm
def timepiece_settings(request):
default_famfamfam_url = settings.STATIC_URL + 'images/icons/'
famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url)
context = {
... | Check request.user before using it | Check request.user before using it
| Python | mit | josesanch/django-timepiece,josesanch/django-timepiece,dannybrowne86/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,gaga3966/django-timepiece,gaga3966/django-timepiece,BocuStudio/django-timepiece,dannybrowne86/django-timepiece,gaga3966/django-timepiece,josesanch/django-timepiece,dannybrowne86/django... |
cb0c4b7af5efc16d1ca5da9722d9e29cae527fec | acme/utils/signals.py | acme/utils/signals.py | # Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | Fix pytype issue in signal handling code. | Fix pytype issue in signal handling code.
PiperOrigin-RevId: 408605103
Change-Id: If724504629a50d5cb7a099cf0263ba642e95345d
| Python | apache-2.0 | deepmind/acme,deepmind/acme |
1db5fefc1752b71bf11fbf63853f7c93bcc526f5 | tests/macaroon_property_tests.py | tests/macaroon_property_tests.py | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
ascii_text_stategy = strategy(text_type).map(
lambda s: s.encode('ascii', 'ignore')
)... | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampl... | Improve strategies in property tests | Improve strategies in property tests
| Python | mit | matrix-org/pymacaroons,matrix-org/pymacaroons,ecordell/pymacaroons,illicitonion/pymacaroons |
6e8f35b83fc563c8349cb3be040c61a0588ca745 | rplugin/python3/LanguageClient/logger.py | rplugin/python3/LanguageClient/logger.py | import logging
logger = logging.getLogger("LanguageClient")
fileHandler = logging.FileHandler(filename="/tmp/LanguageClient.log")
fileHandler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S"))
logger.addHandler(fileHandler)
logger.setLevel(logging.WARN)
| import logging
import tempfile
logger = logging.getLogger("LanguageClient")
with tempfile.NamedTemporaryFile(
prefix="LanguageClient-",
suffix=".log", delete=False) as tmp:
tmpname = tmp.name
fileHandler = logging.FileHandler(filename=tmpname)
fileHandler.setFormatter(
logging.Formatter(
... | Use tempfile lib for log file | Use tempfile lib for log file
The fixed name for the log file causes issues for multiple users. The
tempfile library will create temporary files that don't conflict.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... |
1a8f67ec1eaa97aebe25d7d6625a237f8e1ce151 | example/tests/integration/test_includes.py | example/tests/integration/test_includes.py | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.conte... | import pytest
from django.core.urlresolvers import reverse
from example.tests.utils import load_json
pytestmark = pytest.mark.django_db
def test_included_data_on_list(multiple_entries, client):
response = client.get(reverse("entry-list") + '?include=comments&page_size=5')
included = load_json(response.conte... | Fix for test included_data_on_list included types check | Fix for test included_data_on_list included types check
| Python | bsd-2-clause | django-json-api/rest_framework_ember,scottfisk/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-fr... |
382b8df7a25732ee8384c02d776472a93c18a0ea | vcspull/__about__.py | vcspull/__about__.py | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__pypi__ = 'https://pypi.org/project/vcspull/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyrig... | __title__ = 'vcspull'
__package_name__ = 'vcspull'
__description__ = 'synchronize your repos'
__version__ = '1.2.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/vcspull'
__docs__ = 'https://vcspull.git-pull.com'
__tracker__ = 'https://github.com/vcs-python/vcspull/issues'
__pypi__ = 'https://... | Add docs / tracker to metadata | Add docs / tracker to metadata
| Python | mit | tony/vcspull,tony/vcspull |
d1cc22a5ab94b6df503679cc8b6a19948f4049c9 | maildump/web_realtime.py | maildump/web_realtime.py | from flask import current_app
from gevent.queue import Queue
clients = set()
def broadcast(event, data=None):
for q in clients:
q.put((event, data))
def handle_sse_request():
return current_app.response_class(_gen(), mimetype='text/event-stream')
def _gen():
yield _sse('connected')
q = Qu... | from flask import current_app
from gevent.queue import Empty, Queue
clients = set()
def broadcast(event, data=None):
for q in clients:
q.put((event, data))
def handle_sse_request():
return current_app.response_class(_gen(), mimetype='text/event-stream')
def _gen():
yield _sse('connected')
... | Send regular ping on SSE channel | Send regular ping on SSE channel
Otherwise dead clients stay around for a very long time (they are
only detected and removed when sending data fails, and that used to
depend on new emails arriving).
| Python | mit | ThiefMaster/maildump,ThiefMaster/maildump,ThiefMaster/maildump,ThiefMaster/maildump |
be67ff47938be435f1eb713ed1c9b08f3f98bc5b | number_to_words.py | number_to_words.py | class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine',... | class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine',... | Add condition to handle the case when `number` is 0 | Add condition to handle the case when `number` is 0 | Python | mit | ianfieldhouse/number_to_words |
ab3d830ca682805180710bf1aeb79519c826a7f0 | frontend.py | frontend.py | from flask import Flask
from flask import render_template
import requests
import json
app = Flask(__name__)
@app.route('/')
def index():
r = requests.get("http://127.0.0.1:5000/playlist")
playlist = json.loads(r.text)
return render_template('index.html', playlist=playlist)
@app.route('/settings')
def s... | from flask import Flask
from flask import render_template
import requests
import json
app = Flask(__name__)
@app.route('/')
def index():
r = requests.get("http://127.0.0.1:5000/playlist")
playlist = json.loads(r.text)
return render_template('index.html', playlist=playlist)
@app.route('/settings')
def s... | Add tunein search and use flask new run | Add tunein search and use flask new run
| Python | mit | MCG-Radio/frontend,MCG-Radio/frontend,MCG-Radio/frontend |
d791577e797bdcdabe68ef4999e39d2b2d99a291 | sugar/activity/__init__.py | sugar/activity/__init__.py | import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
def get_default_type(activity_type):
"""Get the activity default type.
It's ... | import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
settings.set_string_property('gtk-font-name', 'Sans 14', '')
def get_default_type... | Set default font size to 14 | Set default font size to 14
| Python | lgpl-2.1 | i5o/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,Daksh/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,godiard/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit... |
d7454240f4f888309a63bba07526a821962c9670 | masters/master.chromium.webrtc.fyi/master_source_cfg.py | masters/master.chromium.webrtc.fyi/master_source_cfg.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 master import gitiles_poller
def Update(config, c):
webrtc_repo_url = config.Master.git_server_url + '/external/webrtc/'
webrtc_poller = gitil... | # 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 master import gitiles_poller
def Update(config, c):
webrtc_repo_url = config.Master.git_server_url + '/external/webrtc/'
webrtc_poller = gitil... | Remove poller for webrtc-samples repo. | WebRTC: Remove poller for webrtc-samples repo.
Having multiple GittilesPollers produces blamelists
with hashes from different repos, but more importantly perf
dashboard links that are not valid, since the from-hash can be
from the Chromium repo and the to-hash from the webrtc-samples repo.
Since breakages by changes ... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
57d4e10636b9593ef650f0f62410f0b0d7effdf2 | test/test_e2e.py | test/test_e2e.py | import h2o
import socket
import threading
import unittest
import urllib.request
SIMPLE_PATH = b'/simple'
SIMPLE_BODY = b'<h1>It works!</h1>'
class E2eTest(unittest.TestCase):
def setUp(self):
config = h2o.Config()
host = config.add_host(b'default', 65535)
host.add_path(SIMPLE_PATH).add_ha... | import h2o
import socket
import threading
import unittest
import urllib.request
SIMPLE_PATH = b'/simple'
SIMPLE_BODY = b'<h1>It works!</h1>'
class E2eTest(unittest.TestCase):
def setUp(self):
config = h2o.Config()
host = config.add_host(b'default', 65535)
host.add_path(SIMPLE_PATH).add_ha... | Fix test under python 3.4 | Fix test under python 3.4
| Python | mit | iceb0y/pyh2o,iceb0y/pyh2o |
89b164781ba433c9209f306889463e189006778c | board.py | board.py | """
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init(self, rows, columns):
self.rows = rows
self.columns = columns
| import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init(self, rows, columns):
self.rows = rows
self.columns = columns
self.boardMatrix = numpy.ze... | Add matrix and addPiece function. | Add matrix and addPiece function.
| Python | mit | isaacarvestad/four-in-a-row |
56da6b0b39fc3b4b9fa5c19ed0738ff526bf5072 | src/sugar/__init__.py | src/sugar/__init__.py | # Copyright (C) 2006-2007, Red Hat, Inc.
# Copyright (C) 2007, One Laptop Per Child
#
# 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 of the License, or (at your option... | # Copyright (C) 2006-2007, Red Hat, Inc.
# Copyright (C) 2007-2008, One Laptop Per Child
#
# 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 of the License, or (at your o... | Use the right gettext domain. | Use the right gettext domain.
| Python | lgpl-2.1 | tchx84/debian-pkg-sugar-base,ceibal-tatu/sugar-base,ceibal-tatu/sugar-base,sugarlabs/sugar-base,ceibal-tatu/sugar-base,tchx84/debian-pkg-sugar-base,sugarlabs/sugar-base,sugarlabs/sugar-base,tchx84/debian-pkg-sugar-base |
e94d40af916fa51e7e8737fd151d8cfc8a94891a | cmsplugin_iframe/models.py | cmsplugin_iframe/models.py | from cms.models import CMSPlugin
from django.db import models
class IframePlugin(CMSPlugin):
src = models.URLField()
| from cms.models import CMSPlugin
from django.db import models
class IframePlugin(CMSPlugin):
src = models.URLField(max_length=400)
| Increase urlfield size from 200 to 500 to deal with large embed urls for google calendar and other embeds | Increase urlfield size from 200 to 500 to deal with large embed urls for google calendar and other embeds
| Python | mit | jonasmcarson/cmsplugin-iframe,jonasmcarson/cmsplugin-iframe |
116e76557d239edab69bab47c96cb5835618c31f | tilenol/xcb/keysymparse.py | tilenol/xcb/keysymparse.py | import re
keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)")
class Keysyms(object):
__slots__ = ('name_to_code', 'code_to_name', '__dict__')
def __init__(self):
self.name_to_code = {}
self.code_to_name = {}
def add_from_file(self, filename):
with open(filename, 'rt') ... | import os
import re
keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)")
class Keysyms(object):
__slots__ = ('name_to_code', 'code_to_name', '__dict__')
def __init__(self):
self.name_to_code = {}
self.code_to_name = {}
def add_from_file(self, filename):
with open(filena... | Allow to override include dir of xproto | Allow to override include dir of xproto
| Python | mit | tailhook/tilenol,tailhook/tilenol |
6f9a2ef636c8ac5272de15ddfeb7c80b3bd00246 | test/test_arena.py | test/test_arena.py | from support import lib,ffi
from qcgc_test import QCGCTest
class ArenaTestCase(QCGCTest):
def test_size_calculations(self):
exp = lib.QCGC_ARENA_SIZE_EXP
size = 2**exp
bitmap = size / 128
cells = (size - 2 * bitmap) / 16
self.assertEqual(size, lib.qcgc_arena_size)
se... | from support import lib,ffi
from qcgc_test import QCGCTest
class ArenaTestCase(QCGCTest):
def test_size_calculations(self):
exp = lib.QCGC_ARENA_SIZE_EXP
size = 2**exp
bitmap = size / 128
cells = size / 16
self.assertEqual(size, lib.qcgc_arena_size)
self.assertEqual(... | Fix wrong cell count calculation | Fix wrong cell count calculation
| Python | mit | ntruessel/qcgc,ntruessel/qcgc,ntruessel/qcgc |
5fd3bed281018a556cfd6305670317bf5acb2a16 | tests/test_auth.py | tests/test_auth.py | import random
import unittest
from .config import *
from tweepy import API, OAuthHandler
class TweepyAuthTests(unittest.TestCase):
def testoauth(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
# test getting access token
auth_url = auth.get_authorization_url()
... | import random
import unittest
from .config import *
from tweepy import API, OAuthHandler
class TweepyAuthTests(unittest.TestCase):
def testoauth(self):
auth = OAuthHandler(consumer_key, consumer_secret)
# test getting access token
auth_url = auth.get_authorization_url()
print('P... | Update consumer key and secret usage in auth tests | Update consumer key and secret usage in auth tests
| Python | mit | svven/tweepy,tweepy/tweepy |
fc08fb4086b3438cbe84042903b855c6fb55c30e | sshuttle/assembler.py | sshuttle/assembler.py | import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
... | import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
global verbosity
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
... | Declare 'verbosity' as global variable to placate linters | Declare 'verbosity' as global variable to placate linters | Python | lgpl-2.1 | sshuttle/sshuttle,sshuttle/sshuttle |
964da81ef5a90130a47ff726839798a7a7b716ef | buildcert.py | buildcert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
with app.app_context():
msg = Message('Freifunk V... | Add app.context() to populate context for render_template | Add app.context() to populate context for render_template
| Python | mit | freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net |
d95eda2f88a8b493e40cd6628c7e532a1f510610 | src/dashboard/src/main/urls.py | src/dashboard/src/main/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template, redirect_to
UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}'
urlpatterns = patterns('dashboard.main.views',
# Ingest
url(r'ingest/$', direct_to_template, {'template': 'main/in... | from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template, redirect_to
UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}'
urlpatterns = patterns('dashboard.main.views',
# Index
(r'^$', redirect_to, {'url': '/ingest/'}),
# Ingest
... | Remove default route because it is not the desired behavior. | Remove default route because it is not the desired behavior.
Autoconverted from SVN (revision:1409)
| Python | agpl-3.0 | artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history |
1a35294baac296bbd665dc55e35cd2b383ae7116 | alembic/versions/87acbbe5887b_add_freeform_profile_for_user.py | alembic/versions/87acbbe5887b_add_freeform_profile_for_user.py | """Add freeform profile for user
Revision ID: 87acbbe5887b
Revises: f2a71c7b93b6
Create Date: 2016-09-11 21:39:20.753000
"""
# revision identifiers, used by Alembic.
revision = '87acbbe5887b'
down_revision = 'f2a71c7b93b6'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def u... | """Add freeform profile for user
Revision ID: 87acbbe5887b
Revises: f2a71c7b93b6
Create Date: 2016-09-11 21:39:20.753000
"""
# revision identifiers, used by Alembic.
revision = '87acbbe5887b'
down_revision = 'f2a71c7b93b6'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def u... | Set default value for user profile data | Set default value for user profile data
| Python | mit | katajakasa/aetherguild2,katajakasa/aetherguild2 |
12a9ef54d82d9508852e5596dbb9df321986e067 | tests/test_heroku.py | tests/test_heroku.py | """Tests for the Wallace API."""
import subprocess
import re
import requests
class TestHeroku(object):
"""The Heroku test class."""
def test_sandbox(self):
"""Launch the experiment on Heroku."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox... | """Tests for the Wallace API."""
import subprocess
import re
import os
import requests
class TestHeroku(object):
"""The Heroku test class."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
os.environ['app_id'] = re.search(
'... | Refactor Heroku tests to have shared setup | Refactor Heroku tests to have shared setup
| Python | mit | Dallinger/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dalli... |
3c66efc142d53a4c8f9f88fb33d942c6840bd343 | tests/test_trivia.py | tests/test_trivia.py |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parenthes... |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_num... | Test large number as response for check_answer | [Tests] Test large number as response for check_answer
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
46807ee4923a5799ec371cd8094c36f0b672f4b4 | common/highlights.py | common/highlights.py | import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id']
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOME... | import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
# Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
# 20 seconds for how long the actual event is...
linkts = timestamp - 45
... | Add timestamp to link too | Add timestamp to link too
| Python | apache-2.0 | andreasots/lrrbot,mrphlip/lrrbot,mrphlip/lrrbot,andreasots/lrrbot,mrphlip/lrrbot,andreasots/lrrbot |
b06f0e17541f7d424e73fd200ae10db0722b1a5a | organizer/views.py | organizer/views.py | from django.shortcuts import (
get_object_or_404, render)
from .forms import TagForm
from .models import Startup, Tag
def startup_detail(request, slug):
startup = get_object_or_404(
Startup, slug__iexact=slug)
return render(
request,
'organizer/startup_detail.html',
{'star... | from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import TagForm
from .models import Startup, Tag
def startup_detail(request, slug):
startup = get_object_or_404(
Startup, slug__iexact=slug)
return render(
request,
'organizer/startup_detail.html',
... | Create and redirect to Tag in tag_create(). | Ch09: Create and redirect to Tag in tag_create().
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
5553dd2aba90749fdedda55067c2010cf1522f54 | mesobox/boxes.py | mesobox/boxes.py | from django.conf import settings
import importlib
# Merge two lots of mesobox-compatible context additions
def merge_context_additions(additions):
context = {}
boxes = {}
for c in additions:
try:
context.update(c.get("context"))
except TypeError:
pass
try:
... | from django.conf import settings
import importlib
# Merge two lots of mesobox-compatible context additions
def merge_context_additions(additions):
context = {}
boxes = {}
for c in additions:
try:
context.update(c.get("context"))
except TypeError:
pass
try:
... | Remove a debugging print that should never have been left there anyway. | Remove a debugging print that should never have been left there anyway.
| Python | mit | grundleborg/mesosphere |
bde51dc314bd920dafd5f72fbc4ccae099f5be59 | tsune/settings/ci.py | tsune/settings/ci.py | from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
#'NAME': 'db.sqlite3',
}
}
INSTALLED_APPS += ('django_jenkins',)
PROJECT_APPS = {
'cardbox',
} | from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
#'NAME': 'db.sqlite3',
}
}
INSTALLED_APPS += ('django_jenkins',)
PROJECT_APPS = {
'cardbox',
'deckglue',
'memorize',
}
| Add deckglue and memorize to django_jenkins | Add deckglue and memorize to django_jenkins
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune |
2492803223060ecf92f8c60a2aa07db8f450e7b1 | get_dev_id.py | get_dev_id.py | from gmusicapi import Mobileclient
# Try to print out some valid device IDs.
if __name__ == '__main__':
api = Mobileclient()
email = input('Enter your email: ')
password = input('Enter your password: ')
if not api.login(email, password, Mobileclient.FROM_MAC_ADDRESS):
print('Login failed, veri... | import getpass
from gmusicapi import Mobileclient
# Try to print out some valid device IDs.
if __name__ == '__main__':
api = Mobileclient()
email = input('Enter your email: ').strip()
assert '@' in email, 'Please enter a valid email.'
password = getpass.getpass('Enter password for {}: '.format(email))... | Secure with getpass(), Simplify with enumerate() | Secure with getpass(), Simplify with enumerate() | Python | mit | christopher-dG/pmcli,christopher-dG/pmcli |
443172dd4f8717f55da8f8a4af1397044f66ccf0 | yunity/users/api.py | yunity/users/api.py | from django.contrib.auth import get_user_model
from rest_framework import filters
from rest_framework import viewsets
from yunity.users.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
filter_backends = ... | from django.contrib.auth import get_user_model
from rest_framework import filters
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, AllowAny, BasePermission
from yunity.users.serializers import UserSerializer
class IsRequestUser(BasePermission):
message = 'You can modify... | Extend Users API to conform to tests | Extend Users API to conform to tests
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend |
20a938892492defb1063a63b12e1aeb5b47c5508 | web/core/models.py | web/core/models.py | from __future__ import unicode_literals
from django.db import models
from django.conf import settings
import django.db.models.signals
import django.dispatch.dispatcher
import web.core
import re
import os
import uuid
class File(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=... | from __future__ import unicode_literals
from django.db import models
from django.conf import settings
import django.db.models.signals
import django.dispatch.dispatcher
import web.core
import re
import os
import uuid
class File(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=... | Remove directories when deleting files | Remove directories when deleting files
| Python | bsd-3-clause | ambientsound/rsync,ambientsound/rsync,ambientsound/rsync,ambientsound/rsync |
d7d9fcb260b85a3f785852239acaea6ccda1725a | what_meta/views.py | what_meta/views.py | from django.core import serializers
from django.http.response import HttpResponse
from what_meta.models import WhatTorrentGroup
def search_torrent_groups(request, query):
return HttpResponse(
serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
content_type='text... | from django.core import serializers
from django.http.response import HttpResponse
from what_meta.models import WhatTorrentGroup
def search_torrent_groups(request, query):
response = HttpResponse(
serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
content_type='... | Support for super simple player. | Support for super simple player.
| Python | mit | grandmasterchef/WhatManager2,davols/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,karamanolev/WhatManager2,karamanolev/W... |
fd516d3b80e63c6883d5eec47a8bf9ff6042509b | pandoc-figref.py | pandoc-figref.py | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('\{#([a-z... | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#(... | Fix error with no space before tag | Fix error with no space before tag
| Python | mit | scotthartley/pandoc-figref |
7642359c1ecf2b5dc38f70924e7c9885739a79c8 | jungle/emr.py | jungle/emr.py | # -*- coding: utf-8 -*-
import boto3
import click
@click.group()
def cli():
"""EMR CLI group"""
pass
@cli.command(help='List EMR clusters')
@click.argument('name', default='*')
def ls(name):
"""List EMR instances"""
client = boto3.client('emr', region_name='us-east-1')
results = client.list_clus... | # -*- coding: utf-8 -*-
import subprocess
import boto3
import click
@click.group()
def cli():
"""EMR CLI group"""
pass
@cli.command(help='List EMR clusters')
@click.argument('name', default='*')
def ls(name):
"""List EMR instances"""
client = boto3.client('emr')
results = client.list_clusters(
... | Add ssh subcommand for EMR | Add ssh subcommand for EMR
| Python | mit | achiku/jungle |
9168abf53be960d1630ec6ecb01c6d8f55d21739 | promotions_app/models.py | promotions_app/models.py | from django.db import models
from authentication_app.models import Account
'''
@name : Promotion
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = mode... | from django.db import models
from authentication_app.models import Account
'''
@name : PromotionManager.
@desc : The PromotionManager is responsible to create, delete and update the promotions.
'''
class PromotionManager(models.Manager):
def create_promotion(self, name, desc, expire_date, image):
... | Add the promotion manager to the promotions app. | Add the promotion manager to the promotions app.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app |
657d2d7e5aaefd2ee3b543ab9eb03f4a91d26d37 | Lib/xml/__init__.py | Lib/xml/__init__.py | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parser -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginso... | """Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Meggins... | Add magic to replace the xml package with _xmlplus at import time. Update docstring to reflect change of name for the parsers subpackage. | Add magic to replace the xml package with _xmlplus at import time.
Update docstring to reflect change of name for the parsers subpackage.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
61f4d269e745a24209e1719049f25dab3e3171a0 | preconditions.py | preconditions.py | class PreconditionError (TypeError):
pass
def preconditions(*precs):
pass # stub.
| class PreconditionError (TypeError):
pass
def preconditions(*precs):
def decorate(f):
def g(*a, **kw):
return f(*a, **kw)
return g
return decorate
| Implement a stub decorator factory. | Implement a stub decorator factory.
| Python | mit | nejucomo/preconditions |
5e1ffdab41c322a9bcd466b34aabaa37ef08a6e2 | profiling_run.py | profiling_run.py | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25]... | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25]... | Make jacobian use more explicit. | Make jacobian use more explicit.
| Python | mit | jensv/fluxtubestability,jensv/fluxtubestability |
845b9b9be9c5a7f0f4e214215854d2d3c05a11f3 | bfg9000/shell/__init__.py | bfg9000/shell/__init__.py | import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(... | import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(... | Fix closing /dev/null when executing in quiet mode | Fix closing /dev/null when executing in quiet mode
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 |
daaf58639148b220d6dcce13e054374a68f9b01a | testfixtures/tests/test_docs.py | testfixtures/tests/test_docs.py | # Copyright (c) 2009 Simplistix Ltd
#
# See license.txt for more details.
import unittest
from glob import glob
from os.path import dirname,join,pardir
from doctest import DocFileSuite,REPORT_NDIFF,ELLIPSIS
options = REPORT_NDIFF|ELLIPSIS
def test_suite():
return unittest.TestSuite((
DocFileSuite(
... | # Copyright (c) 2009 Simplistix Ltd
#
# See license.txt for more details.
from glob import glob
from manuel import doctest,codeblock
from manuel.testing import TestSuite
from os.path import dirname,join,pardir
from doctest import REPORT_NDIFF,ELLIPSIS
def test_suite():
m = doctest.Manuel(optionflags=REPORT_NDIFF... | Use Manuel instead of doctest. | Use Manuel instead of doctest.
| Python | mit | nebulans/testfixtures,Simplistix/testfixtures |
a8726f9acf3d2a1b0287046d0ffb5236892c6535 | tests/django_test_app/models.py | tests/django_test_app/models.py | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 Raphaël Barrois
from django.db import models
from semantic_version import django_fields as semver_fields
class VersionModel(models.Model):
version = semver_fields.VersionField(verbose_name='my version')
spec = semver_fields.SpecField(verbose_name='my spec')
... | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 Raphaël Barrois
try:
from django.db import models
django_loaded = True
except ImportError:
django_loaded = False
if django_loaded:
from semantic_version import django_fields as semver_fields
class VersionModel(models.Model):
version = se... | Fix test running when Django isn't available. | tests: Fix test running when Django isn't available.
| Python | bsd-2-clause | rbarrois/python-semanticversion,marcelometal/python-semanticversion,mhrivnak/python-semanticversion,pombredanne/python-semanticversion |
b8c4d7aabcd07fcba443558a02cdcb38d32009df | pages/tests.py | pages/tests.py | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.l... | from django.test import TestCase
import settings
from pages.models import *
from django.test.client import Client
page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1}
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
... | Add a test for slug collision | Add a test for slug collision
git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@320 439a9e5f-3f3e-0410-bc46-71226ad0111b
| Python | bsd-3-clause | pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,batiste/django-page-cms,batiste/django-page-cm... |
89c906fc0ff6490de07543292c6e1e738652e2ef | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Leonardo Zhou'
SITENAME = u'\u4e91\u7ffc\u56fe\u5357'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = Non... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Leonardo Zhou'
SITENAME = u'\u4e91\u7ffc\u56fe\u5357'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = Non... | Change custom theme settings and url pattern | Change custom theme settings and url pattern
| Python | cc0-1.0 | glasslion/zha,glasslion/zha-beta,glasslion/zha,glasslion/zha-beta,glasslion/zha-beta,glasslion/zha |
0ac40dd99823ccff795361c9e0f49409d9d4d95e | bpython/test/test_keys.py | bpython/test/test_keys.py | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_map(self):
"""Verify KeyMap.map being a dictionary with the correct length."""
self.assertEqual(len(keys.key_dispatch.map), 43)
def test_keymap_setitem(self):
"""Verify ... | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_getitem(self):
"""Verify keys.KeyMap correctly looking up items."""
self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^['))
self.assertEqual(keys.key_dispatch['F11'], ('K... | Add __delitem__, and dict length checking to tests for keys | Add __delitem__, and dict length checking to tests for keys
| Python | mit | myint-archive/bpython,hirochachacha/apython,thomasballinger/old-bpython-with-hy-support |
aedd144895d6ff6da0766d935cd0221985fccca8 | kaf2html.py | kaf2html.py | """Script to generate an HTML page from a KAF file that shows the text contents
including line numbers.
"""
from bs4 import BeautifulSoup
with open('data/minnenijd.kaf') as f:
xml_doc = BeautifulSoup(f)
output_html = ['<html><head>',
'<meta http-equiv="Content-Type" content="text/html; '
... | """Script to generate an HTML page from a KAF file that shows the text contents
including line numbers.
"""
from bs4 import BeautifulSoup
import sys
xml_doc = None
if len(sys.argv) < 2:
print 'Please provide a kaf input file.'
print 'Usage: python kaf2html.py <kaf input>'
s... | Read kaf input from command line argument | Read kaf input from command line argument
The kaf input file used in the script is read from the command line.
| Python | apache-2.0 | NLeSC/embodied-emotions-scripts,NLeSC/embodied-emotions-scripts |
6661c7afe060e21b29483cb01d30473211cef830 | timepiece/urls.py | timepiece/urls.py | from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Redirect the base URL to the dashboard.
url(r'^$', lambda r: HttpResponsePermanentRedirect(reverse('dashboard'))),
url('', i... | from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = patterns('',
# Redirect the base URL to the dashboard.
url(r'^$', RedirectView.as_view(url=reverse_lazy('dashboard')),
url('', include('timepie... | Use generic RedirectView rather than lambda function | Use generic RedirectView rather than lambda function
| Python | mit | dannybrowne86/django-timepiece,caktus/django-timepiece,josesanch/django-timepiece,caktus/django-timepiece,dannybrowne86/django-timepiece,gaga3966/django-timepiece,arbitrahj/django-timepiece,arbitrahj/django-timepiece,gaga3966/django-timepiece,josesanch/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timep... |
6eacc0a0736edc410c011003986831b5f58da03e | tests/command_test.py | tests/command_test.py | import os, sys
import unittest
class SqliteTest(unittest.TestCase):
TESTING_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testing_dir'))
def test_command(self):
command = 'diary generate sqlite %s/log.sqlite3' % self.TESTING_DIR
os.system(command)
self.assertTrue(os.... | import os, sys
import unittest
class SqliteTest(unittest.TestCase):
TESTING_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testing_dir'))
def test_command(self):
command = 'diary generate sqlite %s/log.sqlite3' % self.TESTING_DIR
os.system(command)
self.assertTrue(os.... | Add test for odd extension to diary command | Add test for odd extension to diary command
| Python | mit | GreenVars/diary |
f2ecbe9020746a00c9f68918697a45b7f68e23fa | utils/tests/test_math_utils.py | utils/tests/test_math_utils.py | import numpy as np
from nose2 import tools
import utils
@tools.params(((1000, 25), 10, 0),
((1000, 25), 10, 1),
((1000, 25), 77, 0)
)
def test_online_statistics(shape, batch_size, axis):
online_stats = utils.OnlineStatistics(axis=axis)
X = np.random.random(shape)
... | import numpy as np
from nose2 import tools
import utils
@tools.params(((1000, 25), 10, 0),
((1000, 25), 10, 1),
((1000, 25), 77, 0),
((1000, 1, 2, 3), 10, (0, 3))
)
def test_online_statistics(shape, batch_size, axis):
online_stats = utils.OnlineStatistics(ax... | Add test case for OnlineStatistics where axis is a tuple | Add test case for OnlineStatistics where axis is a tuple
| Python | mit | alexlee-gk/visual_dynamics |
3814a07c44c7d97a2ca4aa0f2741a913149d4acd | support/update-converity-branch.py | support/update-converity-branch.py | #!/usr/bin/env python
# Update the coverity branch from the master branch.
# It is not done automatically because Coverity Scan limits
# the number of submissions per day.
from __future__ import print_function
import shutil, tempfile
from subprocess import check_call
class Git:
def __init__(self, dir):
self.dir... | #!/usr/bin/env python
# Update the coverity branch from the master branch.
# It is not done automatically because Coverity Scan limits
# the number of submissions per day.
from __future__ import print_function
import shutil, tempfile
from subprocess import check_output, STDOUT
class Git:
def __init__(self, dir):
... | Handle fast forward in update-coverity-branch.py | Handle fast forward in update-coverity-branch.py | Python | bsd-2-clause | lightslife/cppformat,alabuzhev/fmt,mojoBrendan/fmt,dean0x7d/cppformat,Jopie64/cppformat,alabuzhev/fmt,cppformat/cppformat,alabuzhev/fmt,mojoBrendan/fmt,cppformat/cppformat,lightslife/cppformat,cppformat/cppformat,dean0x7d/cppformat,lightslife/cppformat,dean0x7d/cppformat,mojoBrendan/fmt,Jopie64/cppformat,Jopie64/cppfor... |
1c5cd470002b256677f9dc0a7c25c141880cd916 | leonardo/widgets/__init__.py | leonardo/widgets/__init__.py |
from leonardo.module.nav.mixins import NavigationWidgetMixin
from leonardo.module.nav.models import NavigationWidget
from leonardo.module.web.models import ListWidget, Widget
from leonardo.module.web.widgets.mixins import (AuthContentProxyWidgetMixin,
ContentProxyWidgetM... |
from leonardo.module.nav.mixins import NavigationWidgetMixin
from leonardo.module.nav.models import NavigationWidget
from leonardo.module.web.models import ListWidget, Widget
from leonardo.module.web.widgets.mixins import (AuthContentProxyWidgetMixin,
ContentProxyWidgetM... | Include get htmltext widget in widgets module. | Include get htmltext widget in widgets module.
| Python | bsd-3-clause | django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo |
ffff57041cf8d2a13a941a8f0e39d92fe082f28a | welt2000/__init__.py | welt2000/__init__.py | from flask import Flask, request, session
from flask.ext.babel import Babel
from welt2000.__about__ import (
__title__, __summary__, __uri__, __version__, __author__, __email__,
__license__,
) # noqa
app = Flask(__name__)
app.secret_key = '1234567890'
babel = Babel(app)
translations = ['en']
translations.... | from flask import Flask, request, session
from flask.ext.babel import Babel
from babel.core import negotiate_locale
from welt2000.__about__ import (
__title__, __summary__, __uri__, __version__, __author__, __email__,
__license__,
) # noqa
app = Flask(__name__)
app.secret_key = '1234567890'
babel = Babel(a... | Use babel.negotiate_locale() instead of best_match() | app: Use babel.negotiate_locale() instead of best_match()
The babel version takes care of handling territory codes etc.
| Python | mit | Turbo87/welt2000,Turbo87/welt2000 |
ef91f18f7fce637643ad58351b96e13c37eb8925 | traits/qt/__init__.py | traits/qt/__init__.py | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and ... | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and ... | Fix bug in the PyQt4 binding selection logic. | Fix bug in the PyQt4 binding selection logic.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits |
9b020b87cede9dc2014c86946b3fa9bfedbd0577 | tests/rules_tests/FromSymbolComputeTest.py | tests/rules_tests/FromSymbolComputeTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class FromSymbolComputeTest(TestCase):
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class Simple(Rule):
fromSymbol = 0
toSymbol = 1
class FromSymbolComputeTest(TestCase):
def test_rules_simple(self):
r = Si... | Add tests of converting from symbol to rest of rule's property | Add tests of converting from symbol to rest of rule's property
| Python | mit | PatrikValkovic/grammpy |
d44010acc32fcb78570cd34478d0f4e8f1cfa979 | utility/dbproc.py | utility/dbproc.py | from discord.ext import commands
from utils import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from member import Base, Member
import discord
import asyncio
class Baydb:
engine = create_engine('sqlite:///bayohwoolph.db')
Base.metadata.bind = engine
DBSession = sessionma... | from discord.ext import commands
from utils import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from member import Base, Member
from config import Config
import discord
import asyncio
class Baydb:
engine = create_engine(Config.MAIN['dbpath'])
Base.metadata.bind = engine
... | Move another usage of DB into ini file thing. | Move another usage of DB into ini file thing.
| Python | agpl-3.0 | dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph |
7660b601d068652487cc97a704ae54acc33c6889 | setup.py | setup.py | from distutils.core import setup
setup(name='hermes-gui',
version='0.1',
packages=[
'acme',
'acme.acmelab',
'acme.core',
'acme.core.views',
],
package_data={
'acme.acmelab': ['images/*'],
'acme.core': ['images/*.png'],
}
... | from distutils.core import setup
setup(name='hermes-gui',
version='0.1',
packages=[
'acme',
'acme.acmelab',
'acme.core',
'acme.core.views',
],
package_data={
'acme.acmelab': ['images/*'],
'acme.core': ['images/*.png'],
},
... | Install the hermes-gui.py executable too | Install the hermes-gui.py executable too
| Python | bsd-3-clause | certik/hermes-gui |
eca14d9db21a6cdfdb47261af1a29f6fc294825a | accounts/backends.py | accounts/backends.py | """Custom authentication backends"""
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class SmarterModelBackend(ModelBackend):
"""Authentication backend that is less moronic that the default Django one"""
def authenticate(self, request, username=None, passw... | """Custom authentication backends"""
import logging
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
LOGGER = logging.getLogger(__name__)
class SmarterModelBackend(ModelBackend):
"""Authentication backend that is less moronic that the default Django one"""
... | Add a case sensitive login for duplicate usernames | Add a case sensitive login for duplicate usernames
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,lutris/website |
dda39cf93fdbd9e40becfc82bb4e1e49e08c44f3 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
import lithium
packages = ['lithium',]
core = ['conf', 'views',]
apps = ['blog', 'contact',]
templatetags = ['blog',]
package_data = {}
for item in templatetags:
packages.append('lithium.%s.templatetags' % item)
for item in apps + core + templatetags:
pa... | #!/usr/bin/env python
from distutils.core import setup
import lithium
packages = ['lithium',]
core = ['conf', 'views',]
apps = ['blog', 'contact',]
templatetags = ['blog',]
package_data = {}
for item in templatetags:
packages.append('lithium.%s.templatetags' % item)
for item in apps + core + templatetags:
pa... | Include *.txt in package data, since lithium.contact has a txt template | Include *.txt in package data, since lithium.contact has a txt template
| Python | bsd-2-clause | kylef/lithium |
e5c949d33bb40c32d05932e4dfe8fe75f87fbf16 | lcp/urls.py | lcp/urls.py | """lcp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... | """lcp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... | Make the API not use trailing slashes. This is what Ember expects. | Make the API not use trailing slashes. This is what Ember expects.
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp |
fcc030b960965f9ac462bbefa48f629b73db5c8b | etd_drop_app/validators.py | etd_drop_app/validators.py | from django.core.exceptions import ValidationError
import magic
class MimetypeValidator(object):
def __init__(self, mimetypes):
self.mimetypes = mimetypes
def __call__(self, value):
mime = magic.from_buffer(value.read(1024), mime=True)
if not mime in self.mimetypes:
raise ValidationError('%s is not an ac... | from django.core.exceptions import ValidationError
import magic
class MimetypeValidator(object):
def __init__(self, mimetypes):
self.mimetypes = mimetypes
def __call__(self, value):
try:
mime = magic.from_buffer(value.read(1024), mime=True)
if not mime in self.mimetypes:
raise ValidationError('%s is... | Make mimetype validator slightly more robust | Make mimetype validator slightly more robust
| Python | bsd-3-clause | MetaArchive/etd-drop,MetaArchive/etd-drop |
9bec0bfcf8f12dc3f95a04918331c99c77b4914b | exercises/chapter_04/exercise_04_01/exercise_04_01.py | exercises/chapter_04/exercise_04_01/exercise_04_01.py | # 4-1. Pizzas
favorite_pizzas = ["Columpus", "Marco Polo", "Amerikana"]
for pizza in favorite_pizzas:
print(pizza)
| # 4-1. Pizzas
favorite_pizzas = ["Columpus", "Marco Polo", "Amerikana"]
for pizza in favorite_pizzas:
print("I like " + pizza + " pizza.")
| Add version 2 of exercise 4.1. | Add version 2 of exercise 4.1.
| Python | mit | HenrikSamuelsson/python-crash-course |
5645946d9a99ff86c43c7801053a0ef279dc1382 | ynr/apps/candidates/csv_helpers.py | ynr/apps/candidates/csv_helpers.py | from compat import BufferDictWriter
from .models import CSV_ROW_FIELDS
def _candidate_sort_by_name_key(row):
return (
row["name"].split()[-1],
row["name"].rsplit(None, 1)[0],
not row["election_current"],
row["election_date"],
row["election"],
row["post_label"],
... | from collections import defaultdict
from compat import BufferDictWriter
from django.conf import settings
from popolo.models import Membership
from candidates.models import PersonRedirect
def list_to_csv(membership_list):
csv_fields = settings.CSV_ROW_FIELDS
writer = BufferDictWriter(fieldnames=csv_fields)
... | Move to using membership based CSV output | Move to using membership based CSV output
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
39404dfa8ab921977347d4405c525935a0ce234d | cc/license/tests/test_licenses.py | cc/license/tests/test_licenses.py | from nose.tools import assert_true
def test_find_sampling_selector():
from zope.interface import implementedBy
import cc.license
sampling_selector = cc.license.get_selector('recombo')()
return sampling_selector
def test_find_sampling_licenses():
selector = test_find_sampling_selector()
lic = ... | from nose.tools import assert_true
def test_find_sampling_selector():
from zope.interface import implementedBy
import cc.license
sampling_selector = cc.license.get_selector('recombo')()
return sampling_selector
def test_find_standard_selector():
from zope.interface import implementedBy
import... | Add a test for grabbing the standard selector | Add a test for grabbing the standard selector
| Python | mit | creativecommons/cc.license,creativecommons/cc.license |
5568e84b715ed2de20d325aa1e66e9959e5e8b89 | feed/feed.home.loadtest.py | feed/feed.home.loadtest.py | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file_... | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file_... | Remove no longer needed python libs | Remove no longer needed python libs
| Python | apache-2.0 | fxstein/SentientHome |
f75d06702274257215229b83c4ff74de3dc72463 | nnpy/tests.py | nnpy/tests.py | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = nnpy.Socket(nnpy.AF_SP, nnpy.S... | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy... | Add some more test coverage | Add some more test coverage
| Python | mit | nanomsg/nnpy |
e409e8d77eec8e53978512da56bf52f768d46c1a | create-application.py | create-application.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess, os, sys, optparse
fullpath = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
capath = os.path.abspath(
os.path.join(fullpath, "qooxdoo", "tool", "bin", "create-application.py")
)
skeletonpath = os.path.abspath(
os.path.join(fullpath, "un... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Create skeleton application for Unify
# Copyright (C) 2012 Sebastian Fastner, Mainz, Germany
# License: MIT or Apache2
import os, sys, shutil
print("Unify create skeleton")
print("(C) 2012 Sebastian Fastner, Mainz, Germany")
print()
if (len(sys.argv) != 2):
print... | Add variable replacements to create application | Add variable replacements to create application
| Python | mit | unify/unify,unify/unify,unify/unify,unify/unify,unify/unify,unify/unify |
3d6015649e50a2f55e5dc1ef84406e229607cdaa | test2.py | test2.py | import json
#from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp
import jsonrpclib
class StanfordNLP:
def __init__(self, port_number=8080):
self.server = jsonrpclib.Server("http://localhost:%d" % port_number)
def parse(self, text):
return json.loads(self.server.parse(text))
nlp = Stanf... | import json
#from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp
import jsonrpclib
import fileinput
class StanfordNLP:
def __init__(self, port_number=8080):
self.server = jsonrpclib.Server("http://localhost:%d" % port_number)
def parse(self, text):
return json.loads(self.server.parse(te... | Add loop, allowing several tests. | Add loop, allowing several tests.
| Python | agpl-3.0 | ProjetPP/PPP-QuestionParsing-Grammatical,ProjetPP/PPP-QuestionParsing-Grammatical |
23dac5f2e5be725eff7d329a6af399f6d80c59de | logintokens/tokens.py | logintokens/tokens.py | """module containing generator for login tokens
"""
import base64
from django.core.signing import TimestampSigner, BadSignature
from django.contrib.auth import get_user_model
class LoginTokenGenerator:
"""Generator for the timestamp signed tokens used for logging in.
"""
def __init__(self):
sel... | """module containing generator for login tokens
"""
import base64
from django.contrib.auth import get_user_model
from django.core.signing import TimestampSigner, BadSignature
USER = get_user_model()
class LoginTokenGenerator:
"""Generator for the timestamp signed tokens used for logging in.
"""
def _... | Use last login of user in signed value | Use last login of user in signed value
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
eb994bad8556c750f2c27f83117e7d32899d9427 | tests.py | tests.py | """
Tests for TwitterSA
These tests might be overkill, it's my first time messing around
with unit tests.
Jesse Mu
"""
import TwitterSA
import unittest
class TwitterSATestCase(unittest.TestCase):
def setUp(self):
TwitterSA.app.config['TESTING'] = True
self.app = TwitterSA.app.test_client()
... | """
Tests for TwitterSA
These tests might be overkill, it's my first time messing around
with unit tests.
Jesse Mu
"""
import TwitterSA
import unittest
try:
import cPickle as pickle
except ImportError:
import pickle
DATA_SOURCES = [
'lib/noslang.p'
]
class TwitterSATestCase(unittest.TestCase):
de... | Add validate data sources test | Add validate data sources test
| Python | mit | jayelm/twittersa,jayelm/twittersa |
3cf7ca56ac156154dc08433955fff4b15e7eb331 | mpd_mypy.py | mpd_mypy.py | #!/usr/bin/python
import mpd
SERVER = "localhost"
PORT = 6600
def connect(mpdclient):
"""
Handle connection to the mpd server
"""
mpdclient.connect(SERVER, PORT)
mpdclient = mpd.MPDClient()
connect(mpdclient)
bands = set(mpdclient.list("artist"))
| #!/usr/bin/python
import mpd
SERVER = "localhost"
PORT = 6600
def connect(mpdclient):
"""
Handle connection to the mpd server
"""
mpdclient.connect(SERVER, PORT)
mpdclient = mpd.MPDClient()
connect(mpdclient)
bands = set(str(artist).lower() for artist in mpdclient.list("artist")
if art... | Apply filters on artists to clean duplicates | Apply filters on artists to clean duplicates
| Python | bsd-2-clause | Anthony25/mpd_muspy |
d837a194e29b867443a3758bb4c159afe193e798 | enumfields/fields.py | enumfields/fields.py | from django.core.exceptions import ValidationError
from django.db import models
import six
class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)):
def __init__(self, enum, choices=None, max_length=10, **options):
self.enum = enum
if not choices:
try:
choices = en... | from django.core.exceptions import ValidationError
from django.db import models
import six
class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)):
def __init__(self, enum, choices=None, max_length=10, **options):
self.enum = enum
if not choices:
try:
choices = en... | Revert "Add South introspection rules" | Revert "Add South introspection rules"
They weren't correct.
This reverts commit b7235e2fc4b28271e0dce8d812faa4a46ed84aea.
| Python | mit | suutari-ai/django-enumfields,jessamynsmith/django-enumfields,bxm156/django-enumfields,jackyyf/django-enumfields |
5e12fbf432331f1cc6f16c85e9535c12e5584ecc | neuroimaging/setup.py | neuroimaging/setup.py | import os
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('neuroimaging', parent_package, top_path)
config.add_subpackage('algorithms')
config.add_subpackage('core')
config.add_subpackage('data_io')
config.add_subpa... | import os
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('neuroimaging', parent_package, top_path)
config.add_subpackage('algorithms')
config.add_subpackage('core')
config.add_subpackage('externals')
config.add_sub... | Change neuroimaging package list data_io to io. | Change neuroimaging package list data_io to io. | Python | bsd-3-clause | alexis-roche/nipy,alexis-roche/register,arokem/nipy,alexis-roche/register,alexis-roche/niseg,nipy/nireg,nipy/nipy-labs,nipy/nireg,arokem/nipy,alexis-roche/nipy,alexis-roche/register,arokem/nipy,alexis-roche/nireg,bthirion/nipy,nipy/nipy-labs,alexis-roche/nireg,bthirion/nipy,bthirion/nipy,alexis-roche/nipy,arokem/nipy,a... |
e8454180e4ec612e5c76ab0ec5f149adcaadf026 | runtests.py | runtests.py | #!/usr/bin/env python
from django.conf import settings
from django.core.management import call_command
INSTALLED_APPS = (
# Required contrib apps.
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.sessions',
# Our app and ... | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
INSTALLED_APPS = (
# Required contrib apps.
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.sessions',
... | Make testrunner work with Django 1.7). | Make testrunner work with Django 1.7).
| Python | bsd-3-clause | helber/django-dbsettings,helber/django-dbsettings,zlorf/django-dbsettings,sciyoshi/django-dbsettings,johnpaulett/django-dbsettings,nwaxiomatic/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,winfieldco/django-dbsettings,DjangoAdminHackers/django-dbsettings,johnpaulett/django-dbsettings,wi... |
f9b079b7956419ec324234dbad11d073bed70dd8 | users/views.py | users/views.py | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... | Use Python 3 style for super | Use Python 3 style for super
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja |
78854858ebeb3fe92df82e203880e177a205051a | apps/mommy/management/commands/mommy-task-run.py | apps/mommy/management/commands/mommy-task-run.py | from django.core.management.base import BaseCommand
from apps import mommy
class Command(BaseCommand):
args = 'name of job'
help = 'run a job'
@staticmethod
def print_job_names():
possible_jobs = []
for task, _ in mommy.schedule.tasks.items():
possible_jobs.append(task.__... | from django.core.management.base import BaseCommand
from apps import mommy
class Command(BaseCommand):
help = 'run a job'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
mommy.autodiscover()
def add_arguments(self, parser):
parser.add_argument('job', help=... | Use add_arguments instead of deprecated .args | Use add_arguments instead of deprecated .args
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
14557e20e2e813a83c05d5733fb2998857527460 | Differ.py | Differ.py |
file1 = raw_input('[file1:] ')
modified = open(file1,"r").readlines()[0]
file2 = raw_input('[file2:] ')
pi = open(file2, "r").readlines()[0] # [:len(modified)]
resultado = "".join( x for x,y in zip(modified, pi) if x != y)
resultado2 = "".join( x for x,y in zip(pi, modified) if x != y)
print "[Differ:]
print '\n---... |
#!/usr/bin/python
# Script to Check the difference in 2 files
# 1 fevereiro de 2015
# https://github.com/thezakman
file1 = raw_input('[file1:] ')
modified = open(file1,"r").readlines()[0]
file2 = raw_input('[file2:] ')
pi = open(file2, "r").readlines()[0] # [:len(modified)]
result... | Check Diff of 2 files | Check Diff of 2 files | Python | artistic-2.0 | thezakman/CTF-Scripts,thezakman/CTF-Scripts |
6377a1a50293c2b62eb5e29c936998ad09995c7a | service/inchi.py | service/inchi.py | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.st... | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi)
request = requests.get(re... | Fix URL for fetch CJSON | Fix URL for fetch CJSON
| Python | bsd-3-clause | OpenChemistry/mongochemweb,OpenChemistry/mongochemweb |
2498f0184e9cf0496fdf1e33c8aa4fe4aa643502 | stats.py | stats.py | #!/usr/bin/python
# encoding: utf-8
from __future__ import with_statement
import argparse, re, sys
def filter(args):
bytes_extractor = re.compile(r"([0-9]+) bytes")
with args.output:
with args.input:
for line in args.input:
if line.find("avr-size") >= 0:
... | #!/usr/bin/python
# encoding: utf-8
# In order to use this script from shell:
# > make CONF=UNO clean-examples
# > make CONF=UNO examples >tempsizes
# > cat tempsizes | ./stats.py >sizes
# > rm tempsizes
# Then sizes file can be opened in LibreOffice Calc
from __future__ import with_statement
import argparse, re, sys... | Document python script to extract program sizes from make output. | Document python script to extract program sizes from make output.
| Python | lgpl-2.1 | jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib |
cfaed02921ba1c46c45f726aa4a008f4fa1cd66f | partner_academic_title/models/partner_academic_title.py | partner_academic_title/models/partner_academic_title.py | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of partner_academic_title,
# an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# partner_academic_title is free software:
# you can redistribute it an... | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of partner_academic_title,
# an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# partner_academic_title is free software:
# you can redistribute it an... | Add translate=True on academic title name | Add translate=True on academic title name
| Python | agpl-3.0 | brain-tec/partner-contact,brain-tec/partner-contact |
d2fe3bbf4f97ef5ece4c6c69e531e261eeed75b1 | stoq/plugins/archiver.py | stoq/plugins/archiver.py | #!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# Un... | #!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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
#
# Un... | Remove @abstracmethod from archive method as well | Remove @abstracmethod from archive method as well | Python | apache-2.0 | PUNCH-Cyber/stoq |
2f4483440a98f34b650ea09a75f6dc941548f8b2 | zeus/vcs/db.py | zeus/vcs/db.py | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | Disable asyncpg prepared statement cache | Disable asyncpg prepared statement cache
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
24d51efaf80993352d82038d059c4435857fcd67 | test/backend/test_job.py | test/backend/test_job.py | import unittest
import cryptosite
import saliweb.test
import saliweb.backend
import os
class JobTests(saliweb.test.TestCase):
"""Check custom CryptoSite Job class"""
def test_run_first_stepok(self):
"""Test successful run method, first step"""
j = self.make_test_job(cryptosite.Job, 'RUNNING')
... | import unittest
import cryptosite
import saliweb.test
import saliweb.backend
import os
class JobTests(saliweb.test.TestCase):
"""Check custom CryptoSite Job class"""
def test_run_first_stepok(self):
"""Test successful run method, first step"""
j = self.make_test_job(cryptosite.Job, 'RUNNING')
... | Update to match new format for param.txt. | Update to match new format for param.txt.
| Python | lgpl-2.1 | salilab/cryptosite-web,salilab/cryptosite-web |
c76be093ca2fe226d43e2f6ef908dfc7dbf1faf1 | keys.py | keys.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# weatherBot keys
# Copyright 2015 Brian Mitchell under the MIT license
# See the GitHub repository: https://github.com/bman4789/weatherBot
import os
keys = dict(
consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | #!/usr/bin/env python3
# weatherBot keys
# Copyright 2015 Brian Mitchell under the MIT license
# See the GitHub repository: https://github.com/bman4789/weatherBot
import os
keys = dict(
consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_key... | Remove flickr key, add forecast.io key | Remove flickr key, add forecast.io key
| Python | mit | bman4789/weatherBot,bman4789/weatherBot,BrianMitchL/weatherBot |
f64447ca0e1442552b4a854fec5a8f847d2165cd | numpy/_array_api/_types.py | numpy/_array_api/_types.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | Use the array API types for the array API type annotations | Use the array API types for the array API type annotations
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
263ffc507d693854aec3fe826964b3c9031cdad8 | s4v1.py | s4v1.py | from s3v3 import *
import csv
def write_to_file(filename, data_sample):
example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect).
example.writerows(data_sample) # write ro... | from s3v3 import *
import csv
# ORIGINAL VERSION - Leaves file open
# def write_to_file(filename, data_sample):
# example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect).
... | Update export csv function to close file when finished | Update export csv function to close file when finished
| Python | mit | alexmilesyounger/ds_basics |
c2aaf1f325ba44406acacd3935a4897c833dc16c | django-row-tracker.py | django-row-tracker.py | import sys
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db.utils import DatabaseError
from django.db.transaction import rollback_unless_managed
from django.db import models
def get_model_info():
'''
Dump all models and their row counts to the screen
... | import argparse
import sys
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db.utils import DatabaseError
from django.db.transaction import rollback_unless_managed
from django.db import models
def get_model_info():
'''
Dump all models and their row counts... | Add argument handling for path and project name | Add argument handling for path and project name
| Python | bsd-3-clause | shearichard/django-row-tracker |
9efd7f63f12affffb58b7e243777432a331e91f2 | examples/add_command_line_argument.py | examples/add_command_line_argument.py | from locust import HttpUser, TaskSet, task, between
from locust import events
@events.init_command_line_parser.add_listener
def _(parser):
parser.add_argument(
'--custom-argument',
help="It's working"
)
@events.init.add_listener
def _(environment, **kw):
print("Custom argument supplied: %... | from locust import HttpUser, TaskSet, task, between
from locust import events
@events.init_command_line_parser.add_listener
def _(parser):
parser.add_argument(
"--my-argument",
type=str,
env_var="LOCUST_MY_ARGUMENT",
default="",
help="It's working"
)
@events.init.add_... | Add type, env var and default value to custom argument example. And rename it so that nobody thinks the "custom" in the name has a specific meaning. | Add type, env var and default value to custom argument example. And rename it so that nobody thinks the "custom" in the name has a specific meaning.
| Python | mit | mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust |
2a37edaef3be06ab97bb1561b51d7977909e4abe | feed_sources/CTTransit.py | feed_sources/CTTransit.py | """Fetch CT Transit (Connecticut) feeds."""
import logging
from FeedSource import FeedSource
LOG = logging.getLogger(__name__)
BASE_URL = 'http://www.cttransit.com/uploads_GTFS/'
SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip'
class CTTransit(FeedSource):
"""Fetch PATH feed."""
def _... | """Fetch CT Transit (Connecticut) feeds."""
import logging
from FeedSource import FeedSource
LOG = logging.getLogger(__name__)
BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip'
SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip'
HARTFORD_URL = 'http://www.hartford... | Update CT Transit feed fetcher | Update CT Transit feed fetcher
CT Transit has changed their URLs.
| Python | mit | azavea/gtfs-feed-fetcher |
0148b417a9ce8531383f2fb4e5500d9b32794f2c | byceps/services/party/settings_service.py | byceps/services/party/settings_service.py | """
byceps.services.party.settings_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ...typing import PartyID
from .models.setting import Setting as DbSetting
from .transfer.models import Pa... | """
byceps.services.party.settings_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ...database import db
from ...typing import PartyID
from .models.setting import Setting as DbSetting
from... | Add service functions to create a party setting and to obtain one's value | Add service functions to create a party setting and to obtain one's value
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps |
4bd9a94243ddc01d86ded2d592c339e464ec42fc | dedupe/convenience.py | dedupe/convenience.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | Update dataSample to index on the ints returned by random_pairs | Update dataSample to index on the ints returned by random_pairs
| Python | mit | 01-/dedupe,tfmorris/dedupe,01-/dedupe,nmiranda/dedupe,datamade/dedupe,neozhangthe1/dedupe,pombredanne/dedupe,tfmorris/dedupe,datamade/dedupe,dedupeio/dedupe,nmiranda/dedupe,pombredanne/dedupe,davidkunio/dedupe,dedupeio/dedupe-examples,davidkunio/dedupe,neozhangthe1/dedupe,dedupeio/dedupe |
5529900f5f9642f460a78ce58a2c74e021e35266 | gaphor/misc/tests/test_gidlethread.py | gaphor/misc/tests/test_gidlethread.py | from gaphor.misc.gidlethread import GIdleThread
def test_wait_with_timeout():
# GIVEN a running gidlethread
def counter(max):
for x in range(max):
yield x
t = GIdleThread(counter(20000))
t.start()
assert t.is_alive()
# WHEN waiting for 0.01 sec timeout
wait_result = t.... | import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.01 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result =... | Update test to use fixtures and parameterization | Update test to use fixtures and parameterization
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
2ce4e16979e095f1885f35cd767b0625dcd424c6 | defender/test_urls.py | defender/test_urls.py | from django.conf.urls import patterns, include
from django.contrib import admin
urlpatterns = patterns(
'',
(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
| Use url method instead of patterns in test URLs setup. | Use url method instead of patterns in test URLs setup.
| Python | apache-2.0 | kencochrane/django-defender,kencochrane/django-defender |
8b2f95dd8399d5c354769c860e2b955c3fe212b0 | semesterpage/forms.py | semesterpage/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from dal import autocomplete
from .models import Course, Options
class OptionsForm(forms.ModelForm):
"""
A form solely used for autocompleting Courses in the admin,
using django-autocomplete-light,
"""
self_chosen_c... | from django import forms
from django.utils.translation import ugettext_lazy as _
from dal import autocomplete
from .models import Course, Options
class OptionsForm(forms.ModelForm):
"""
A form solely used for autocompleting Courses in the admin,
using django-autocomplete-light,
"""
self_chosen_c... | Make it more clear that users should enter courses | Make it more clear that users should enter courses
| Python | mit | afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.