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 |
|---|---|---|---|---|---|---|---|---|---|
6384e6a23f73eddf1099e01ed0d8c067141651a5 | tcelery/__init__.py | tcelery/__init__.py | from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION)) + '-dev'
def setup_nonblocking_producer(celery_app=None... | from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 3, 4)
__version__ = '.'.join(map(str, VERSION))
def setup_nonblocking_producer(celery_app=None, io_loop... | Set release version to 0.3.4 | Set release version to 0.3.4
| Python | bsd-3-clause | shnjp/tornado-celery,qudos-com/tornado-celery,mher/tornado-celery,sangwonl/tornado-celery |
eb25c6900b307792821f7db6bcfa92cc62a80298 | lims/pricebook/views.py | lims/pricebook/views.py |
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from lims.permissions.permissions import IsInAdminGroupOrRO
from lims.shared.mixins import AuditTrailViewMixin
from .models import PriceBook
from .serializers import PriceBookSerializer
f... | from django.conf import settings
from simple_salesforce import Salesforce
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from lims.permissions.permissions import IsInAdminGroupOrRO
from lims.shared.mixins import AuditTrailViewMixin
f... | Add list crm pricebooks endpoint and update pricebook fetching | Add list crm pricebooks endpoint and update pricebook fetching
| Python | mit | GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend |
07dc719807a6d890fa33338746caca61704de0a1 | src/genbank-gff-to-nquads.py | src/genbank-gff-to-nquads.py | #!/usr/bin/env python
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
components = reco... | #!/usr/bin/env python
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
locusTagAttributeKey = 'locus_tag'
components =... | Move locus tag attribute key name into the function that uses it | Move locus tag attribute key name into the function that uses it
| Python | apache-2.0 | justinccdev/biolta |
af85d44d9a6f7cf65fe504816bcf4a10ba603d51 | pdfdocument/utils.py | pdfdocument/utils.py | import re
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
FILENAME_RE = re.compile(r'[^A-Za-z0-9\-\.]+')
def pdf_response(filename, as_attachment=True, **kwargs):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = '%s; filename="%s.pd... | import re
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
FILENAME_RE = re.compile(r'[^A-Za-z0-9\-\.]+')
def pdf_response(filename, as_attachment=True, pdfdocument=PDFDocument,
**kwargs):
response = HttpResponse(content_type='application/pdf')
response['Content-Di... | Make the PDFDocument class used in pdf_response configurable | Make the PDFDocument class used in pdf_response configurable
| Python | bsd-3-clause | matthiask/pdfdocument,dongguangming/pdfdocument |
d4e8839ac02935b86c1634848476a9a8512c376d | delivery_transsmart/models/res_partner.py | delivery_transsmart/models/res_partner.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Delivery Transsmart Ingegration
# © 2016 - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gene... | # -*- coding: utf-8 -*-
##############################################################################
#
# Delivery Transsmart Ingegration
# © 2016 - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gene... | Remove double product field definitions | [DEL] Remove double product field definitions
| Python | agpl-3.0 | 1200wd/1200wd_addons,1200wd/1200wd_addons |
b8d73fb12fa91a6f0aa33ed985dd5521843e05b8 | src/zeit/content/dynamicfolder/browser/tests/test_folder.py | src/zeit/content/dynamicfolder/browser/tests/test_folder.py | import zeit.cms.interfaces
import zeit.cms.testing
import zeit.content.dynamicfolder.testing
class EditDynamicFolder(zeit.cms.testing.BrowserTestCase):
layer = zeit.content.dynamicfolder.testing.DYNAMIC_LAYER
def test_check_out_and_edit_folder(self):
b = self.browser
b.open('http://localhost... | import zeit.cms.interfaces
import zeit.cms.testing
import zeit.content.dynamicfolder.testing
class EditDynamicFolder(zeit.cms.testing.BrowserTestCase):
layer = zeit.content.dynamicfolder.testing.DYNAMIC_LAYER
def test_check_out_and_edit_folder(self):
b = self.browser
b.open('http://localhost... | Remove superfluous test setup after zeit.cms got smarter | MAINT: Remove superfluous test setup after zeit.cms got smarter
| Python | bsd-3-clause | ZeitOnline/zeit.content.dynamicfolder |
1a1a45fe5175d002c239610be487607dbb7cdde1 | thinc/neural/_classes/feed_forward.py | thinc/neural/_classes/feed_forward.py | from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X[:1000])
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that ch... | from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X)
if hasattr(X, 'shape'):
X = model.ops.xp.ascontiguousarray(X)
@describe.on_data(_run_ch... | Make copy of X in feed-forward | Make copy of X in feed-forward
| Python | mit | spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc |
c862a4c40f17040017e9bb6f67f5b9fa293c23e5 | mcb_interface/driver.py | mcb_interface/driver.py | #!/usr/bin/env python3
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(0.1, 0)
print "Battery Voltage: ", battery_millivolts[0], " V... | #!/usr/bin/env python3
from romi import Romi
romi = Romi()
from time import sleep
# from math import pi
while True:
battery_millivolts = romi.read_battery_millivolts()
v_x, v_theta, x, y, theta = romi.read_odometry()
romi.velocity_command(1.0, 0)
print "Battery Voltage: ", battery_millivolts[0], " V... | Add more output printing, increase velocity command. | Add more output printing, increase velocity command.
| Python | mit | waddletown/sw |
5f888f5ee388efa046bc9e0de0622e5c8b66d712 | src/viewsapp/views.py | src/viewsapp/views.py | from django.shortcuts import (
get_object_or_404, render)
from django.views.decorators.http import \
require_http_methods
from .models import ExampleModel
@require_http_methods(['GET', 'HEAD'])
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_4... | from django.shortcuts import (
get_object_or_404, render)
from django.views.decorators.http import \
require_safe
from .models import ExampleModel
@require_safe
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=re... | Switch HTTP restriction decorator to require_safe. | Switch HTTP restriction decorator to require_safe.
| Python | bsd-2-clause | jambonrose/djangocon2015-views,jambonrose/djangocon2015-views |
b2df5972bcc9f3367c3832719d1590410317bbba | swift/obj/dedupe/fp_index.py | swift/obj/dedupe/fp_index.py | __author__ = 'mjwtom'
import sqlite3
import unittest
class fp_index:
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.execute('''C... | __author__ = 'mjwtom'
import sqlite3
import unittest
class Fp_Index(object):
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.exec... | Use database to detect the duplication. But the md5 value does not match. Need to add some code here | Use database to detect the duplication. But the md5 value does not match. Need to add some code here
| Python | apache-2.0 | mjwtom/swift,mjwtom/swift |
bdee8b95429a6ac96cb0577e7eddbd25b764ebfc | mirrit/web/models.py | mirrit/web/models.py | from humbledb import Mongo, Document
class User(Document):
username = ''
password = ''
email = ''
config_database = 'mirrit'
config_collection = 'users'
@property
def id(self):
return unicode(self._id)
@property
def user_id(self):
return unicode(self._id)
@st... | from bson.objectid import ObjectId
from humbledb import Mongo, Document
class ClassProperty (property):
"""Subclass property to make classmethod properties possible"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class User(Document):
username = ''
password = ''
... | Fix stupid pseudo-django model crap in signup | Fix stupid pseudo-django model crap in signup
| Python | bsd-3-clause | 1stvamp/mirrit |
f76bba08c1a8cfd3c821f641adb2b10e3cfa47b9 | tests/test_base_os.py | tests/test_base_os.py | from .fixtures import elasticsearch
def test_base_os(host):
assert host.system_info.distribution == 'centos'
assert host.system_info.release == '7'
def test_java_home_env_var(host):
java_path_cmdline = '$JAVA_HOME/bin/java -version'
assert host.run(java_path_cmdline).exit_status == 0
| from .fixtures import elasticsearch
def test_base_os(host):
assert host.system_info.distribution == 'centos'
assert host.system_info.release == '7'
def test_java_home_env_var(host):
java_path_cmdline = '$JAVA_HOME/bin/java -version'
assert host.run(java_path_cmdline).exit_status == 0
def test_no_... | Add acceptance test to ensure image doesn't contain core files in / | Add acceptance test to ensure image doesn't contain core files in /
In some occasions, depending on the build platform (noticed with aufs with old docker-ce versions) may create a /corefile.<pid>.
Fail a build if the produced image containers any /core* files.
Relates #97 | Python | apache-2.0 | jarpy/elasticsearch-docker,jarpy/elasticsearch-docker |
5fc80b347191761d848f6bf736358ec1ec351f33 | fbmsgbot/bot.py | fbmsgbot/bot.py | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
print error
... | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
if error is n... | Remove print statments and fix completion logic | Remove print statments and fix completion logic
| Python | mit | ben-cunningham/pybot,ben-cunningham/python-messenger-bot |
a32831dbf6b46b33691a76e43012e9fbbbc80e17 | superlists/lists/tests.py | superlists/lists/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
class SmokeTest(TestCase):
def test_bad_maths(self):
self.assertEqual(1 + 1, 3)
| Add app for lists, with deliberately failing unit test | Add app for lists, with deliberately failing unit test
| Python | mit | jrwiegand/tdd-project,jrwiegand/tdd-project,jrwiegand/tdd-project |
41cf41f501b715902cf180b5a2f62ce16a816f30 | oscar/core/prices.py | oscar/core/prices.py | class TaxNotKnown(Exception):
"""
Exception for when a tax-inclusive price is requested but we don't know
what the tax applicable is (yet).
"""
class Price(object):
"""
Simple price class that encapsulates a price and its tax information
Attributes:
incl_tax (Decimal): Price inclu... | class TaxNotKnown(Exception):
"""
Exception for when a tax-inclusive price is requested but we don't know
what the tax applicable is (yet).
"""
class Price(object):
"""
Simple price class that encapsulates a price and its tax information
Attributes:
incl_tax (Decimal): Price inclu... | Define __repr__ for the core Price class | Define __repr__ for the core Price class
| Python | bsd-3-clause | saadatqadri/django-oscar,WillisXChen/django-oscar,adamend/django-oscar,sasha0/django-oscar,faratro/django-oscar,bnprk/django-oscar,jinnykoo/christmas,jinnykoo/wuyisj.com,WillisXChen/django-oscar,WadeYuChen/django-oscar,taedori81/django-oscar,taedori81/django-oscar,bschuon/django-oscar,WadeYuChen/django-oscar,WillisXChe... |
836e946e5c6bfb6b097622193a4239c7eba1ca9a | thinglang/parser/blocks/handle_block.py | thinglang/parser/blocks/handle_block.py | from thinglang.compiler.buffer import CompilationBuffer
from thinglang.compiler.opcodes import OpcodeJump, OpcodePopLocal
from thinglang.lexer.blocks.exceptions import LexicalHandle
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import Par... | from thinglang.compiler.buffer import CompilationBuffer
from thinglang.compiler.opcodes import OpcodeJump, OpcodePopLocal, OpcodePop
from thinglang.lexer.blocks.exceptions import LexicalHandle
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule... | Add missing void pop in uncaptured exception blocks | Add missing void pop in uncaptured exception blocks
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
44110a305b5a23609c5f6366da9d746244807dbb | power/__init__.py | power/__init__.py | # coding=utf-8
"""
Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate.
Allows you to add observer for power notifications if platform supports it.
Usage:
from power import PowerManagement, PowerManagementObserver # Automatically imports platform-speci... | # coding=utf-8
"""
Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate.
Allows you to add observer for power notifications if platform supports it.
Usage:
from power import PowerManagement, PowerManagementObserver # Automatically imports platform-speci... | Use PowerManagementNoop on import errors | Use PowerManagementNoop on import errors
Platform implementation can fail to import its dependencies.
| Python | mit | Kentzo/Power |
0f7ba6290696e1ce75e42327fdfc4f9eae8614c3 | pdfdocument/utils.py | pdfdocument/utils.py | from datetime import date
import re
from django.db.models import Max, Min
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('dat... | from datetime import date
import re
from django.db.models import Max, Min
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('dat... | Allow passing initialization kwargs to PDFDocument through pdf_response | Allow passing initialization kwargs to PDFDocument through pdf_response
| Python | bsd-3-clause | matthiask/pdfdocument,dongguangming/pdfdocument |
edfd2edc5496cb412477b7409f43aa53acf7dea9 | tests/test_loadproblem.py | tests/test_loadproblem.py | # -*- coding: utf-8 -*-
import unittest
import os
from mathdeck import loadproblem
class TestMathdeckLoadProblem(unittest.TestCase):
def test_loadproblem_has_answers_attribute(self):
file_name = 'has_answers_attribute.py'
problem_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
... | # -*- coding: utf-8 -*-
import unittest
import os
from mathdeck import loadproblem
class TestMathdeckLoadProblem(unittest.TestCase):
def test_loadproblem_has_answers_attribute(self):
file_name = 'has_answers_attribute.py'
file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
... | Fix parameter values for load function | Fix parameter values for load function
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck |
503f92796b9368a78f39c41fb6bb596f32728b8d | herana/views.py | herana/views.py | import json
from django.shortcuts import render
from django.views.generic import View
from models import Institute, ProjectDetail
from forms import SelectInstituteForm, SelectOrgLevelForm
def home(request):
return render(request, 'index.html')
class ResultsView(View):
template_name = 'results.html'
def... | import json
from django.shortcuts import render
from django.views.generic import View
from models import Institute, ProjectDetail
from forms import SelectInstituteForm, SelectOrgLevelForm
def home(request):
return render(request, 'index.html')
class ResultsView(View):
template_name = 'results.html'
def... | Check if user in logged in | Check if user in logged in
| Python | mit | Code4SA/herana,Code4SA/herana,Code4SA/herana,Code4SA/herana |
562a0868b3648e3ba40c29289ba7f4ebd4c75800 | pyinfra/api/__init__.py | pyinfra/api/__init__.py | # pyinfra
# File: pyinfra/api/__init__.py
# Desc: import some stuff
from .config import Config # noqa: F401
from .deploy import deploy # noqa: F401
from .exceptions import ( # noqa: F401
DeployError,
InventoryError,
OperationError,
)
from .facts import FactBase # noqa: F401
from .inventory import Inven... | # pyinfra
# File: pyinfra/api/__init__.py
# Desc: import some stuff
from .config import Config # noqa: F401
from .deploy import deploy # noqa: F401
from .exceptions import ( # noqa: F401
DeployError,
InventoryError,
OperationError,
)
from .facts import FactBase, ShortFactBase # noqa: F401
from .invento... | Add `ShortFactBase` import to `pyinfra.api`. | Add `ShortFactBase` import to `pyinfra.api`.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
663a61362c30b737f2532de42b5b680795ccf608 | quran_text/models.py | quran_text/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.db import models
class Sura(models.Model):
"""
Model to hold the Quran Chapters "Sura"
"""
index = models.PositiveIntegerField(primary_key=True)
name = models.CharFie... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.db import models
class Sura(models.Model):
"""
Model to hold the Quran Chapters "Sura"
"""
index = models.PositiveIntegerField(primary_key=True)
name = models.CharFie... | Add ordering to Ayah model | Add ordering to Ayah model
| Python | mit | EmadMokhtar/tafseer_api |
ddabef55b9dde75af422d4dedb2d5578d7019905 | tests/test_authentication.py | tests/test_authentication.py | import unittest
from flask import json
from api import db
from api.BucketListAPI import app
from instance.config import application_config
class AuthenticationTestCase(unittest.TestCase):
def setUp(self):
app.config.from_object(application_config['TestingEnv'])
self.client = app.test_client()
... | import unittest
from flask import json
from api import db
from api.BucketListAPI import app
from instance.config import application_config
class AuthenticationTestCase(unittest.TestCase):
def setUp(self):
app.config.from_object(application_config['TestingEnv'])
self.client = app.test_client()
... | Add test for invalid email | Add test for invalid email
| Python | mit | patlub/BucketListAPI,patlub/BucketListAPI |
adcba0285ef700738a63986c7657bd9e5ac85d85 | wikipendium/user/forms.py | wikipendium/user/forms.py | from django.forms import Form, CharField, ValidationError
from django.contrib.auth.models import User
class UserChangeForm(Form):
username = CharField(max_length=30, label='New username')
def clean(self):
cleaned_data = super(UserChangeForm, self).clean()
if User.objects.filter(username=clea... | from django.forms import Form, CharField, EmailField, ValidationError
from django.contrib.auth.models import User
class UserChangeForm(Form):
username = CharField(max_length=30, label='New username')
def clean(self):
cleaned_data = super(UserChangeForm, self).clean()
if User.objects.filter(u... | Use EmailField for email validation | Use EmailField for email validation
| Python | apache-2.0 | stianjensen/wikipendium.no,stianjensen/wikipendium.no,stianjensen/wikipendium.no |
945baec1540ff72b85b3d0563511d93cb33d660e | nbgrader/tests/formgrader/fakeuser.py | nbgrader/tests/formgrader/fakeuser.py | import os
from jupyterhub.auth import LocalAuthenticator
from jupyterhub.spawner import LocalProcessSpawner
from tornado import gen
class FakeUserAuth(LocalAuthenticator):
"""Authenticate fake users"""
@gen.coroutine
def authenticate(self, handler, data):
"""If the user is on the whitelist, authe... | import os
from jupyterhub.auth import LocalAuthenticator
from jupyterhub.spawner import LocalProcessSpawner
from tornado import gen
class FakeUserAuth(LocalAuthenticator):
"""Authenticate fake users"""
@gen.coroutine
def authenticate(self, handler, data):
"""If the user is on the whitelist, authe... | Remove os.setpgrp() from fake spawner | Remove os.setpgrp() from fake spawner
| Python | bsd-3-clause | jhamrick/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jupyter/nbgrader |
1bbf986cbde2d0ec8add3ac845cb10fcd061e46d | nodeconductor/server/test_settings.py | nodeconductor/server/test_settings.py | # Django test settings for nodeconductor project.
from nodeconductor.server.doc_settings import *
INSTALLED_APPS += (
'nodeconductor.quotas.tests',
'nodeconductor.structure.tests',
)
ROOT_URLCONF = 'nodeconductor.structure.tests.urls'
| # Django test settings for nodeconductor project.
from nodeconductor.server.doc_settings import *
INSTALLED_APPS += (
'nodeconductor.quotas.tests',
'nodeconductor.structure.tests',
)
ROOT_URLCONF = 'nodeconductor.structure.tests.urls'
# XXX: This option should be removed after itacloud assembly creation.
NO... | Add "IS_ITACLOUD" flag to settings | Add "IS_ITACLOUD" flag to settings
- itacloud-7125
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
cdfd622f4e7017ab1860e1f7420d6f26424a69f1 | dashboard_app/extension.py | dashboard_app/extension.py | from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bund... | from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bund... | Move support for dataview-specific database from lava-server | Move support for dataview-specific database from lava-server
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server |
419d2ca4d53e33c58d556b45bcc6910bd28ef91a | djangae/apps.py | djangae/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from .patches.contenttypes import patch
patch()
from djangae.db.backends.appengine.caching import... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from .patches.contenttypes import patch
patch()
from djangae.db.backends.appengine.caching import... | Make sure we only connect to the signals onces | Make sure we only connect to the signals onces
| Python | bsd-3-clause | kirberich/djangae,asendecka/djangae,asendecka/djangae,SiPiggles/djangae,wangjun/djangae,potatolondon/djangae,kirberich/djangae,SiPiggles/djangae,SiPiggles/djangae,leekchan/djangae,armirusco/djangae,chargrizzle/djangae,trik/djangae,grzes/djangae,armirusco/djangae,jscissr/djangae,trik/djangae,jscissr/djangae,wangjun/djan... |
d81a68a46fbdc98f803c94a2123b48cca6f5da31 | tests/aqdb/test_rebuild.py | tests/aqdb/test_rebuild.py | #!/ms/dist/python/PROJ/core/2.5.4-0/bin/python
"""Test module for rebuilding the database."""
import os
import __init__
import aquilon.aqdb.depends
import nose
import unittest
from subprocess import Popen, PIPE
class TestRebuild(unittest.TestCase):
def testrebuild(self):
env = {}
for (key, valu... | #!/ms/dist/python/PROJ/core/2.5.4-0/bin/python
"""Test module for rebuilding the database."""
import os
import __init__
import aquilon.aqdb.depends
import nose
import unittest
from subprocess import Popen, PIPE
from aquilon.config import Config
class TestRebuild(unittest.TestCase):
def testrebuild(self):
... | Fix aqdb rebuild to work when not using AQDCONF env variable. | Fix aqdb rebuild to work when not using AQDCONF env variable.
| Python | apache-2.0 | guillaume-philippon/aquilon,quattor/aquilon,quattor/aquilon,stdweird/aquilon,stdweird/aquilon,guillaume-philippon/aquilon,quattor/aquilon,stdweird/aquilon,guillaume-philippon/aquilon |
2db81321de1c506d6b61d8851de9ad4794deba3e | lmj/sim/base.py | lmj/sim/base.py | # Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | # Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | Allow for World to handle key presses. | Allow for World to handle key presses.
| Python | mit | EmbodiedCognition/pagoda,EmbodiedCognition/pagoda |
df58b36b6f62c39030d6ff28c6fb67c11f112df0 | pyxrf/gui_module/main_window.py | pyxrf/gui_module/main_window.py | from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self... | from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self... | Test window title on Mac | Test window title on Mac
| Python | bsd-3-clause | NSLS-II-HXN/PyXRF,NSLS-II/PyXRF,NSLS-II-HXN/PyXRF |
3005b947312c0219c6754e662496c876e46aafc4 | model/openacademy_session.py | model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
... | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
... | Add domain or and ilike | [REF] openacademy: Add domain or and ilike
| Python | apache-2.0 | luisll-vauxoo/openacademy |
7371244c00c94fdc552c5d146ab1a245b643427e | reeprotocol/ip.py | reeprotocol/ip.py | """IP Physical Layer
"""
from __future__ import absolute_import
import socket
from .protocol import PhysicalLayer
class Ip(PhysicalLayer):
"""IP Physical Layer"""
def __init__(self, addr):
"""Create an IP Physical Layer.
:addr tuple: Address tuple (host, port)
"""
self.addr = ... | """IP Physical Layer
"""
from __future__ import absolute_import
import socket
import queue
import threading
from .protocol import PhysicalLayer
class Ip(PhysicalLayer):
"""IP Physical Layer"""
def __init__(self, addr):
"""Create an IP Physical Layer.
:addr tuple: Address tuple (host, port)
... | Implement reading socket with threading | Implement reading socket with threading
| Python | agpl-3.0 | javierdelapuente/reeprotocol |
e2b691810f9d9a33f054bf245f1429d6999338a6 | dataproperty/_interface.py | dataproperty/_interface.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import six
from ._function import is_nan
from ._typecode import Typecode
@six.add_metaclass(abc.ABCMeta)
class DataPeropertyInterface(object):
__slots__ = ()
@abc.abstractpr... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import six
from ._function import is_nan
from ._typecode import Typecode
@six.add_metaclass(abc.ABCMeta)
class DataPeropertyInterface(object):
__slots__ = ()
@abc.abstractpr... | Delete property from the interface class | Delete property from the interface class
| Python | mit | thombashi/DataProperty |
367d8415773a44356ce604ecfc839117798f7d3a | tests/test_pytestplugin.py | tests/test_pytestplugin.py | from io import FileIO
from six import next
from pkg_resources import resource_filename, working_set
from wex.readable import EXT_WEXIN
from wex.output import EXT_WEXOUT
from wex import pytestplugin
def pytest_funcarg__parent(request):
return request.session
response = b"""HTTP/1.1 200 OK\r
Content-type: applicati... | from io import FileIO
from six import next
import pytest
from pkg_resources import resource_filename, working_set
from wex.readable import EXT_WEXIN
from wex.output import EXT_WEXOUT
from wex import pytestplugin
@pytest.fixture
def parent(request):
return request.session
response = b"""HTTP/1.1 200 OK\r
Content-t... | Replace funcarg with fixture for pytestplugin | Replace funcarg with fixture for pytestplugin
| Python | bsd-3-clause | gilessbrown/wextracto,eBay/wextracto,eBay/wextracto,gilessbrown/wextracto |
26eaaffb872d7046be9417ae53302e59dbc7b808 | TrainingDataGenerator/Scripts/generateNumberImage.py | TrainingDataGenerator/Scripts/generateNumberImage.py | # -*- coding: utf-8 -*-
import threading
import os
import shutil
from PIL import Image, ImageDraw2, ImageDraw, ImageFont
import random
count = range(0, 200)
path = './generatedNumberImages'
text = '0123456789X'
def start():
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
for idx in co... | # -*- coding: utf-8 -*-
import threading
import os
import shutil
from PIL import Image, ImageDraw2, ImageDraw, ImageFont, ImageEnhance
import random
count = range(0, 200)
path = './generatedNumberImages'
text = '0123456789X'
def start():
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
... | Add Image Enhance for generated image. | Add Image Enhance for generated image.
| Python | apache-2.0 | KevinGong2013/ChineseIDCardOCR,KevinGong2013/ChineseIDCardOCR,KevinGong2013/ChineseIDCardOCR |
4f84482803049b40d7b7da26d9d624a6a63b4820 | core/utils.py | core/utils.py | # -*- coding: utf-8 -*-
from django.utils import timezone
def duration_string(duration, precision='s'):
"""Format hours, minutes and seconds as a human-friendly string (e.g. "2
hours, 25 minutes, 31 seconds") with precision to h = hours, m = minutes or
s = seconds.
"""
h, m, s = duration_parts(dur... | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.utils.translation import ngettext
def duration_string(duration, precision='s'):
"""Format hours, minutes and seconds as a human-friendly string (e.g. "2
hours, 25 minutes, 31 seconds") with precision to h = hours, m = minutes or
s = sec... | Add translation support to `duration_string` utility | Add translation support to `duration_string` utility
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy |
786ebc992ac09cd4b25e90ee2a243447e39c237f | director/accounts/forms.py | director/accounts/forms.py | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
from django import forms
from accounts.models import Account, Team
from lib.data_cleaning import clean_slug, SlugType
from lib.forms import ModelFormWithCreate
class CleanNameMixin:
def clean_name(self):
return clea... | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, HTML, Submit
from django import forms
from accounts.models import Account, Team
from lib.data_cleaning import clean_slug, SlugType
from lib.forms import ModelFormWithCreate
from assets.thema import themes
class CleanNameMixin:
... | Add theme and hosts to settings | feat(Accounts): Add theme and hosts to settings
| Python | apache-2.0 | stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub |
c3c1b9c6a1d13f38cd50762b451ca19eb0a05ff2 | run_deploy_job_wr.py | run_deploy_job_wr.py | #!/usr/bin/env python
import json
import os
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
command = [
'$HOME/juju-ci-tools/run-deploy-job-remote.bash',
os.environ['revision_build'],
os.environ['JOB_NAME'],
]
command.extend(sys.argv[2:])
wi... | #!/usr/bin/env python
import json
import os
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix='juju-ci/products/version-{}/{}/build-{}'.format... | Update for more artifact support. | Update for more artifact support. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju |
41236c2be66b6f790308cba321cb482807814323 | ubersmith/calls/device.py | ubersmith/calls/device.py | """Device call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
... | """Device call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
... | Make module graph call return a file. | Make module graph call return a file.
| Python | mit | jasonkeene/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,hivelocity/python-ubersmith |
61a6d057302767aa49633d6d010f7da583035533 | web/templatetags/getattribute.py | web/templatetags/getattribute.py | import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif ha... | import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
if callable(getattr(value, arg)):
... | Call objects methods directly from the templates yay | web: Call objects methods directly from the templates yay
| Python | apache-2.0 | SchoolIdolTomodachi/SchoolIdolAPI,laurenor/SchoolIdolAPI,dburr/SchoolIdolAPI,laurenor/SchoolIdolAPI,rdsathene/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI,dburr/SchoolIdolAPI,laurenor/SchoolIdolAPI |
f4c989567fa77002541c5e5199f2fc3f8e53d6da | test_htmlgen/image.py | test_htmlgen/image.py | from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_eq... | from unittest import TestCase
from asserts import assert_equal
from htmlgen import Image
from test_htmlgen.util import parse_short_tag
class ImageTest(TestCase):
def test_attributes(self):
image = Image("my-image.png", "Alternate text")
assert_equal("my-image.png", image.url)
assert_eq... | Use public API in tests | [tests] Use public API in tests
| Python | mit | srittau/python-htmlgen |
8e2b9e1c80e3a91df7e2cce775c19208aa9d4839 | exam/asserts.py | exam/asserts.py | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __... | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __... | Change __exit__arg names to not be built ins | Change __exit__arg names to not be built ins
| Python | mit | gterzian/exam,Fluxx/exam,Fluxx/exam,gterzian/exam |
24d67552f1ae16179fb1aa21a06c191c6d596fb1 | akhet/urlgenerator.py | akhet/urlgenerator.py | """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, s... | """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, s... | Comment out 'static' and 'deform' methods; disagreements on long-term API. | Comment out 'static' and 'deform' methods; disagreements on long-term API.
| Python | mit | hlwsmith/akhet,hlwsmith/akhet,Pylons/akhet,hlwsmith/akhet,Pylons/akhet |
d7bec88009b73a57124dbfacc91446927328abf9 | src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py | src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py | # pylint: disable=no-self-use,too-many-arguments
from azure.mgmt.network.models import Subnet, SecurityRule
from ._factory import _network_client_factory
def create_update_subnet(resource_group_name, subnet_name, virtual_network_name, address_prefix):
'''Create or update a virtual network (VNet) subnet'''
subn... | # pylint: disable=no-self-use,too-many-arguments
from azure.mgmt.network.models import Subnet, SecurityRule
from ._factory import _network_client_factory
def create_update_subnet(resource_group_name, subnet_name, virtual_network_name, address_prefix):
'''Create or update a virtual network (VNet) subnet'''
subn... | Fix broken NSG create command (duplicate --name parameter) | Fix broken NSG create command (duplicate --name parameter)
| Python | mit | QingChenmsft/azure-cli,samedder/azure-cli,BurtBiel/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli,yugangw-msft/azure... |
cde815fd3c87cbe000620060f41bf2b29976555d | kindergarten-garden/kindergarten_garden.py | kindergarten-garden/kindergarten_garden.py | CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(student... | CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(student... | Use unpacking for simpler code | Use unpacking for simpler code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
31f6cc777054f4b48a37bb93453bcf405a9101a3 | examples/example_import.py | examples/example_import.py | import xkcdpass.xkcd_password as xp
import random
def random_capitalisation(s, chance):
new_str = []
for i, c in enumerate(s):
new_str.append(c.upper() if random.random() < chance else c)
return "".join(new_str)
words = xp.locate_wordfile()
mywords = xp.generate_wordlist(wordfile=words, min_leng... | import xkcdpass.xkcd_password as xp
import random
def random_capitalisation(s, chance):
new_str = []
for i, c in enumerate(s):
new_str.append(c.upper() if random.random() < chance else c)
return "".join(new_str)
def capitalize_first_letter(s):
new_str = []
s = s.split(" ")
for i, c in... | Add "capitalize first letter" function to examples | Add "capitalize first letter" function to examples
| Python | bsd-3-clause | amiryal/XKCD-password-generator,amiryal/XKCD-password-generator |
520487df7b9612e18dc06764ba8632b0ef28aad2 | solvent/bring.py | solvent/bring.py | from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
... | from solvent import config
from solvent import run
from solvent import requirementlabel
import logging
import os
class Bring:
def __init__(self, repositoryBasename, product, hash, destination):
self._repositoryBasename = repositoryBasename
self._product = product
self._hash = hash
... | Bring now uses --myUIDandGIDCheckout if root is not the invoker | Bring now uses --myUIDandGIDCheckout if root is not the invoker
| Python | apache-2.0 | Stratoscale/solvent,Stratoscale/solvent |
1be7ac84b951a1e5803bd46de931235e44e40d9a | 2018/covar/covar-typecheck.py | 2018/covar/covar-typecheck.py | from typing import TypeVar, List
class Mammal:
pass
class Cat(Mammal):
pass
T = TypeVar('T')
def count_mammals(seq : List[Mammal]) -> int:
return len(seq)
lst = [1, 2, 3]
mlst = [Mammal(), Mammal()]
clst = [Cat(), Cat()]
print(count_mammals(clst))
| # Sample of using typing.TypeVar with covariant settings.
# Run with python3.6+
#
# For type-checking with mypy:
#
# > mypy covar-typecheck.py
#
# Eli Bendersky [https://eli.thegreenplace.net]
# This code is in the public domain.
from typing import List, TypeVar, Iterable, Generic
class Mammal:
pass
class Cat(Mam... | Update the sample with covariant markings | Update the sample with covariant markings
| Python | unlicense | eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog |
7405bda939632a5f8cac93413b4e99939ef716c2 | ideas/models.py | ideas/models.py | from __future__ import unicode_literals
from django.db import models
class Idea(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.name | from __future__ import unicode_literals
from django.db import models
class Idea(models.Model):
name = models.CharField(max_length=200, unique=True)
description = models.TextField()
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.name | Add unique parameter to idea name | Add unique parameter to idea name
| Python | mit | neosergio/vote_hackatrix_backend |
7f79645182de6fed4d7f09302cbc31351defe467 | snippet_parser/fr.py | snippet_parser/fr.py | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | Fix params handling in {{s}}. | Fix params handling in {{s}}.
Former-commit-id: 15eae70c91cd08f9028944f8b6a3990d3170aa28 | Python | mit | guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt |
53bb27bd88cb59424e231e7cadbbabcc91cc44e2 | pywikibot/families/commons_family.py | pywikibot/families/commons_family.py | # -*- coding: utf-8 -*-
"""Family module for Wikimedia Commons."""
#
# (C) Pywikibot team, 2005-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.Wik... | # -*- coding: utf-8 -*-
"""Family module for Wikimedia Commons."""
#
# (C) Pywikibot team, 2005-2018
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
from pywikibot import family
# The Wikimedia Commons family
class Family(family.Wik... | Add Endashcatredirect as a new item in list of category redirect templates | Add Endashcatredirect as a new item in list of category redirect templates
Bug: T183987
Change-Id: I72b6ded1ccab48d5d905f4edd4ce6b9485703563
| Python | mit | magul/pywikibot-core,PersianWikipedia/pywikibot-core,wikimedia/pywikibot-core,wikimedia/pywikibot-core,magul/pywikibot-core |
17fbd2f3fa24da128cb5cabef4a8c94b59b50b0c | sqrl/client/crypt.py | sqrl/client/crypt.py | #!/usr/bin/env python
import ed25519
import hmac
from sqrl.utils import baseconv
class Crypt:
"""
Crypt
- Creating site specific key pair
- Signing SRQL response
- Providing public key
"""
def __init__(self, masterkey):
self.masterkey = masterkey
def _site_key_pair(self, dom... | #!/usr/bin/env python
import ed25519
import hmac
import baseconv
class Crypt:
"""
Crypt
- Creating site specific key pair
- Signing SRQL response
- Providing public key
"""
def __init__(self, masterkey):
self.masterkey = masterkey
def _site_key_pair(self, domain):
se... | Fix up imports after module has moved | Fix up imports after module has moved
| Python | mit | vegarwe/sqrl,vegarwe/sqrl,vegarwe/sqrl,vegarwe/sqrl |
a5ce8febd35795a06288291ae67df1a92b4ba664 | test_knot.py | test_knot.py | # -*- coding: utf-8 -*-
import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container
def create_app():
app = Flask(__name__)
app.config['TESTING'] = True
return app
class TestKnot(unittest.TestCase):
def test_acts_like_container(self):
app = create_app()
di... | # -*- coding: utf-8 -*-
import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container
def create_app():
app = Flask(__name__)
app.config['TESTING'] = True
return app
class TestKnot(unittest.TestCase):
def test_acts_like_container(self):
app = create_app()
di... | Add test for required registration. | Add test for required registration. | Python | mit | jaapverloop/flask-knot |
3e1f5adf1402d6e9ddd4ef6a08f4a667be950e1d | src/ansible/admin.py | src/ansible/admin.py | from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
| from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
admin.site.site_title = 'Ansible Admin'
admin.site.index_title = 'Admin Tool'
| Add ansible app site title | Add ansible app site title
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
98f7c1080765e00954d0c38a98ab1bb3e207c059 | podcoder.py | podcoder.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Ubuntu Podcast
# http://www.ubuntupodcast.org
# See the file "LICENSE" for the full license governing this code.
from podpublish import configuration
from podpublish import encoder
from podpublish import uploader
def main():
config = configuration.Con... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Ubuntu Podcast
# http://www.ubuntupodcast.org
# See the file "LICENSE" for the full license governing this code.
from podpublish import configuration
from podpublish import encoder
def main():
config = configuration.Configuration('podcoder.ini')
i... | Determine what to encode based in skip options. | Determine what to encode based in skip options.
| Python | lgpl-2.1 | rikai/podpublish |
1ea51baec10ebc76bfb2be88270df2050a29fbb5 | http-error-static-pages/5xx-static-html-generator.py | http-error-static-pages/5xx-static-html-generator.py | import os, errno
# Create build folder if it doesn't exist
try:
os.makedirs('build')
except OSError as e:
if e.errno != errno.EEXIST:
raise
template = open('./5xx.template.html', 'r')
templateString = template.read()
template.close()
# We only use 0-11 according to
# https://en.wikipedia.org/wiki/List... | import os, errno
# Create build folder if it doesn't exist
def get_path(relative_path):
cur_dir = os.path.dirname(__file__)
return os.path.join(cur_dir, relative_path)
try:
os.makedirs(get_path('build'))
except OSError as e:
if e.errno != errno.EEXIST:
raise
template = open(get_path('./5xx.template... | Make static http error code generator directory agnostic | Make static http error code generator directory agnostic
| Python | mit | thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-front-end,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-front-end |
c7ef5d2c049beba4bd1b12ec2e62a61446746a8a | unsubscribe/views.py | unsubscribe/views.py | from django import http
from mailgun import utils
import models as unsubscribe_model
def unsubscribe_webhook(request):
verified = utils.verify_webhook(
request.POST.get('token'),
request.POST.get('timestamp'),
request.POST.get('signature')
)
if not verified:
return http.H... | from django import http
from django.views.decorators.csrf import csrf_exempt
from mailgun import utils
import models as unsubscribe_model
@csrf_exempt
def unsubscribe_webhook(request):
verified = utils.verify_webhook(
request.POST.get('token'),
request.POST.get('timestamp'),
request.POST.... | Return http 200 for webhooks | Return http 200 for webhooks
| Python | mit | p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc |
c3479ba8d8486ae9a274367b4601e9e4b6699a1a | prj/urls.py | prj/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^djadmin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^djadmin/', include(admin.site.urls)),
# Root
url( r'^$', 'wishlist.views.index' ),
)
| Add root URL (to serve public wishlist) | Add root URL (to serve public wishlist)
| Python | mit | cgarvey/django-mywishlist,cgarvey/django-mywishlist |
465fd8892c177925d8da3080d08676daad866195 | core/urls.py | core/urls.py | from django.conf.urls import url
from core import views
urlpatterns = [
url(r'^sensors/$', views.SensorList.as_view()),
url(r'^sensors/(?P<pk>[0-9]+)/$', views.SensorDetail.as_view()),
url(r'^stations/$', views.StationList.as_view()),
url(r'^stations/(?P<pk>[0-9]+)/$', views.StationDetail.as_view()),
url(r'^rea... | from django.conf.urls import url
from core import views
urlpatterns = [
url(r'^$', views.api_root),
url(r'^sensors/$', views.SensorList.as_view(), name='sensor-list'),
url(r'^sensors/(?P<pk>[0-9]+)/$', views.SensorDetail.as_view(), name='sensor-detail'),
url(r'^sensors/(?P<pk>[0-9]+)/data/$', views.Se... | Add URLs for previous views. | Add URLs for previous views.
| Python | apache-2.0 | qubs/climate-data-api,qubs/data-centre,qubs/climate-data-api,qubs/data-centre |
8255fd2fdee3a7d6b96859eb7b8d1297431c730b | utils/00-cinspect.py | utils/00-cinspect.py | import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat import cast_unicode
old_find_file = OI.find_file
old_getsource = inspect.getsource
inspect.getsource = getsource
def patch_find_file(obj):
fname = old_find_file(obj)
if fname is None:
... | """ A startup script for IPython to patch it to 'inspect' using cinspect. """
# Place this file in ~/.ipython/<PROFILE_DIR>/startup to patch your IPython to
# use cinspect for the code inspection.
import inspect
from cinspect import getsource, getfile
import IPython.core.oinspect as OI
from IPython.utils.py3compat ... | Add a note for the utility script. | Add a note for the utility script.
| Python | bsd-3-clause | punchagan/cinspect,punchagan/cinspect |
41c7d60556dff4be1c5f39cf694470d3af4869f0 | qual/iso.py | qual/iso.py | from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
return date(year, 1, 8) + timedelta(days=offset)
| from datetime import date, timedelta
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError("Week number %d is invalid for an ISO calendar." % (week, ))
jan_8 = date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
d = date(year, 1, ... | Add checks for a reasonable week number. | Add checks for a reasonable week number.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual |
09dd2e16ef29b6c79ee344a55bea5bd0e59c7a59 | fireplace/cards/gvg/shaman.py | fireplace/cards/gvg/shaman.py | from ..utils import *
##
# Spells
# Ancestor's Call
class GVG_029:
action = [
ForcePlay(CONTROLLER, RANDOM(CONTROLLER_HAND + MINION)),
ForcePlay(OPPONENT, RANDOM(OPPONENT_HAND + MINION)),
]
| from ..utils import *
##
# Minions
# Vitality Totem
class GVG_039:
OWN_TURN_END = [Heal(FRIENDLY_HERO, 4)]
# Siltfin Spiritwalker
class GVG_040:
def OWN_MINION_DESTROY(self, minion):
if minion.race == Race.MURLOC:
return [Draw(CONTROLLER, 1)]
##
# Spells
# Ancestor's Call
class GVG_029:
action = [
For... | Implement Powermace, Crackle, Vitality Totem and Siltfin Spiritwalker | Implement Powermace, Crackle, Vitality Totem and Siltfin Spiritwalker
| Python | agpl-3.0 | oftc-ftw/fireplace,Meerkov/fireplace,Ragowit/fireplace,butozerca/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,amw2104/fireplace,oftc-ftw/fireplace,NightKev/fireplace,butozerca/fireplace,amw2104/fireplace,beheh/fireplace,liujimj/fireplace,jleclanche/fireplace,Ragowit/fireplace,Meerkov/fireplace,liujimj/fi... |
0d37a94593a7749dca4b2553334f1b67c946d3f8 | ambassador/tests/t_lua_scripts.py | ambassador/tests/t_lua_scripts.py | from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP
class LuaTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
def manifests(self) -> str:
return super().manifests() + self.format('''
---
apiVersion: getambassador.io/v1
... | from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP
class LuaTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
self.env = ["LUA_SCRIPTS_ENABLED=Processed"]
def manifests(self) -> str:
return super().manifests() +... | Update LUA test to perform interpolation | Update LUA test to perform interpolation
| Python | apache-2.0 | datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador |
5c7c1155a6bfe0e1dda8def877bcef9d8c528ee3 | vaux/api/__init__.py | vaux/api/__init__.py | import os
from flask import Flask, abort, request
from flask.ext import restful
from vaux.storage import LibreDB
from datetime import datetime
from werkzeug import secure_filename
from cors import crossdomain
app = Flask(__name__)
database = LibreDB('../data', 'localhost', 28015, 'docliber')
from peer import PeerReso... | import os
import ConfigParser
from flask import Flask, abort, request
from flask.ext import restful
from vaux.storage import LibreDB
from datetime import datetime
from werkzeug import secure_filename
from cors import crossdomain
app = Flask(__name__)
config = ConfigParser.SafeConfigParser()
config.read('/etc/vaux.ini... | Read in the database and data options from a config file | Read in the database and data options from a config file
I hope this works.
| Python | mit | VauxIo/core |
0948eced6cd551df7f136614b136378e9864b4eb | forms.py | forms.py | from flask import flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, Length
def flash_errors(form):
""" Universal interface to handle form error.
Handles form error with the help of flash message
"""
for field, error... | from flask import flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
def flash_errors(form):
""" Universal interface to handle form error.
Handles form error with the help of flash message
"""
for fie... | Add input rule for adding employee | Add input rule for adding employee
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee |
848384b0283538556a231a32e4128d52ba9e1407 | direlog.py | direlog.py | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
import fileinput
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:... | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
import fileinput
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:... | Fix args.file and remove stat from argparse | Fix args.file and remove stat from argparse
| Python | mit | abcdw/direlog,abcdw/direlog |
ef89d3608b9ab54aef105528f2c15fa9cc437bcd | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from os.path import abspath, dirname
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
... | #!/usr/bin/env python
import sys
from os.path import abspath, dirname
from django.conf import settings
import django
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.ses... | Fix tests for Django 1.7 | Fix tests for Django 1.7
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log |
da39bc268e3fe94af348690262fc116e3e0b2c9c | attachments/admin.py | attachments/admin.py | from attachments.models import Attachment
from django.contrib.contenttypes import generic
class AttachmentInlines(generic.GenericStackedInline):
model = Attachment
extra = 1 | from attachments.models import Attachment
from django.contrib.contenttypes import admin
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1 | Fix deprecated modules for content types | Fix deprecated modules for content types
| Python | bsd-3-clause | leotrubach/django-attachments,leotrubach/django-attachments |
969334fec0822a30d1e5f10a458f79556053836a | fabfile.py | fabfile.py | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder... | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.virtualenv = 'source /usr/local/bin/virtualenvwrapper.sh'
env.project_root = '/opt/sana.protocol_builder'
def test():
local('python sana_builder... | Update deploy script to support Travis. | Update deploy script to support Travis.
| Python | bsd-3-clause | SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder |
8e8370a76c67d7905c73bcb808f89e3cd4b994a3 | runtests.py | runtests.py | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
... | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
... | Add PERMISSIONS setting to test settings | Add PERMISSIONS setting to test settings
| Python | mit | wylee/django-perms,PSU-OIT-ARC/django-perms |
926731b05f22566e98a02737d673cca3fc0b28ec | docs/conf.py | docs/conf.py | # -*- coding: utf-8 -*-
### General settings
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Firebase Admin SDK for PHP'
author = u'Jérôme Gamez'
copyright = u'Jérôme Gamez'
version = u'4.x'
html_title = u'Firebase Admin SDK for PHP Documentation'
html_short_tit... | # -*- coding: utf-8 -*-
### General settings
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Firebase Admin SDK for PHP'
author = u'Jérôme Gamez'
copyright = u'Jérôme Gamez'
version = u'4.x'
html_title = u'Firebase Admin SDK for PHP Documentation'
html_short_tit... | Fix "Edit on GitHub" links | Fix "Edit on GitHub" links
Using "master" seems to mess it up, see
https://github.com/readthedocs/readthedocs.org/issues/5518
| Python | mit | kreait/firebase-php |
7aaa385da78bef57c8b6339f6db04044ace08807 | api/taxonomies/serializers.py | api/taxonomies/serializers.py | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, JSONAPIListField
class TaxonomyField(ser.Field):
def to_representation(self, obj):
if obj is not None:
return {'id': obj._id,
'text': obj.text}
return None
... | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, JSONAPIListField
class TaxonomyField(ser.Field):
def to_representation(self, obj):
if obj is not None:
return {'id': obj._id,
'text': obj.text}
return None
... | Add child_count taken from new Subject property | Add child_count taken from new Subject property
| Python | apache-2.0 | adlius/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,rdhyee/osf.io,sloria/osf.io,brianjgeiger/osf.io,sloria/osf.io,binoculars/osf.io,mattclark/osf.io,saradbowman/osf.io,aaxelb/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,laurenrevere/osf.io,samchrisinger/osf.io,binoculars/osf.io,aaxelb/osf.io,rdhyee/osf.io,al... |
6c349621dd3331bf92f803d2d66c96868f8e94c6 | src/geelweb/django/editos/runtests.py | src/geelweb/django/editos/runtests.py | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, int... | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
import django
from django.test.utils import get_runner
from django.conf import settings
def runtests():
if django.VERSION[0] == 1 and django.VERSION[1] < 7:
from... | Upgrade to test using django 1.7 and 1.8 | Upgrade to test using django 1.7 and 1.8
| Python | mit | geelweb/django-editos,geelweb/django-editos |
de441445dbdade4d937783626f1beeb9f439ee11 | helpers.py | helpers.py | import feedparser
import datetime
from .models import RssEntry
class RssSyncHelper(object):
def __init__(self, feed):
self.feed = feed
def save_entry(self, result):
pub_date = result.updated_parsed
published = datetime.date(pub_date[0], pub_date[1], pub_date[2])
return RssEn... | import feedparser
import datetime
from .models import RssEntry
def add_custom_acceptable_elements(elements):
"""
Add custom acceptable elements so iframes and other potential video
elements will get synched.
"""
elements += list(feedparser._HTMLSanitizer.acceptable_elements)
feedparser._HTMLS... | Allow iframes to be synched | Allow iframes to be synched
| Python | bsd-3-clause | ebrelsford/django-rsssync |
fe5eb7db52725f8d136cbeba4341f5c3a33cf199 | tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py | tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py | # Copyright 2019 The TensorFlow Authors. 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 applica... | # Copyright 2019 The TensorFlow Authors. 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 applica... | Include AllValuesQuantizer in external APIs | Include AllValuesQuantizer in external APIs
PiperOrigin-RevId: 320104499
| Python | apache-2.0 | tensorflow/model-optimization,tensorflow/model-optimization |
589e2df8c9af8ce8102904c9cfebbf87ee2df744 | ckanext/orgdashboards/tests/helpers.py | ckanext/orgdashboards/tests/helpers.py | from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.... | ''' Helper methods for tests '''
import string
import random
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_da... | Add function for generating random id | Add function for generating random id
| Python | agpl-3.0 | ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards,ViderumGlobal/ckanext-orgdashboards |
b8abb57f7a0e822ba32be2d379bb967f4abfbc21 | setup.py | setup.py | from distutils.core import setup
setup(
name='Zuice',
version='0.2-dev',
description='A dependency injection framework for Python',
author='Michael Williamson',
author_email='mike@zwobble.org',
url='http://gitorious.org/zuice',
packages=['zuice'],
)
| from distutils.core import setup
setup(
name='Zuice',
version='0.2-dev',
description='A dependency injection framework for Python',
author='Michael Williamson',
author_email='mike@zwobble.org',
url='https://github.com/mwilliamson/zuice',
packages=['zuice'],
)
| Update package URL to use GitHub | Update package URL to use GitHub
| Python | bsd-2-clause | mwilliamson/zuice |
18bd0bcc0d892aef4ea9babfc6ec2af6e40cea62 | manager/urls.py | manager/urls.py | from django.conf.urls import url
from manager import views
urlpatterns = [
url(r'^$', views.package_list, name='package_list'),
url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'),
url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build... | from django.conf.urls import url
from manager import views
urlpatterns = [
url(r'^$', views.package_list, name='package_list'),
url(r'^packages/$', views.package_list, name='package_list'),
url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'),
url(r'^packag... | Add alternative package list url | Add alternative package list url
| Python | mit | colajam93/aurpackager,colajam93/aurpackager,colajam93/aurpackager,colajam93/aurpackager |
646b0f8babf346f3ec21ae688453deee24fb410f | tests/core/tests/base_formats_tests.py | tests/core/tests/base_formats_tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.test import TestCase
from django.utils.text import force_text
from import_export.formats import base_formats
class XLSTest(TestCase):
def test_binary_format(self):
self.assertTrue(base_formats.XLS().is_binary())
cl... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.test import TestCase
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from import_export.formats import base_formats
class XLSTest(TestCa... | Fix importing force_text tests for 1.4 compatibility | Fix importing force_text tests for 1.4 compatibility
use 1.4 compat code
| Python | bsd-2-clause | copperleaftech/django-import-export,PetrDlouhy/django-import-export,PetrDlouhy/django-import-export,rhunwicks/django-import-export,copperleaftech/django-import-export,Apkawa/django-import-export,jnns/django-import-export,PetrDlouhy/django-import-export,daniell/django-import-export,django-import-export/django-import-exp... |
a3d655bd311161679bafbcad66f678d412e158f0 | colour/examples/volume/examples_rgb.py | colour/examples/volume/examples_rgb.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations')
message_box('Computing "ProPhoto RGB" RGB coloursp... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases RGB colourspace volume computations.
"""
from __future__ import division, unicode_literals
import colour
from colour.utilities.verbose import message_box
message_box('RGB Colourspace Volume Computations')
message_box('Computing "ProPhoto RGB" RGB coloursp... | Add "Pointer's Gamut" coverage computation example. | Add "Pointer's Gamut" coverage computation example.
| Python | bsd-3-clause | colour-science/colour |
160f29d42086a10bc38d255d8e03a30b1eb01deb | medical_prescription_sale/__openerp__.py | medical_prescription_sale/__openerp__.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Prescription Sales',
'summary': 'Create Sale Orders from Prescriptions',
'version': '9.0.0.1.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': ... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Prescription Sales',
'summary': 'Create Sale Orders from Prescriptions',
'version': '9.0.0.1.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': ... | Add dependency * Add dependency on stock to manifest file. This is needed by some of the demo data in the module, which was not installing due to its absence. | [FIX] medical_prescription_sale: Add dependency
* Add dependency on stock to manifest file. This is needed by some of the demo
data in the module, which was not installing due to its absence.
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical |
81b77db1a455a976a5c516decb5fdd141f10bc31 | Lib/test/test_fork1.py | Lib/test/test_fork1.py | """This test checks for correct fork() behavior.
"""
import os
import time
import unittest
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children
try:
os.fork
except AttributeError:
raise unittest.SkipTest, "os.fork not defined -- skipping test_fork1"
class ForkTest(For... | """This test checks for correct fork() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, import_module
import_module('os.fork')
class ForkTest(ForkWait):
def wait_impl(self, cpid):
for i in range(10):
# waitpid(... | Convert import try/except to use test_support.import_module(). | Convert import try/except to use test_support.import_module().
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
9ea9d111c8b6a20015f9ad6149f690c9e8c0774d | tools/tiny-test-fw/Utility/__init__.py | tools/tiny-test-fw/Utility/__init__.py | from __future__ import print_function
import sys
_COLOR_CODES = {
"white": '\033[0m',
"red": '\033[31m',
"green": '\033[32m',
"orange": '\033[33m',
"blue": '\033[34m',
"purple": '\033[35m',
"W": '\033[0m',
"R": '\033[31m',
"G": '\033[32m',
"O": '\033[33m',
"B": '\033[34m'... | from __future__ import print_function
import sys
_COLOR_CODES = {
"white": u'\033[0m',
"red": u'\033[31m',
"green": u'\033[32m',
"orange": u'\033[33m',
"blue": u'\033[34m',
"purple": u'\033[35m',
"W": u'\033[0m',
"R": u'\033[31m',
"G": u'\033[32m',
"O": u'\033[33m',
"B": u... | Make Utility.console_log accept Unicode and byte strings as well | tools: Make Utility.console_log accept Unicode and byte strings as well
| Python | apache-2.0 | mashaoze/esp-idf,espressif/esp-idf,armada-ai/esp-idf,www220/esp-idf,www220/esp-idf,mashaoze/esp-idf,www220/esp-idf,www220/esp-idf,mashaoze/esp-idf,espressif/esp-idf,www220/esp-idf,espressif/esp-idf,espressif/esp-idf,armada-ai/esp-idf,mashaoze/esp-idf,armada-ai/esp-idf,armada-ai/esp-idf,mashaoze/esp-idf |
7baaac652f74ea44817cd48eb1a4b3aa36f94e23 | armstrong/hatband/sites.py | armstrong/hatband/sites.py | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class AdminSite(DjangoAdminSite):
def get_urls(self):
from django.conf.urls.defaults import patterns, url
return patterns('',
# Custom hatband Views here
... | from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjango... | Revert "Simplify this code and make sure AdminSite doesn't act like a singleton" | Revert "Simplify this code and make sure AdminSite doesn't act like a singleton"
Unfortunately, it's not that simple. Without the runtime merging from
inside hatband.AdminSite, this doesn't seem to pick up everything else.
This reverts commit 122b4e6982fe7a74ee668c1b146c32a61c72ec7b.
| Python | apache-2.0 | texastribune/armstrong.hatband,armstrong/armstrong.hatband,armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband |
812d456599e1540e329a4ddc05a7541b5bfdc149 | labonneboite/conf/__init__.py | labonneboite/conf/__init__.py | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` f... | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` f... | Fix FileNotFoundError on missing local_settings.py | Fix FileNotFoundError on missing local_settings.py
This has been broken for a long time... When running LBB without a
local_settings.py and without an LBB_ENV environment variable, importing
local_settings.py was resulting in a FileNotFoundError.
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite |
1f4ff058d14a32e7e7b9a28daee54a2e8ea1eb02 | media.py | media.py | # media.py
class Movie(object):
def __init__(self,
title,
storyline,
poster_image_url,
trailer_youtube_url,
lead_actors,
release_date,
mpaa_rating,
language,
run... | # media.py
class Movie(object):
""" Movie class for creating a movie """
def __init__(self,
title,
storyline,
poster_image_url,
trailer_youtube_url,
lead_actors,
release_date,
mpaa_rating,
... | Add docstring for class Movie | Add docstring for class Movie
| Python | mit | vishallama/udacity-fullstack-movie-trailer,vishallama/udacity-fullstack-movie-trailer |
4dcb0e56627d3b801b5377d77fca721c43090ce2 | bom_data_parser/axf_parser.py | bom_data_parser/axf_parser.py | import csv
def read_axf(axf_string):
blocks = {}
state = 'new_block'
for line in axf_string.split('\n'):
if line == '[$]' or line == '':
pass
elif line.startswith('['):
block_key = line.replace('[',"").replace(']',"")
print block_key
else:
... | import csv
def read_axf(axf_string):
blocks = {}
state = 'new_block'
for line in axf_string.split('\n'):
if line == '[$]' or line == '':
pass
elif line.startswith('['):
block_key = line.replace('[',"").replace(']',"")
else:
if block_key not in ... | Fix some print statments for Python3 compatibility. | Fix some print statments for Python3 compatibility.
| Python | bsd-3-clause | amacd31/bom_data_parser,amacd31/bom_data_parser |
828d03d7a49d65e8584d4bc373ae4d429b291104 | tests/test_tensorflow_addons.py | tests/test_tensorflow_addons.py | import unittest
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
... | import unittest
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(i... | Add a test exercising TFA custom op. | Add a test exercising TFA custom op.
To prevent future regression.
BUG=145555176
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python |
c9ca274a1a5e9596de553d2ae16950a845359321 | examples/plotting/file/geojson_points.py | examples/plotting/file/geojson_points.py | from bokeh.io import output_file, show
from bokeh.models import GeoJSONDataSource
from bokeh.plotting import figure
from bokeh.sampledata.sample_geojson import geojson
output_file("geojson_points.html", title="GeoJSON Points")
p = figure()
p.circle(line_color=None, fill_alpha=0.8, source=GeoJSONDataSource(geojson=geo... | from bokeh.io import output_file, show
from bokeh.models import GeoJSONDataSource, HoverTool
from bokeh.plotting import figure
from bokeh.sampledata.sample_geojson import geojson
output_file("geojson_points.html", title="GeoJSON Points")
p = figure()
p.circle(line_color=None, fill_alpha=0.8, size=20, source=GeoJSONDa... | Add HoverTool to show off properties availability | Add HoverTool to show off properties availability
| Python | bsd-3-clause | draperjames/bokeh,bokeh/bokeh,timsnyder/bokeh,dennisobrien/bokeh,maxalbert/bokeh,phobson/bokeh,jakirkham/bokeh,stonebig/bokeh,jakirkham/bokeh,bokeh/bokeh,DuCorey/bokeh,justacec/bokeh,dennisobrien/bokeh,clairetang6/bokeh,azjps/bokeh,timsnyder/bokeh,aiguofer/bokeh,timsnyder/bokeh,ericmjl/bokeh,DuCorey/bokeh,rs2/bokeh,bok... |
a0fc801130fa9068c5acc0a48d389f469cdb4bb2 | tasks.py | tasks.py | """
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser
from invoke import task, run
DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')
@task
def docs(show=True):
"""Build the docs and show them in default web browser."""
run('sphinx-build docs docs/_build')
... | """
Automation tasks, aided by the Invoke package.
"""
import os
import webbrowser
from invoke import task, run
DOCS_DIR = 'docs'
DOCS_OUTPUT_DIR = os.path.join(DOCS_DIR, '_build')
@task
def docs(output='html', rebuild=False, show=True):
"""Build the docs and show them in default web browser."""
build_cmd ... | Add more options to the `docs` task | Add more options to the `docs` task
| Python | bsd-3-clause | Xion/callee |
704439e7ae99d215948c94a5dfa61ee1f3f57971 | fireplace/cards/tgt/neutral_legendary.py | fireplace/cards/tgt/neutral_legendary.py | from ..utils import *
##
# Minions
# Confessor Paletress
class AT_018:
inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY))
# Skycap'n Kragg
class AT_070:
cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE))
| from ..utils import *
##
# Minions
# Confessor Paletress
class AT_018:
inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY))
# Skycap'n Kragg
class AT_070:
cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE))
# Gormok the Impaler
class AT_122:
play = Hit(TARGET, 4)
# ... | Implement more TGT Neutral Legendaries | Implement more TGT Neutral Legendaries
| Python | agpl-3.0 | Ragowit/fireplace,liujimj/fireplace,oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,Ragowit/fireplace,Meerkov/fireplace,Meerkov/fireplace |
d86a4b75b1d8b4d18aadbb2bc98387b5ce78f939 | tests/web/splinter/test_view_album.py | tests/web/splinter/test_view_album.py | from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestUploadImage(TestCase):
@with_settings(bucket='humptydump')
... | from __future__ import unicode_literals
from tests import with_settings
from tests.web.splinter import TestCase
from catsnap import Client
from catsnap.table.image import Image
from catsnap.table.album import Album
from nose.tools import eq_
class TestViewAlbum(TestCase):
@with_settings(bucket='humptydump')
d... | Fix a test class name | Fix a test class name
| Python | mit | ErinCall/catsnap,ErinCall/catsnap,ErinCall/catsnap |
eac78bcb95e2c34a5c2de75db785dd6532306819 | ibei/main.py | ibei/main.py | # -*- coding: utf-8 -*-
import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog
def uibei(order, energy_lo, temp, chem_potential):
"""
Upper incomplete Bose-Einstein integral.
"""
kT = temp * constants.k_B
reduced_energy_lo = energy_lo / kT
... | # -*- coding: utf-8 -*-
import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog
def uibei(order, energy_lo, temp, chem_potential):
"""
Upper incomplete Bose-Einstein integral.
"""
kT = temp * constants.k_B
reduced_energy_lo = energy_lo / kT
... | Add draft of DeVos solar cell power function | Add draft of DeVos solar cell power function
| Python | mit | jrsmith3/tec,jrsmith3/ibei,jrsmith3/tec |
1650c9d9620ba9b9262598d3a47208c6c8180768 | app/views.py | app/views.py | from flask import render_template, jsonify
from app import app
from models import Show, Episode
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route("/api/new-episodes/")
def new_episodes():
data = {
"items": []
}
for episode in Episode.query.filter_b... | from flask import render_template, jsonify
from app import app
from models import Show, Episode
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route("/api/new-episodes/")
def new_episodes():
# Return all episodes with showcase set to True.
data = {
"items... | Make shows and episodes only appear if published is true. | Make shows and episodes only appear if published is true.
| Python | mit | frequencyasia/website,frequencyasia/website |
f32685ef4ad847bd237845da6b5b8c44dac0ea9b | tests/skipif_markers.py | tests/skipif_markers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
travis = os.environ[u'TRAVIS']
except KeyError:
travis = False
try:
no_network = os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | Fix travis, make sure skipif condition resolves to a bool | Fix travis, make sure skipif condition resolves to a bool
| Python | bsd-3-clause | audreyr/cookiecutter,dajose/cookiecutter,kkujawinski/cookiecutter,hackebrot/cookiecutter,venumech/cookiecutter,vintasoftware/cookiecutter,pjbull/cookiecutter,lucius-feng/cookiecutter,ramiroluz/cookiecutter,venumech/cookiecutter,0k/cookiecutter,christabor/cookiecutter,hackebrot/cookiecutter,Vauxoo/cookiecutter,Springerl... |
114a6eb827c0e3dd4557aee8f76fde1bbd111bb9 | archalice.py | archalice.py | #!/usr/bin/env python
import os
import re
import time
import sys
from threading import Thread
class testit(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
self.responsetime = -1
def run(self):
pingaling = os.popen("ping -q -c2 "+self.ip,"r")
... | #!/usr/bin/env python
import os
import re
import time
import sys
from threading import Thread
class testit(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
self.responsetime = -1
def run(self):
pingaling = os.popen("ping -q -c2 "+sel... | Update indentation to 4 spaces | Update indentation to 4 spaces
| Python | mit | imrehg/archalice |
b63bda37aa2e9b5251cf6c54d59785d2856659ca | tests/python/unittest/test_random.py | tests/python/unittest/test_random.py | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
shape = (100, 100)
mx.random.seed(128)
ret1 = mx.random.normal(mu, sigma, shape)
u... | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
for i in range(5):
shape = (100 + i, 100 + i)
mx.random.seed(128)
ret1... | Update random number generator test | Update random number generator test
| Python | apache-2.0 | sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet |
221413b5715286bb7b61e18f8e678f2ca097a5e1 | rover.py | rover.py | class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
| class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
def set_position(self, x, y, direction):
self.x = ... | Add set_position method to Rover | Add set_position method to Rover
| Python | mit | authentik8/rover |
64038fad35e7a1b9756921a79b6b13d59925e682 | tests/test_endpoints.py | tests/test_endpoints.py | import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
... | import unittest
from soccermetrics.rest import SoccermetricsRestClient
class ClientEndpointTest(unittest.TestCase):
"""
Test endpoints of API resources in client.
"""
def setUp(self):
self.client = SoccermetricsRestClient(account="APP_ID",api_key="APP_KEY")
def test_service_root(self):
... | Expand test on URL endpoints in API client | Expand test on URL endpoints in API client
| Python | mit | soccermetrics/soccermetrics-client-py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.