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 |
|---|---|---|---|---|---|---|---|---|---|
5779380fd4ec28367c1f232710291b3f81e1791f | nested_comments/views.py | nested_comments/views.py | # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.rever... | # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.rever... | Add queryset attribute to NestedCommentDetail view | Add queryset attribute to NestedCommentDetail view
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin |
761c6538d33daf59135d519f1aeaaac9b920c5ff | nova/objects/__init__.py | nova/objects/__init__.py | # Copyright 2013 IBM Corp.
#
# 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 agree... | # Copyright 2013 IBM Corp.
#
# 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 agree... | Fix importing InstanceInfoCache during register_all() | Fix importing InstanceInfoCache during register_all()
Related to blueprint unified-object-model
Change-Id: Ib5edd0d0af46d9ba9d0fcaa14c9601ad75b8d50d
| Python | apache-2.0 | openstack/oslo.versionedobjects,citrix-openstack-build/oslo.versionedobjects |
555637aa86bef0b3cf5d3fe67b0341bcee5e271a | findaconf/tests/test_autocomplete_routes.py | findaconf/tests/test_autocomplete_routes.py | # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomp... | # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomp... | Add tests for 404 on invalid routes | Add tests for 404 on invalid routes
| Python | mit | cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf |
47fb142f285f989f7b911915b7b130bf4a72254b | opencraft/urls.py | opencraft/urls.py | """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', name... | """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', name... | Remove 1.8 warning about redirect | Remove 1.8 warning about redirect
| Python | agpl-3.0 | omarkhan/opencraft,open-craft/opencraft,open-craft/opencraft,brousch/opencraft,omarkhan/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,brousch/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft |
8d392a0723205a8229512a47355452bb94b36cfb | examples/visualization/eeg_on_scalp.py | examples/visualization/eeg_on_scalp.py | """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plo... | """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plo... | Remove brain example [skip azp] [skip actions] | FIX: Remove brain example [skip azp] [skip actions]
| Python | bsd-3-clause | wmvanvliet/mne-python,Eric89GXL/mne-python,Teekuningas/mne-python,mne-tools/mne-python,pravsripad/mne-python,larsoner/mne-python,drammock/mne-python,mne-tools/mne-python,olafhauk/mne-python,Teekuningas/mne-python,bloyl/mne-python,larsoner/mne-python,drammock/mne-python,kingjr/mne-python,Eric89GXL/mne-python,larsoner/mn... |
6eec6ac19073e5bef6d8d4fc9451d173015407f7 | examples/plot_pmt_time_slewing.py | examples/plot_pmt_time_slewing.py | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import m... | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Time slewing corrects the hit time due to different rise times of the
PMT signals depending on the number of photo electrons.
The reference point is at 26.4ns and hits with a d... | Add some docs to PMT time slewing | Add some docs to PMT time slewing
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe |
cc4211e2a3cdc58bf5ac3bf64711b881d1c046d0 | modules/currency.py | modules/currency.py | import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
else:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5]
to = ... | import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = se... | Check for valid currencies in a file | Check for valid currencies in a file
| Python | mit | jasuka/pyBot,jasuka/pyBot |
fa5f50a4a257477f7dc0cbacec6d1cd3d8f0d217 | hdc1008test.py | hdc1008test.py | """Tests for the hdc1008 module"""
import pyb
from hdc1008 import HDC1008
i2c = pyb.I2C(2)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
while True:
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
print("Rel... | """Tests for the hdc1008 module"""
from hdc1008 import HDC1008
import utime
i2c = pyb.I2C(1)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
def read_sensors():
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
p... | Update to the new API and small cosmetic changes. | Update to the new API and small cosmetic changes. | Python | mit | kfricke/micropython-hdc1008 |
fdb63cca26170d1348526ce8c357803ac6b37cf6 | hybrid_analysis/file_reader/hybrid_reader.py | hybrid_analysis/file_reader/hybrid_reader.py | #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
def read_afterburner_output(filename, read_initial=False):
id_event = 0
particlelist = []
if os.path.isfile(filename):
read_data = False
initial_list = False
for line in open(filename, "r"):
inp... | #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
import copy
from .. import dataobjects.particledata
def read_afterburner_output(filename, read_initial=False):
id_event = 0
if os.path.isfile(filename):
read_data = False
initial_list = False
eventlist = []
... | Use ParticleData class in file reader | Use ParticleData class in file reader
File reader now creates lists of ParticleData objects.
Signed-off-by: Jussi Auvinen <16b8c81f9479dec4f5eedf7ae5a2413c6a10bc13@phy.duke.edu>
| Python | mit | jauvinen/hybrid-model-analysis |
a23641edf1fd941768eebb1938340d2173ac2e11 | iputil/parser.py | iputil/parser.py | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
match = IP_REGEX.findall(line)
... | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
matches += IP_REGEX.findall(line)
... | Remove unnecessary check, used to re functions returning different types | Remove unnecessary check, used to re functions returning different types
| Python | mit | kolanos/iputil |
2e1774aa0505873f7a3e8fe5a120e8931200fa35 | pokr/models/__init__.py | pokr/models/__init__.py | import assembly
import bill
import bill_feed
import bill_keyword
import bill_review
import bill_status
import bill_withdrawal
import candidacy
import cosponsorship
import election
import favorite_keyword
import favorite_person
import feed
import keyword
import meeting
import meeting_attendee
import party
import person
... | from assembly import *
from bill import *
from bill_feed import *
from bill_keyword import *
from bill_review import *
from bill_status import *
from bill_withdrawal import *
from candidacy import *
from cosponsorship import *
from election import *
from favorite_keyword import *
from favorite_person import *
from feed... | Make 'from pokr.models import ~' possible | Make 'from pokr.models import ~' possible
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr |
09225071761ae059c46393d41180b6c37d1b3edc | portal/models/locale.py | portal/models/locale.py | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
... | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
... | Correct coding error - need to return coding from property function or it'll cache None. | Correct coding error - need to return coding from property function or it'll cache None.
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal |
3664b2d9b7590b6750e35abba2c0fe77c7afd4cd | bin/license_finder_pip.py | bin/license_finder_pip.py | #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
from pip._internal.download import PipSession
except ImportError:
from pip.download import PipSession
from pip._vendor imp... | #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
# since pip 19.3
from pip._internal.network.session import PipSession
except ImportError:
try:
# since pip 10
... | Support finding licenses with pip>=19.3 | Support finding licenses with pip>=19.3
| Python | mit | pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder |
f4209f7be27ef1ce0725f525a7029246c4c54631 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| Switch to more optimal non-generator solution | Switch to more optimal non-generator solution
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
a633e7c1c5ca2fff4018ab7f51136ba9ad1b9cde | grammpy_transforms/contextfree.py | grammpy_transforms/contextfree.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree():
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, tra... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree:
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, trans... | Add additional parameters into CotextFree.is_grammar_generating method | Add additional parameters into CotextFree.is_grammar_generating method
| Python | mit | PatrikValkovic/grammpy |
fafd048452ebfb3379ab428cc74e795d3406478f | apps/comments/models.py | apps/comments/models.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... | Make sure we have a recipient before sending notification | Make sure we have a recipient before sending notification | Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas |
be746c870f2015507af5513a8636905cf9018001 | image_cropping/thumbnail_processors.py | image_cropping/thumbnail_processors.py | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if isinstance(box, basestring):
if box.startswith('-... | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if box and not box.startswith('-'):
# a leading - i... | Tweak thumbnail processor a little | Tweak thumbnail processor a little
| Python | bsd-3-clause | henriquechehad/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping |
f6d4f822d8f0f34316c5a2c92c8ceade7bc7fdbd | movieman/movieman.py | movieman/movieman.py | import requests
import os
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, d... | import requests
import os
import sys
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
... | Replace console output for raw txt | Replace console output for raw txt
| Python | mit | kshvmdn/movieman |
0c027086cf6491a301b08b8e0cb1565715e615fe | webapp/byceps/blueprints/ticket/service.py | webapp/byceps/blueprints/ticket/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
... | Use more succinct syntax to filter in database query. | Use more succinct syntax to filter in database query.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
996611b4ec0f0e13769d40122f21b6a6362783a5 | app.tmpl/models.py | app.tmpl/models.py | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
os.path.join(app.root_path, app... | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
o... | Use newer package import syntax for Flask | Use newer package import syntax for Flask
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template |
9d7c55855b2226ff1aef36ed82d34d2f3626d376 | easyium/exceptions.py | easyium/exceptions.py | __author__ = 'karl.gong'
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
self.msg = msg
self.message = self.msg
self.context = context
def __str__(self):
exception_msg = ""
if self.msg is not None:
exception_msg = self.msg
... | import re
__author__ = 'karl.gong'
filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)")
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
# Remove Session info and Driver info of the message.
self.msg = filter_msg_regex.sub("", ... | Remove session info and driver info of webdriverexception. | Remove session info and driver info of webdriverexception.
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium |
b2854df273d2fa84a3bb5f2e0f2574f4ea80fb04 | migrations/211-recategorize-canned-responses.py | migrations/211-recategorize-canned-responses.py | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... | Fix migration 211 to handle lack of data. | Fix migration 211 to handle lack of data.
| Python | bsd-3-clause | Osmose/kitsune,feer56/Kitsune1,orvi2014/kitsune,Osmose/kitsune,iDTLabssl/kitsune,mythmon/kitsune,asdofindia/kitsune,chirilo/kitsune,rlr/kitsune,feer56/Kitsune2,silentbob73/kitsune,mozilla/kitsune,philipp-sumo/kitsune,asdofindia/kitsune,YOTOV-LIMITED/kitsune,anushbmx/kitsune,rlr/kitsune,dbbhattacharya/kitsune,safwanrahm... |
a673bc6b3b9daf27404e4d330819bebc25a73608 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
... | import os
import testinfra.utils.ansible_runner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRu... | Add Selenium test for basic logic. | Add Selenium test for basic logic.
| Python | apache-2.0 | Graylog2/graylog-ansible-role |
8b78f3e84c688b0e45ecfa0dda827870eced4c4e | sdi/corestick.py | sdi/corestick.py | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... | Fix reading in for layer_colors. | Fix reading in for layer_colors.
| Python | bsd-3-clause | twdb/sdi |
c82efa3d0db2f3f9887f4639552e761802829be6 | pgcli/pgstyle.py | pgcli/pgstyle.py | from pygments.token import Token
from pygments.style import Style
import pygments.styles
def style_factory(name):
class PGStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
... | from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PG... | Add safety check for non-existent style. | Add safety check for non-existent style.
| Python | bsd-3-clause | j-bennet/pgcli,suzukaze/pgcli,dbcli/pgcli,darikg/pgcli,johshoff/pgcli,thedrow/pgcli,thedrow/pgcli,janusnic/pgcli,darikg/pgcli,j-bennet/pgcli,yx91490/pgcli,koljonen/pgcli,yx91490/pgcli,lk1ngaa7/pgcli,d33tah/pgcli,lk1ngaa7/pgcli,bitemyapp/pgcli,bitemyapp/pgcli,joewalnes/pgcli,d33tah/pgcli,w4ngyi/pgcli,dbcli/vcli,koljonen... |
200027f73a99f18eeeae4395be9622c65590916f | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... | Exclude Enhance-o Mechano from its own buff targets | Exclude Enhance-o Mechano from its own buff targets
| Python | agpl-3.0 | oftc-ftw/fireplace,smallnamespace/fireplace,butozerca/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,Meerkov/fireplace,NightKev/fireplace,butozerca/fireplace,amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fi... |
631a096eb8b369258c85b5c014460166787abf6c | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variable... | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variable... | Make short unit extraction script idempotent | Make short unit extraction script idempotent
| Python | mit | OurWorldInData/owid-grapher,owid/owid-grapher,aaldaber/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-graphe... |
d8347132e246caf4874384000014353ce200dff4 | launcher/launcher/ui/__init__.py | launcher/launcher/ui/__init__.py | CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "synapse.isrd.isi.edu",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| Set prod server as config default. | Set prod server as config default.
| Python | bsd-3-clause | informatics-isi-edu/synspy,informatics-isi-edu/synspy,informatics-isi-edu/synspy |
8b88ca952ff562eb692f25cba54263afcbbcfafd | auth/models.py | auth/models.py | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def set_p... | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def __ini... | Set password in user ini | Set password in user ini
| Python | mit | haldun/optimyser2,haldun/optimyser2,haldun/tornado-gae-auth |
7a448c4df3feb717d0b1d8abbf9d32237751aab5 | nbgrader/tests/apps/test_nbgrader_extension.py | nbgrader/tests/apps/test_nbgrader_extension.py | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 3
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
paths = [ex... | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
assert nbex... | Fix tests for nbgrader extensions | Fix tests for nbgrader extensions
| Python | bsd-3-clause | jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader |
e385a20fdb877f0c6308883709814920cf0378d7 | behave/__main__.py | behave/__main__.py | #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
if __name__ == "__main__":
from .main import main
sys.exit(main())
| #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
from .main import main
if __name__ == "__main__":
sys.exit(main())
| Tweak for better backward compatibility w/ master repository. | Tweak for better backward compatibility w/ master repository.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave |
ababeb31c0673c44b0c0e6d0b30bf369d67b9e55 | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
def rpp_initialisation():
a = Rp... | import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
pow_ride_1 = np.linspace(100, 200, 4... | Bring some test which need to be finished | Bring some test which need to be finished
| Python | mit | glemaitre/power-profile,clemaitre58/power-profile,glemaitre/power-profile,clemaitre58/power-profile |
67b80161fd686ef0743470dd57e56b64fe9f9128 | rnn_padding.py | rnn_padding.py | import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=N... | import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=N... | Return Vector is in decreasing order of origal length. | Return Vector is in decreasing order of origal length.
| Python | mit | reachtarunhere/pytorch-snippets |
8acb681ff8963621452f0e018781c76d4935cb84 | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', ... | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/... | Add url for project_status_edit option | Add url for project_status_edit option
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
ef974d5b01940efa3886a4074eda964bfc07b133 | bookie/__init__.py | bookie/__init__.py | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.au... | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.au... | Fix the rootfactory for no matchdict so we can get a 404 back out | Fix the rootfactory for no matchdict so we can get a 404 back out
| Python | agpl-3.0 | pombredanne/Bookie,skmezanul/Bookie,teodesson/Bookie,GreenLunar/Bookie,wangjun/Bookie,bookieio/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,charany1/Bookie,bookieio/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,adamlincoln/Bookie,charany1/Bookie,charany1/Bookie,teodesso... |
ffbe699a8435dd0abfb43a37c8528257cdaf386d | pymogilefs/request.py | pymogilefs/request.py | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (s... | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (s... | Add __str__/__bytes__ Python 2.7 compatibility | Add __str__/__bytes__ Python 2.7 compatibility
| Python | mit | bwind/pymogilefs,bwind/pymogilefs |
8b3e40e70101433157709d9d774b199ce606196f | violations/tests/test_base.py | violations/tests/test_base.py | from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test register"""
... | import sure
from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test regi... | Use sure in violations bases tests | Use sure in violations bases tests
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web |
516bebe37212e72362b416bd1d9c87a83726fa5f | changes/api/cluster_nodes.py | changes/api/cluster_nodes.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... | Enforce ordering on cluster nodes endpoint | Enforce ordering on cluster nodes endpoint
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes |
fe8266beb5541f1ac5b08f365edb5f30b3e8eddd | snakeeyes/blueprints/contact/tasks.py | snakeeyes/blueprints/contact/tasks.py | from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail... | from flask import current_app
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id:... | Fix contact form recipient email address | Fix contact form recipient email address
Since Celery is configured differently now we can't reach in and
grab config values outside of Celery.
| Python | mit | nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask |
002be05d8bb07e610613b1ba6f24c904691c9f03 | tests/conftest.py | tests/conftest.py | """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCr... | """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCr... | Create credentials fixture for inactive project | Create credentials fixture for inactive project
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python |
ca0d9b40442f3ca9499f4b1630650c61700668ec | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | Add the action required to fix the issue to the warning | Add the action required to fix the issue to the warning
| Python | mit | renanivo/pytest-testdox |
687c0f3c1b8d1b5cd0cee6403a9664bb2b8f63d1 | cleverbot/utils.py | cleverbot/utils.py | def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
... | def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
... | Add deleter to Conversation properties | Add deleter to Conversation properties
| Python | mit | orlnub123/cleverbot.py |
d2c50272ec4509e40562f441e534ba7457a493f3 | tests/test_api.py | tests/test_api.py | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.w... | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.w... | Add test for imperfect imports as well | Add test for imperfect imports as well
| Python | mit | PyCQA/isort,PyCQA/isort |
a8f125236308cbfc9bb2eb5b225a0ac92a3a95e4 | ANN.py | ANN.py | from random import random
class Neuron:
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def get_output(self):
return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
output = property(get_o... | from random import random
class Neuron:
output = None
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def calculate(self):
self.output = sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
c... | Store output instead of calculating it each time | Store output instead of calculating it each time
| Python | mit | tysonzero/py-ann |
884483d27f7c0fac3975da17a7ef5c470ef9e3b4 | fcm_django/apps.py | fcm_django/apps.py | from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
| from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
default_auto_field = "django.db.models.BigAutoField"
| Use BigAutoField as the default ID | Use BigAutoField as the default ID | Python | mit | xtrinch/fcm-django |
a43e1c76ba3bef9ab3cbe1353c3b7289031a3b64 | pydub/playback.py | pydub/playback.py | import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def play(audio_segment):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
audio_segment.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
| import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def _play_with_ffplay(seg):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
seg.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
def _play_with_pyaudio(se... | Use Pyaudio when available, ffplay as fallback | Use Pyaudio when available, ffplay as fallback
| Python | mit | cbelth/pyMusic,miguelgrinberg/pydub,jiaaro/pydub,Geoion/pydub,joshrobo/pydub,sgml/pydub |
414dd0b03b3e4eabc11f848f79d681f3a284380e | pygcvs/helpers.py | pygcvs/helpers.py | from .parser import GcvsParser
try:
import ephem
except ImportError:
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii/html/
"""
w... | from .parser import GcvsParser
try:
import ephem
except ImportError: # pragma: no cover
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii... | Exclude missing ephem from coverage | Exclude missing ephem from coverage
| Python | mit | zsiciarz/pygcvs |
c9a9bf594f9d91a0a2f4c297e6200ebfa047bae6 | examples/manage.py | examples/manage.py | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bs3demo.settings')
execute_from_command_line(sys.argv)
| Use env variable for settings.py | Use env variable for settings.py
| Python | mit | rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,haricot/djangocms-bs4forcascade,haricot/djangocms-bs4forcascade,jrief/djangocms-cascade,jrief/djangocms-cascade,jrief/djangocms-cascade,rfleschenberg/djangocms-cascade,rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,jtiki/djangocms-cascade |
2a379bbef9549005b0c55f29a1bfb0f41811a4e0 | fabfile.py | fabfile.py | from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo sys... | from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo sys... | Add npm install to the fabric script | Add npm install to the fabric script
| Python | agpl-3.0 | UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub |
bbda0891e2fc4d2dfec157e9249e02d114c7c45a | corehq/tests/test_toggles.py | corehq/tests/test_toggles.py | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | Add test to check Solutions sub-tags names | Add test to check Solutions sub-tags names
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
c82eaa445ddbe39f4142de7f51f0d19437a1aef0 | validators/url.py | validators/url.py | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""... | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""... | Remove unnecessary heading from docstring | Remove unnecessary heading from docstring
| Python | mit | kvesteri/validators |
1d4d317c826cd8528dfafd4ae47d006c1e8bb673 | reports/admin.py | reports/admin.py | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
list_filter = ['created_at', 'content']
search_fields = ['addressed_to', 'reported_from__us... | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'signed_from', 'created_at')
list_filter = ['created_at']
search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from']
... | Change search and list fields | Change search and list fields
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
4a98d2ce95d6a082588e4ccc8e04454c26260ca0 | helpers.py | helpers.py | def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
elif i... | def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list) or isinstance(passed_list, tuple):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:... | Make get_readable_list process tuples, too | Make get_readable_list process tuples, too
| Python | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook |
9bc7d09e9abf79f6af7f7fd3cdddbfacd91ba9d3 | run.py | run.py | #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push ... | #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push ... | Add command to update dependencies. | Add command to update dependencies.
| Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger |
5b208baa581e16290aa8332df966ad1d61876107 | deployment/ansible/filter_plugins/custom_filters.py | deployment/ansible/filter_plugins/custom_filters.py | class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, *t):
"""Determnies if there are no ... | class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, x, y):
"""Determines if there are n... | Add explicit method signature to custom filters | Add explicit method signature to custom filters
This changeset adds an explicit method signature to the Ansible custom filters.
| Python | agpl-3.0 | maurizi/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,maurizi/ny... |
b2e0b2047fa686fd716ba22dcec536b79f6fea41 | cookielaw/templatetags/cookielaw_tags.py | cookielaw/templatetags/cookielaw_tags.py | from classytags.helpers import InclusionTag
from django import template
from django.template.loader import render_to_string
register = template.Library()
class CookielawBanner(InclusionTag):
"""
Displays cookie law banner only if user has not dismissed it yet.
"""
template = 'cookielaw/banner.html'... | # -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
return render_to_st... | Use Django simple_tag instead of classytags because there were no context in template rendering. | Use Django simple_tag instead of classytags because there were no context in template rendering. | Python | bsd-2-clause | juan-cb/django-cookie-law,juan-cb/django-cookie-law,juan-cb/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law |
92e7164cf152700c4ae60013bfbb9536e425a64c | neo/rawio/tests/test_nixrawio.py | neo/rawio/tests/test_nixrawio.py | import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "neoraw.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "__mai... | import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "nixrawio-1.5.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "... | Change filename for NIXRawIO tests | [nixio] Change filename for NIXRawIO tests
| Python | bsd-3-clause | NeuralEnsemble/python-neo,INM-6/python-neo,JuliaSprenger/python-neo,apdavison/python-neo,rgerkin/python-neo,samuelgarcia/python-neo |
eef1d6f2c19be042ae3e2e566eb4e0a7b7e71242 | _lib/wordpress_post_processor.py | _lib/wordpress_post_processor.py | import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content) ... | import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content) ... | Remove commented line we definitely will never need | Remove commented line we definitely will never need
| Python | cc0-1.0 | kurtw/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,kurtrwall/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,kurtw/cfgov-refresh,jimmynotjim/cfgov-refresh,kurtw/cfgov-refresh,jimmynotjim/cfgov-refresh,jimmynotjim/cfgov-refresh |
5b702de914f55ee936292576394b2ea06ad15680 | tests/utils.py | tests/utils.py | from __future__ import unicode_literals
import contextlib
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework_simplejwt.settings import api_settings
def client_action_wrapper(action):
def wrapper_method(self, *args, **kwargs... | from __future__ import unicode_literals
import contextlib
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework_simplejwt.compat import reverse
from rest_framework_simplejwt.settings import api_settings
def client_action_wrapper(action):
def wrapper_method(self, *args, *... | Fix broken tests in django master | Fix broken tests in django master
| Python | mit | davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt |
230664f9bbeae88ef640758d150bc5691af23e42 | tests/utils.py | tests/utils.py | from contextlib import contextmanager
from multiprocessing import Process
@contextmanager
def terminate_process(process):
try:
yield
finally:
if process.is_alive():
process.terminate()
@contextmanager
def run_app(app):
process = Process(target=app.run)
process.start()
... | from contextlib import contextmanager
from multiprocessing import Process
from time import sleep
@contextmanager
def terminate_process(process):
try:
yield
finally:
if process.is_alive():
process.terminate()
@contextmanager
def run_app(app):
process = Process(target=app.run)
... | Address issue where process might not fully start | Address issue where process might not fully start
I've tried less than 0.1 seconds and it doesn't routinely pass. This
appears to pass all the time.
| Python | apache-2.0 | tswicegood/steinie,tswicegood/steinie |
9dd503c8d92518f9af4c599473626b98e56393e2 | typhon/tests/arts/test_arts.py | typhon/tests/arts/test_arts.py | # -*- coding: utf-8 -*-
"""Testing the functions in typhon.arts.
"""
import shutil
import pytest
from typhon import arts
class TestPlots:
"""Testing the plot functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
... | # -*- coding: utf-8 -*-
"""Testing the functions in typhon.arts.
"""
import shutil
import pytest
from typhon import arts
class TestARTS:
"""Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system... | Fix name and description of ARTS tests. | Fix name and description of ARTS tests. | Python | mit | atmtools/typhon,atmtools/typhon |
1a6fa386de1c65edfdef695119b69dc124ac27fe | admin/common_auth/forms.py | admin/common_auth/forms.py | from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
... | from __future__ import absolute_import
from django import forms
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
wi... | Update common auth user registration form to show all potential Groups | Update common auth user registration form to show all potential Groups
| Python | apache-2.0 | erinspace/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,acshi/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,erinspace/osf.io,mfraezz/osf.io,felliott/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,hm... |
4d3753b7bd4ec37b7b8fde4eeab627bf96f8d12f | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def getPaths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
re... | # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
r... | Update in outputs and fix spaces and names. | Update in outputs and fix spaces and names.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli |
469fdc0dfc756e68231eebd5ce40eb33e0fdd2f2 | fireplace/cards/gvg/rogue.py | fireplace/cards/gvg/rogue.py | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
##
# Spells
# Tinker's Sharpsword Oil
class GVG_022:
action = buffWeapon("GVG_022a")
def action(self):
if self.controller.weapon:
self.buff(self.controller.weapon, "GVG_022a")
if self.controller.field... | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
# One-eyed Cheat
class GVG_025:
def OWN_MINION_SUMMON(self, player, minion):
if minion.race == Race.PIRATE and minion != self:
self.stealth = True
# Iron Sensei
class GVG_027:
def OWN_TURN_END(self):
... | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
| Python | agpl-3.0 | beheh/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,butozerca/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,smallnamespace/fireplace,amw2104/fireplace,amw2104/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Ragowit/fi... |
09618bd6cdef2025ea02a999a869c9c6a0560989 | mockserver/manager.py | mockserver/manager.py | from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manage... | from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manage... | Fix bug: file encoding is GBK on windows system. | Fix bug: file encoding is GBK on windows system.
| Python | apache-2.0 | IfengAutomation/mockserver,IfengAutomation/mockserver,IfengAutomation/mockserver |
c262e1d4c1c7422675728298019ee674242b68dd | examples/framework/faren/faren.py | examples/framework/faren/faren.py | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__changed(self, entry, ... | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__insert_text(self, ent... | Use insert_text instead of changed | Use insert_text instead of changed
| Python | lgpl-2.1 | Schevo/kiwi,Schevo/kiwi,Schevo/kiwi |
03a286a27e496da78efbed0ca4e4557ee4121e5c | stack/stack.py | stack/stack.py |
class Node(object):
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class Stack(object):
def __init__(self, head=None):
self.head = head
def push(self, data):
self.head = Node(data, self.head)
def pop(self):
if se... | import sys
class Node(object):
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class Stack(object):
def __init__(self, head=None):
self.head = head
def push(self, data):
self.head = Node(data, self.head)
def pop(self):
... | Add main block to handle CodeEval inputs | Add main block to handle CodeEval inputs
| Python | mit | MikeDelaney/CodeEval |
c1343c392a45d2069b893841f82bf426462bef55 | threadmanager.py | threadmanager.py | import logsupport
from logsupport import ConsoleWarning
HelperThreads = {}
class ThreadItem(object):
def __init__(self, name, start, restart):
self.name = name
self.StartThread = start
self.RestartThread = restart
self.Thread = None
def CheckThreads():
for T in HelperThreads.values():
if not T.Thread.is_... | import logsupport
from logsupport import ConsoleWarning
HelperThreads = {}
class ThreadItem(object):
def __init__(self, name, start, restart):
self.name = name
self.StartThread = start
self.RestartThread = restart
self.Thread = None
def StopThread(self):
self.Thread.stop()
def CheckThreads():
for T in ... | Add a stop thread - may be needed for loss of heartbeat case | Add a stop thread - may be needed for loss of heartbeat case
| Python | apache-2.0 | kevinkahn/softconsole,kevinkahn/softconsole |
bb70a61434f297bdcf30ccc7b95131be75c1f13b | passpie/validators.py | passpie/validators.py | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<bran... | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<bran... | Remove loading config from ".passpie/.config" if db set | Remove loading config from ".passpie/.config" if db set
| Python | mit | marcwebbie/passpie,scorphus/passpie,marcwebbie/passpie,scorphus/passpie |
799e79b03a753e5e8ba09a436e325e304a1148d6 | apiserver/worker/grab_config.py | apiserver/worker/grab_config.py | """
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/hal... | """
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/hal... | Determine GPU presence on workers based on instance metadata | Determine GPU presence on workers based on instance metadata
| Python | mit | lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,Halit... |
65bb7bc1c7e10756a3e172bfe0bf0cc64d03e178 | eve_neo4j/utils.py | eve_neo4j/utils.py | # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREAT... | # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREAT... | Convert every datetime field into float. | Convert every datetime field into float.
| Python | mit | Abraxas-Biosystems/eve-neo4j,Grupo-Abraxas/eve-neo4j |
3ec857dd32330ad2321a471c05c13dad3ee5b58e | tests/test_postgres_processor.py | tests/test_postgres_processor.py | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
engine = create_engine('postgresql://lo... | import pytest
# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
NORMALIZED = NormalizedDocument(uti... | Remove sqlalchemy test db setup | Remove sqlalchemy test db setup
| Python | apache-2.0 | erinspace/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi |
36675bf7be5b22f34205b8c1ff22175a4828962f | web/impact/impact/permissions/v1_api_permissions.py | web/impact/impact/permissions/v1_api_permissions.py | from accelerator_abstract.models.base_user_utils import is_employee
from impact.permissions import (
settings,
BasePermission)
class V1APIPermissions(BasePermission):
authenticated_users_only = True
def has_permission(self, request, view):
return request.user.groups.filter(
name=s... | from accelerator_abstract.models.base_user_utils import is_employee
from accelerator_abstract.models.base_user_role import is_finalist_user
from impact.permissions import (
settings,
BasePermission)
class V1APIPermissions(BasePermission):
authenticated_users_only = True
def has_permission(self, reque... | Add finalists to v1 user group | [AC-7071] Add finalists to v1 user group
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
03dcdca0f51ca40a2e3fee6da3182197d69de21d | pytrmm/__init__.py | pytrmm/__init__.py | """Package tools for reading TRMM data.
"""
try:
from __dev_version import version as __version__
from __dev_version import git_revision as __git_revision__
except ImportError:
from __version import version as __version__
from __version import git_revision as __git_revision__
import trmm3b4xrt
| """Package tools for reading TRMM data.
"""
try:
from __dev_version import version as __version__
from __dev_version import git_revision as __git_revision__
except ImportError:
from __version import version as __version__
from __version import git_revision as __git_revision__
from trmm3b4xrt import *... | Put file reader class into top-level namespace | ENH: Put file reader class into top-level namespace
| Python | bsd-3-clause | sahg/pytrmm |
77c0c6087b385eb7d61ff3f08655312a9d9250f5 | libravatar/urls.py | libravatar/urls.py | # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar 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
# ... | # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar 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
# ... | Remove the admin from the url resolver | Remove the admin from the url resolver
| Python | agpl-3.0 | libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar |
841235452d92ea4e40853c8df51568e01b39dba8 | stackoverflow/21180496/except.py | stackoverflow/21180496/except.py | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Convert top-level-comment to a docstring. | Convert top-level-comment to a docstring.
| Python | apache-2.0 | mbrukman/stackexchange-answers,mbrukman/stackexchange-answers |
e664c5ec6bb90f65ab159fdf332c06d4bd0f42e2 | td_biblio/urls.py | td_biblio/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
# Entry List
url(
'^$',
views.EntryListView.as_view(),
name='entry_list'
),
url(
'^import$',
views.EntryBatchImportView.as_view(),
name='import'
),
url(... | # -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
app_name = 'td_biblio'
urlpatterns = [
# Entry List
url(
'^$',
views.EntryListView.as_view(),
name='entry_list'
),
url(
'^import$',
views.EntryBatchImportView.as_view(),
name='i... | Add app_name url to td_biblio | Add app_name url to td_biblio
| Python | mit | TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio |
ba5260f5935de1cb1a068f0350cfe8d962e15805 | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__v... | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__v... | Implement UpperCamelCase name check for protocols | Implement UpperCamelCase name check for protocols
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
8f2fcb6f377c93e36612bd815fe810afba56e355 | pyflation/__init__.py | pyflation/__init__.py | """ Pyflation - Cosmological simulations in Python
Author: Ian Huston
Pyflation is a python package to simulate cosmological perturbations in the early universe.
Using the Klein-Gordon equations for both first and second order perturbations,
the evolution and behaviour of these perturbations can be studied.
The main... | """ Pyflation - Cosmological simulations in Python
Author: Ian Huston
Pyflation is a python package to simulate cosmological perturbations in the early universe.
Using the Klein-Gordon equations for both first and second order perturbations,
the evolution and behaviour of these perturbations can be studied.
The main... | Add version to package documentation. | Add version to package documentation.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation |
b8ca257a1a2727a9caa043739463e8cdf49c8d5a | news/middleware.py | news/middleware.py | from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, v... | from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, v... | Add statsd data for (in)secure requests | Add statsd data for (in)secure requests
| Python | mpl-2.0 | glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket |
5cca245f84a87f503c8e16577b7dba635d689a26 | opencc/__main__.py | opencc/__main__.py | from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from... | from __future__ import print_function
import argparse
import sys
import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original... | Add support for Python 2.6 and 2.7 | Add support for Python 2.6 and 2.7
Remove the following error when using Python 2.6 and 2.7.
TypeError: 'encoding' is an invalid keyword argument for this function
Python 3 operation is unchanged
| Python | apache-2.0 | yichen0831/opencc-python |
cb9933852e0f8c46081f084ea1f365873582daf8 | opps/core/admin.py | opps/core/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'publis... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (a... | Fix bug 'auto field does not accept 0 value' | Fix bug 'auto field does not accept 0 value'
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps |
446eab8e384e28e6d679233ae0ae13dabaddb77d | .build/build.py | .build/build.py | #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plug... | #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plug... | Remove hack for sqpyte again | Remove hack for sqpyte again
Related: https://github.com/HPI-SWA-Lab/SQPyte/commit/1afdff01b989352e3d72ca7f2cc9c837471642c7
| Python | bsd-3-clause | HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak |
78e2cc736b7c3f5b0fdd2caa24cc9c1c003ca1b6 | test_proj/urls.py | test_proj/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'do... | try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),... | Support for Django > 1.4 for test proj | Support for Django > 1.4 for test proj
| Python | mit | django-admin-tools/django-admin-tools,django-admin-tools/django-admin-tools,miurahr/django-admin-tools,miurahr/django-admin-tools,django-admin-tools/django-admin-tools,glowka/django-admin-tools,glowka/django-admin-tools,eternalfame/django-admin-tools,eternalfame/django-admin-tools,miurahr/django-admin-tools,miurahr/dja... |
e23190cb42bc64f9f381f05e24849174af3e9ff5 | base/test_views.py | base/test_views.py | from django.test import TestCase
from splinter import Browser
class TestBaseViews(TestCase):
def setUp(self):
self.browser = Browser('chrome')
def tearDown(self):
self.browser.quit()
def test_home(self):
self.browser.visit('http://localhost:8000')
test_string = 'Hello, w... | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from splinter import Browser
class TestBaseViews(StaticLiveServerTestCase):
"""Integration test suite for testing the views in the app: base.
Test the url for home and the basefiles like robots.txt and hum... | Add the proper tests for the base app | Add the proper tests for the base app
| Python | mit | tosp/djangoTemplate,tosp/djangoTemplate |
8becd32fc042445d62b885bac12dac326b2dc1fa | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importM... | #!/usr/bin/env python
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importM... | Increase a bit verbosity of tests so people know which test failed | Increase a bit verbosity of tests so people know which test failed
| Python | lgpl-2.1 | nzjrs/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,thiblahute/pygobject,GNOME/pygobject,davidmalcolm/pygobject,GNOME/pygobject,sfeltman/pygobject,MathieuDuponchelle/pygobject,jdahlin/pygobject,Distrotech/pygobject,sfeltman/pygobject,davibe/py... |
cb1142d5ac8d144e5ab0fc95ceed156c855b6bd2 | randomize-music.py | randomize-music.py | #!/usr/bin/env python
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for file_name in os.listdir(dir_name):
rand_name = uuid.uuid4().hex
src = os.path.join(dir_name, file_name)
subprocess.check_call(['eyeD3', '--artist', rand_name,... | #!/usr/bin/env python
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for root, dirs, files in os.walk(dir_name):
for file_name in files:
rand_name = uuid.uuid4().hex
src = os.path.join(root, file_name)
if src.en... | Generalize randomize script to work recursively and on more than just music | Generalize randomize script to work recursively and on more than just music
| Python | mit | cataliniacob/misc,cataliniacob/misc |
215622e070860cb24c032186d768c6b341ad27fb | nemubot.py | nemubot.py | #!/usr/bin/python3
# coding=utf-8
import sys
import os
import imp
import traceback
servers = dict()
print ("Nemubot ready, my PID is %i!" % (os.getpid()))
prompt = __import__ ("prompt")
while prompt.launch(servers):
try:
imp.reload(prompt)
except:
print ("Unable to reload the prompt due to er... | #!/usr/bin/python3
# coding=utf-8
import sys
import os
import imp
import traceback
servers = dict()
prompt = __import__ ("prompt")
if len(sys.argv) >= 2:
for arg in sys.argv[1:]:
prompt.load_file(arg, servers)
print ("Nemubot ready, my PID is %i!" % (os.getpid()))
while prompt.launch(servers):
try:... | Load files given in arguments | Load files given in arguments
| Python | agpl-3.0 | nemunaire/nemubot,nbr23/nemubot,Bobobol/nemubot-1 |
05ec1e93e04b829b8a71f6837409de1b5c8ead5d | bndl/compute/tests/__init__.py | bndl/compute/tests/__init__.py | import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addr... | import sys
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
# Increase switching interval to lure out race conditions a bit ...
cls._old_switchinterval = sys.... | Increase switching interval to lure out race conditions a bit ... | Increase switching interval to lure out race conditions a bit ...
| Python | apache-2.0 | bndl/bndl,bndl/bndl |
de841f77f6c3eaf60e563fd5cac0d9cb73dac240 | cairis/core/PasswordManager.py | cairis/core/PasswordManager.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... | # 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... | Revert database password policy while problems with keyring investigated | Revert database password policy while problems with keyring investigated
| Python | apache-2.0 | failys/CAIRIS,failys/CAIRIS,failys/CAIRIS |
3966d9e77455f36a159d960242849e59ac323c0a | ed2d/physics/physengine.py | ed2d/physics/physengine.py | from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree... | from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree... | Change multi line string to be regular comment. | Change multi line string to be regular comment.
| Python | bsd-2-clause | explosiveduck/ed2d,explosiveduck/ed2d |
7fad37d5a1121fe87db8946645043cd31a78b093 | pi_gpio/events.py | pi_gpio/events.py | from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
... | from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
... | Set the default bouncetime value to -666 | Set the default bouncetime value to -666
Set the default bouncetime to -666 (the default value -666 is in Rpi.GPIO source code).
As-Is: if the bouncetime is not set, your setting for event detecting is silently down. And there is no notification that bouncetime is required. | Python | mit | projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server |
61241b16d3bcef221ab07efe8e12d7ec7c2b6e64 | labonneboite/common/siret.py | labonneboite/common/siret.py |
def is_siret(siret):
# A valid SIRET is composed by 14 digits
try:
int(siret)
except ValueError:
return False
return len(siret) == 14
|
def is_siret(siret):
# A valid SIRET is composed by 14 digits
return len(siret) == 14 and siret.isdigit()
| Use isdigit() instead of int() | Use isdigit() instead of int()
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite |
d901683430c8861b88b577965201bb7acf17e7f8 | print_version.py | print_version.py | """
Get the version string from versioneer and print it to stdout
"""
import versioneer
versioneer.VCS = 'git'
versioneer.tag_prefix = 'v'
versioneer.versionfile_source = 'version.py' # This line is useless
versioneer.parentdir_prefix = 'tesseroids-'
version = versioneer.get_version()
if version == 'master':
# Whe... | """
Get the version string from versioneer and print it to stdout
"""
import sys
import os
# Make sure versioneer is imported from here
here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, here)
import versioneer
versioneer.VCS = 'git'
versioneer.tag_prefix = 'v'
versioneer.versionfile_source = 'versi... | Make sure versioneer is imported from here | Make sure versioneer is imported from here
| Python | bsd-3-clause | leouieda/tesseroids,leouieda/tesseroids,leouieda/tesseroids |
8034684b9c1c798b9f825111df53415a1a3ff9eb | pymogilefs/connection.py | pymogilefs/connection.py | from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.... | from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.... | Break after receiving no bytes to prevent hanging | Break after receiving no bytes to prevent hanging
| Python | mit | bwind/pymogilefs,bwind/pymogilefs |
7a9d3373fb2e11cad694aa1c65901d6cd57beb7c | tests/test_numba_parallel_issues.py | tests/test_numba_parallel_issues.py |
from hypothesis import given
from hypothesis.strategies import integers
from numba import jit
import numpy as np
@jit(nopython=True, parallel=True)
def get(n):
return np.ones((n,1), dtype=np.float64)
@given(integers(min_value=10, max_value=100000))
def test_all_ones(x):
"""
We found one of the scaling... |
import sys
from hypothesis import given
from hypothesis.strategies import integers
from numba import jit
import numpy as np
# Parallel not supported on 32-bit Windows
parallel = not (sys.platform == 'win32')
@jit(nopython=True, parallel=True)
def get(n):
return np.ones((n,1), dtype=np.float64)
@given(integ... | Add guard for parallel kwarg on 32-bit Windows | Add guard for parallel kwarg on 32-bit Windows
| Python | mit | fastats/fastats,dwillmer/fastats |
810e3516e5f466a145d649edbb00fc3ade1a7a68 | services/disqus.py | services/disqus.py | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provide... | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provide... | Rewrite Disqus to use the new scope selection system | Rewrite Disqus to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org |
cc392b38791e465acb579a7e2f4f9b2f32c70c42 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
if __name__ == "__main__":
app.run()
| from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
def parse_reflog():
pass
if __name__ == "__main__":
app.run()
| Add template for parse_reflog function | Add template for parse_reflog function
| Python | bsd-3-clause | kdheepak89/c3.py,kdheepak89/c3.py |
9da4bbe2c5d8dbfe6436ff4fe5e1387178009897 | employees/tests.py | employees/tests.py | from .models import Employee
from rest_framework.test import APITestCase
class EmployeeTestCase(APITestCase):
def setUp(self):
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Employee.objects.create_superuser('user2', 'user2@email.com', 'user2password')
def test... | from .models import Employee
from categories.models import Category
from rest_framework.test import APITestCase
class EmployeeTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Empl... | Fix category dependency for employee creation flow in testing | Fix category dependency for employee creation flow in testing
| Python | apache-2.0 | belatrix/BackendAllStars |
5ab1df0c4a130b4cd32b01805f5749d29795a393 | x256/test_x256.py | x256/test_x256.py | from twisted.trial import unittest
import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, 135]
... | from twisted.trial import unittest
from x256 import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, ... | Fix some bugs in tests | Fix some bugs in tests
| Python | mit | magarcia/python-x256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.