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 |
|---|---|---|---|---|---|---|---|---|---|
c9003940c583a19861c1dff20498aa4c6aae1efb | scikits/crab/tests/test_base.py | scikits/crab/tests/test_base.py | #-*- coding:utf-8 -*-
"""
Base Recommender Models.
"""
# Authors: Marcel Caraciolo <marcel@muricoca.com>
# Bruno Melo <bruno@muricoca.com>
# License: BSD Style.
import unittest
import sys
sys.path.append('/Users/marcelcaraciolo/Desktop/Orygens/crab/crab/scikits/craba')
from base import BaseRecommender
#... | #-*- coding:utf-8 -*-
"""
Base Recommender Models.
"""
# Authors: Marcel Caraciolo <marcel@muricoca.com>
# Bruno Melo <bruno@muricoca.com>
# License: BSD Style.
import unittest
from base import BaseRecommender
#test classes
class MyRecommender(BaseRecommender):
def __init__(self,model):
Base... | Fix the test removing paths. | Fix the test removing paths.
| Python | bsd-3-clause | Lawrence-Liu/crab,muricoca/crab,hi2srihari/crab,echogreens/crab,muricoca/crab,augustoppimenta/crab,imouren/crab,rcarmo/crab,Flowerowl/Crab,wnyc/crab,wnyc/crab |
84dd763d5d2aec1c4248e42106ef4f68439bc4cd | server/api/serializers/rides.py | server/api/serializers/rides.py | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerializer(serializers.ModelSerializer):
... | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from .riders import RiderSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerial... | Send through serialised users with each ride api request | Send through serialised users with each ride api request
| Python | mit | mwillmott/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers |
12bbc7e10ae52328feb766e2bed5f5f20fa0d354 | pyramid_es/__init__.py | pyramid_es/__init__.py | from pyramid.settings import asbool
from .client import ElasticClient
def client_from_config(settings, prefix='elastic.'):
"""
Instantiate and configure an Elasticsearch from settings.
In typical Pyramid usage, you shouldn't use this directly: instead, just
include ``pyramid_es`` and use the :py:fun... | from pyramid.settings import asbool
from .client import ElasticClient
def client_from_config(settings, prefix='elastic.'):
"""
Instantiate and configure an Elasticsearch from settings.
In typical Pyramid usage, you shouldn't use this directly: instead, just
include ``pyramid_es`` and use the :py:fun... | Add a settings key to ensure index at start | Add a settings key to ensure index at start
| Python | mit | storborg/pyramid_es |
bfecf498c30c08d8ede18fd587e192f0961c334c | invoke/run.py | invoke/run.py | from subprocess import PIPE
from .monkey import Popen
from .exceptions import Failure
class Result(object):
def __init__(self, stdout=None, stderr=None, exited=None):
self.exited = self.return_code = exited
self.stdout = stdout
self.stderr = stderr
def __nonzero__(self):
# Ho... | from subprocess import PIPE
from .monkey import Popen
from .exceptions import Failure
class Result(object):
def __init__(self, stdout=None, stderr=None, exited=None):
self.exited = self.return_code = exited
self.stdout = stdout
self.stderr = stderr
def __nonzero__(self):
# Ho... | Add semi-useful `__str__` for Result | Add semi-useful `__str__` for Result
| Python | bsd-2-clause | pyinvoke/invoke,mkusz/invoke,singingwolfboy/invoke,tyewang/invoke,mattrobenolt/invoke,kejbaly2/invoke,sophacles/invoke,pfmoore/invoke,pyinvoke/invoke,mkusz/invoke,pfmoore/invoke,kejbaly2/invoke,alex/invoke,frol/invoke,mattrobenolt/invoke,frol/invoke |
87d099f8094d5fb2c78729adfc6df9c68f68b450 | pythonforandroid/recipes/regex/__init__.py | pythonforandroid/recipes/regex/__init__.py | from pythonforandroid.recipe import CompiledComponentsPythonRecipe
class RegexRecipe(CompiledComponentsPythonRecipe):
name = 'regex'
version = '2017.07.28'
url = 'https://pypi.python.org/packages/d1/23/5fa829706ee1d4452552eb32e0bfc1039553e01f50a8754c6f7152e85c1b/regex-{version}.tar.gz'
depends = ['se... | from pythonforandroid.recipe import CompiledComponentsPythonRecipe
class RegexRecipe(CompiledComponentsPythonRecipe):
name = 'regex'
version = '2017.07.28'
url = 'https://pypi.python.org/packages/d1/23/5fa829706ee1d4452552eb32e0bfc1039553e01f50a8754c6f7152e85c1b/regex-{version}.tar.gz'
depends = ['se... | Fix compilation for regex recipe | [recipes] Fix compilation for regex recipe
The error was: build/other_builds/hostpython3/desktop/hostpython3/Include/Python.h:39:19: fatal error: crypt.h: No such file or directory
| Python | mit | rnixx/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kivy/python-for-android,kivy/python-for-android,kivy/python-for-android,germn/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,rnixx/python-for-android,germn/python-for-android,germn/python-for-android,rnixx/python-for-... |
5f5be04adc9e17aa497022ed3b19371075c63d85 | relay_api/api/backend.py | relay_api/api/backend.py | import json
from relay_api.core.relay import relay
from relay_api.conf.config import relays
def init_relays():
for r in relays:
relays[r]["object"] = relay(relays[r]["gpio"])
relays[r]["state"] = relays[r]["object"].get_state()
def get_all_relays():
relays_dict = __get_relay_dict()
retur... | import json
import copy
from relay_api.core.relay import relay
from relay_api.conf.config import relays
def init_relays():
for r in relays:
relays[r]["object"] = relay(relays[r]["gpio"])
relays[r]["state"] = relays[r]["object"].get_state()
def get_all_relays():
relays_dict = __get_relay_dict... | Use deppcopy to copy dicts | Use deppcopy to copy dicts
| Python | mit | pahumadad/raspi-relay-api |
0d4e619a11a084f83ab42d45e528f7b38777fcae | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to... | Remove unnecessary defaults and simplify regexp | Remove unnecessary defaults and simplify regexp | Python | mit | dylanratcliffe/SublimeLinter-puppet,travisgroth/SublimeLinter-puppet,stopdropandrew/SublimeLinter-puppet |
b6b506e8250078664bdefdcf7d9d380e950e3730 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | Handle case where rule shows before severity | Handle case where rule shows before severity
Thank you @suprMax !
| Python | mit | jackbrewer/SublimeLinter-contrib-stylint |
f7172424977d0166ec4dd7946a360a5a426f4a72 | bin/migrate-tips.py | bin/migrate-tips.py | from gratipay.wireup import db, env
from gratipay.models.team import AlreadyMigrated
db = db(env())
teams = db.all("""
SELECT distinct ON (t.slug) t.*::teams
FROM teams t
JOIN tips ON t.owner = tips.tippee -- Only fetch teams whose owner have tips.
WHERE t.is_approved IS TRUE -- Onl... | from gratipay.wireup import db, env
from gratipay.models.team import AlreadyMigrated
db = db(env())
teams = db.all("""
SELECT distinct ON (t.slug) t.*::teams
FROM teams t
JOIN tips ON t.owner = tips.tippee -- Only fetch teams whose owners had tips under Gratipay 1.0
WHERE t.is_approved IS TRUE... | Exclude teams if owner has other teams with migrated tips | Exclude teams if owner has other teams with migrated tips
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com |
0ce14be170e09530b225f2f7526ad68ee1758095 | peering/migrations/0027_auto_20190105_1600.py | peering/migrations/0027_auto_20190105_1600.py | # Generated by Django 2.1.4 on 2019-01-05 15:00
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(
"peering",
"0026_autonomoussystem_potential_internet_exchange_peering_sessions",
)
... | # Generated by Django 2.1.4 on 2019-01-05 15:00
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(
"peering",
"0026_autonomoussystem_potential_internet_exchange_peering_sessions",
)
... | Fix issue with migrations introduced lately. | Fix issue with migrations introduced lately.
| Python | apache-2.0 | respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager |
e8b8c257c71b6c02fa691557618261e6832fba94 | faker/providers/ssn/uk_UA/__init__.py | faker/providers/ssn/uk_UA/__init__.py | # coding=utf-8
from __future__ import unicode_literals
from .. import Provider as SsnProvider
# Note: as there no SSN in Ukraine
# we get value added tax identification number (VATIN) here.
# It is also called "Ідентифікаційний номер платника податків" (in ukrainian).
# It contains only digits and length if 12.
cla... | # coding=utf-8
from __future__ import unicode_literals
from datetime import date
from .. import Provider as SsnProvider
from faker.providers.date_time import Provider as DateTimeProvider
class Provider(SsnProvider):
@classmethod
def ssn(cls):
"""
Ukrainian "Реєстраційний номер облікової карт... | Make the Ukrainian SSN provider realer | Make the Ukrainian SSN provider realer
| Python | mit | joke2k/faker,danhuss/faker,trtd/faker,joke2k/faker |
b698f6925b4629d7473fbe42806f54068d98428a | tests/component/test_component_identidock.py | tests/component/test_component_identidock.py | import sys
print(sys.path)
| import pytest
import requests
from time import sleep
COMPONENT_INDEX_URL = "http://identidock:5000"
COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'
def test_get_mainpage():
print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
sleep(1)
page =... | Add component test functions using pytest | Add component test functions using pytest
| Python | mit | anirbanroydas/ci-testing-python,anirbanroydas/ci-testing-python,anirbanroydas/ci-testing-python |
024ea3b2e9e373abdcd78e44a163a2c32345073f | unittests.py | unittests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import const
import uniformdh
import obfsproxy.network.buffer as obfs_buf
class UniformDHTest( unittest.TestCase ):
def setUp( self ):
weAreServer = True
self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)
de... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import const
import uniformdh
import obfsproxy.network.buffer as obfs_buf
class UniformDHTest( unittest.TestCase ):
def setUp( self ):
weAreServer = True
self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)
de... | Extend UniformDH test to also verify the length of the shared master secret. | Extend UniformDH test to also verify the length of the shared master secret.
| Python | bsd-3-clause | isislovecruft/scramblesuit,isislovecruft/scramblesuit |
61450328583cfb8e5ceee94a03502cef54bb11d6 | learning_journal/tests/test_models.py | learning_journal/tests/test_models.py | # -*- coding: utf-8 -*-
from learning_journal.models import Entry, DBSession
def test_create_entry(dbtransaction):
"""Assert entry was entered into database."""
new_entry = Entry(title="Entry1", text="Hey, this works. Awesome.")
assert new_entry.id is None
DBSession.flush
assert new_entry.id is n... | # -*- coding: utf-8 -*-
from learning_journal.models import Entry, DBSession
def test_create_entry(dbtransaction):
"""Assert entry was entered into database."""
new_entry = Entry(title="Entry1", text="Hey, this works. Awesome.")
assert new_entry.id is None
DBSession.add(new_entry)
DBSession.flush... | Modify test file, still doesn't work. Messed around in pshell. | Modify test file, still doesn't work. Messed around in pshell.
| Python | mit | DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal |
e45f394c61620db13bae579a29043dfdd6ae2d0f | SLA_bot/alertfeed.py | SLA_bot/alertfeed.py | import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDeco... | import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDeco... | Remove text coloring in AlertFeed if it seems like scheduled text | Remove text coloring in AlertFeed if it seems like scheduled text
| Python | mit | EsqWiggles/SLA-bot,EsqWiggles/SLA-bot |
8dc69dca8538eb992989da396b65ade4fe2e5088 | polls/models.py | polls/models.py | from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=Fals... | from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=Fals... | Fix was_published_recently reporting polls from the future | Fix was_published_recently reporting polls from the future
| Python | mit | fernandocanizo/django-poll-site,fernandocanizo/django-poll-site,fernandocanizo/django-poll-site |
c898d3f3d142727d0a55303238cda8044d729437 | motobot/core_plugins/commands.py | motobot/core_plugins/commands.py | from motobot import command, Notice, split_response, IRCBot
@command('commands')
def commands_command(bot, database, context, message, args):
userlevel = bot.get_userlevel(context.channel, context.nick)
valid_command = lambda plugin: plugin.type == IRCBot.command_plugin \
and plugin.level <= userleve... | from motobot import command, Notice, split_response, IRCBot
from collections import defaultdict
def filter_plugins(plugins, userlevel):
return map(
lambda plugin: (plugin.arg.trigger, plugin.func), filter(
lambda plugin: plugin.type == IRCBot.command_plugin and
plugi... | Revert "Revert "Cleans up split_response"" | Revert "Revert "Cleans up split_response""
This reverts commit c3c62feb9fbd8b7ff35d70eaaa5fecfb2093dbb0.
| Python | mit | Motoko11/MotoBot |
7e78408dad1aab6bb42fd62601ee52e5f0ab3bd9 | stanczyk/proxy.py | stanczyk/proxy.py | from twisted.internet import endpoints, reactor
from txampext.multiplexing import ProxyingFactory
def connectProxy(namespace, identifier, _reactor=reactor):
"""Start listening on some free local port; connections will be
proxied to the virtual server with the given identifier.
"""
remote = namespace.... | from stanczyk.util import _getRemote
from twisted.internet import endpoints, reactor
from txampext.multiplexing import ProxyingFactory
def connectProxy(namespace, identifier, _reactor=reactor):
"""Start listening on some free local port; connections will be
proxied to the virtual server with the given identif... | Use the new fancy refactored remote logic | Use the new fancy refactored remote logic
| Python | isc | crypto101/stanczyk |
00b798c309d8807a562efb31751e82e5149ac7c8 | molo/core/api/tests/test_importers.py | molo/core/api/tests/test_importers.py | """
Test the importing module.
This module relies heavily on an external service and requires
quite a bit of mocking.
"""
import json
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.api import importers
from molo.core.api.tests import constants
class ArticleImportT... | """
Test the importing module.
This module relies heavily on an external service and requires
quite a bit of mocking.
"""
import json
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.api import importers
from molo.core.api.tests import constants
class ArticleImportT... | Write test for importer initialisation | Write test for importer initialisation
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo |
cb6f11ad05ef07facf651f8fbccae9e86e0a77c8 | processing.py | processing.py | #!/usr/bin/env python
"""
Processing routines for the waveFlapper case.
"""
import foampy
import numpy as np
import matplotlib.pyplot as plt
width_2d = 0.1
width_3d = 3.66
def plot_force():
"""Plots the streamwise force on the paddle over time."""
def plot_moment():
data = foampy.load_forces_moments()
... | #!/usr/bin/env python
"""
Processing routines for the waveFlapper case.
"""
import foampy
import numpy as np
import matplotlib.pyplot as plt
width_2d = 0.1
width_3d = 3.66
m_paddle = 1270.0 # Paddle mass in kg, from OMB manual
h_piston = 3.3147
I_paddle = 1/3*m_paddle*h_piston**2
def plot_force():
"""Plots th... | Add paddle inertia to calculations | Add paddle inertia to calculations
| Python | cc0-1.0 | petebachant/waveFlapper-OpenFOAM,petebachant/waveFlapper-OpenFOAM,petebachant/waveFlapper-OpenFOAM |
90bc04a92bbe6f29d1487fbd87a4fad811f22c93 | setup/setup-test-docs.py | setup/setup-test-docs.py | #!/usr/bin/python
#
# SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS
#
# Usage: python setup-test-docs.py <Solr Endpoint Url>
#
# Solr endpoint URL should be in the form:
# https://example.com/solr/<core-name>/
#
# .txt files in the directory ./txt/ will be committed to user-provided Solr
# core matchi... | #!/usr/bin/python
#
# SCRIPT FOR POPULATING TEST SOLR SERVER CORE WITH TEST DOCUMENTS
#
# Usage: python setup-test-docs.py <Solr Endpoint Url>
#
# Solr endpoint URL should be in the form:
# https://example.com/solr/<core-name>/
#
# .txt files in the directory ./txt/ will be committed to user-provided Solr
# core matchi... | Use test_docs as directory for test documents for solr server | Use test_docs as directory for test documents for solr server
| Python | mit | gios-asu/search-api |
f34de068e71c57b434c48c9c2b90471112bb4a2b | common/djangoapps/util/bad_request_rate_limiter.py | common/djangoapps/util/bad_request_rate_limiter.py | """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import ... | """
A utility class which wraps the RateLimitMixin 3rd party class to do bad request counting
which can be used for rate limiting
"""
from ratelimitbackend.backends import RateLimitMixin
from django.conf import settings
if settings.FEATURES.get('EDRAAK_RATELIMIT_APP', False):
from edraak_ratelimit.backends import ... | Fix object has no db_log_failed_attempt | Fix object has no db_log_failed_attempt
| Python | agpl-3.0 | Edraak/edraak-platform,Edraak/edraak-platform,Edraak/edraak-platform,Edraak/edraak-platform |
35201e71037d544893a59bfda8c4538fcb6fb4b7 | api/tests/test_scrape_item.py | api/tests/test_scrape_item.py | from api.scrapers.item import scrape_item_by_id
from api import app
from flask.json import loads
import unittest
app.config['TESTING'] = True
class ScrapeItem(unittest.TestCase):
def test_scrape_item_by_id(self):
item = scrape_item_by_id('d19447e548d')
self.assertEqual('d19447e548d', item.lode... | from api.scrapers.item import scrape_item_by_id
from api import app, db
from flask.json import loads
import unittest
app.config['TESTING'] = True
db.create_all()
class ScrapeItem(unittest.TestCase):
def test_scrape_item_by_id(self):
item = scrape_item_by_id('d19447e548d')
self.assertEqual('d19... | Create tables in database before running tests | Create tables in database before running tests
| Python | mit | Demotivated/loadstone |
3e7d83d51fa43f8e93ad548b07193f13791f8abe | django_lightweight_queue/middleware/transaction.py | django_lightweight_queue/middleware/transaction.py | from django.db import transaction, connection
class TransactionMiddleware(object):
def process_job(self, job):
if not connection.in_atomic_block:
transaction.set_autocommit(False)
def process_result(self, job, result, duration):
if not connection.in_atomic_block:
transa... | from django.db import transaction, connection
class TransactionMiddleware(object):
def process_job(self, job):
if not connection.in_atomic_block:
transaction.set_autocommit(False)
def process_result(self, job, result, duration):
if not connection.in_atomic_block:
transa... | Add a legacy version for older versions of Django. | Add a legacy version for older versions of Django.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | thread/django-lightweight-queue,lamby/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue |
b6c98dd016aa440f96565ceaee2716cd530beae5 | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True... | Add a url attribute to the SearchIndex for pages. | Add a url attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can create a link to the result without having to hit the database
for every object in the result list.
| Python | bsd-3-clause | remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-... |
7f86ab26fb1c6ba01f81fdc3f5b66a0f079c23ff | tests/test_app.py | tests/test_app.py | import asyncio
from unittest import mock
import aiohttp
import pytest
from bottery.app import App
def test_app_session():
app = App()
assert isinstance(app.session, aiohttp.ClientSession)
def test_app_already_configured_session():
app = App()
app._session = 'session'
assert app.session == 'ses... | import asyncio
import sys
from unittest import mock
import aiohttp
import pytest
from bottery.app import App
@pytest.fixture
def mocked_engine():
mocked_engine_module = mock.MagicMock()
mocked_engine_instance = mocked_engine_module.engine.return_value
mocked_engine_instance.tasks.return_value = [(mock.M... | Increase the code coverage of App.configure_platforms method | Increase the code coverage of App.configure_platforms method
| Python | mit | rougeth/bottery |
2e9c6c883de12b7293b9e932e5268a2d806e714c | chatterbot/logic/time_adapter.py | chatterbot/logic/time_adapter.py | from __future__ import unicode_literals
from datetime import datetime
from .logic_adapter import LogicAdapter
class TimeLogicAdapter(LogicAdapter):
"""
The TimeLogicAdapter returns the current time.
"""
def __init__(self, **kwargs):
super(TimeLogicAdapter, self).__init__(**kwargs)
fro... | from __future__ import unicode_literals
from datetime import datetime
from .logic_adapter import LogicAdapter
class TimeLogicAdapter(LogicAdapter):
"""
The TimeLogicAdapter returns the current time.
"""
def __init__(self, **kwargs):
super(TimeLogicAdapter, self).__init__(**kwargs)
fro... | Remove textblob dependency in time logic adapter | Remove textblob dependency in time logic adapter
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot,Gustavo6046/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal |
025c95a59b079d630c778646d5c82f5e0679b47c | sale_automatic_workflow/models/account_invoice.py | sale_automatic_workflow/models/account_invoice.py | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice... | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"... | Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs) | [FIX] Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
| Python | agpl-3.0 | kittiu/sale-workflow,kittiu/sale-workflow |
7e2440c00ce75dc3ff0eac53e63d629981a9873a | raven/contrib/celery/__init__.py | raven/contrib/celery/__init__.py | """
raven.contrib.celery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from ra... | """
raven.contrib.celery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from celery.task import task
except ImportError:
from celery.decorators import task
from celery.signals import task_failure
from ra... | Fix celery task_failure signal definition | Fix celery task_failure signal definition
| Python | bsd-3-clause | lepture/raven-python,recht/raven-python,lepture/raven-python,beniwohli/apm-agent-python,dbravender/raven-python,patrys/opbeat_python,recht/raven-python,jbarbuto/raven-python,getsentry/raven-python,akalipetis/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,patrys/opbeat_python,ewdurbin/raven-python,nikolas/rav... |
9d68808a363ad00c3fc0b0907d625e5c75bdb8ae | ptt_preproc_sampling.py | ptt_preproc_sampling.py | #!/usr/bin/env python
from pathlib import Path
from random import shuffle
from shutil import copy
# configs
N = 10000
SAMPLED_DIR_PATH = Path('sampled/')
# mkdir if doesn't exist
if not SAMPLED_DIR_PATH.exists():
SAMPLED_DIR_PATH.mkdir()
# sample and copy
paths = [p for p in Path('preprocessed/').iterdir()... | #!/usr/bin/env python
from pathlib import Path
from random import sample
from os import remove
# configs
N = 10000
# remove unsampled
paths = [path for path in Path('preprocessed/').iterdir()]
paths_len = len(paths)
if paths_len <= N:
raise RuntimeError('file count {:,} <= N {:,}'.format(paths_len, N))
for... | Use removing rather than copying | Use removing rather than copying
| Python | mit | moskytw/mining-news |
b5e4af74bfc12eb3ae9ca14ab4cebc49daf05fdc | api/wb/urls.py | api/wb/urls.py | from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| Add node id to url. | Add node id to url.
| Python | apache-2.0 | baylee-d/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,caseyrollins/osf.io,erinspace/osf.io,pattisdr/osf.io,erinspace/osf.io,icereval/osf.io,adlius/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,fe... |
44893be528063d25d0b2305c9d24be4605c49f3c | mcserver/config/core.py | mcserver/config/core.py | """
MCServer Tools config loader
"""
import json
import os.path
class CoreConfig(object):
"""
MCServer Tools configuration
"""
SETTINGS_FILE = 'mcserver.settings'
def __init__(self, path):
"""
Load configuration from the given file path
"""
self.settings_file = os.path.join(path, self.SETTINGS_FILE)
... | """
MCServer Tools config loader
"""
import json
import os.path
from mcserver import MCServerError
class CoreConfig(object):
"""
MCServer Tools configuration
"""
SETTINGS_FILE = 'mcserver.settings'
def __init__(self, path):
"""
Load configuration from the given file path
"""
self.settings_file = os.p... | Check for the existance of the settings file and report if its not there | Check for the existance of the settings file and report if its not there
| Python | mit | cadyyan/mcserver-tools,cadyyan/mcserver-tools |
20224e4fe8b93dee087dd7a455f9709b9795a026 | app/models.py | app/models.py | from app import database
class Talk(database.Model):
id = database.Column(database.Integer, primary_key=True, autoincrement=True)
title = database.Column(database.String(128), nullable=False)
description = database.Column(database.String(512))
speaker_facebook_id = database.Column(database.BIGINT, dat... | from app import database
class Talk(database.Model):
id = database.Column(database.Integer, primary_key=True, autoincrement=True)
title = database.Column(database.String(128), unique=True, nullable=False)
description = database.Column(database.String(512))
speaker_facebook_id = database.Column(databas... | Make title unique Talk property | Make title unique Talk property
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot |
3611e8a1b6477d251ddb2c90211e0cfee370671d | cal_pipe/easy_RFI_flagging.py | cal_pipe/easy_RFI_flagging.py |
import sys
import os
'''
Easier searching for good RFI flagging values
'''
try:
vis = sys.argv[1]
except IndexError:
vis = raw_input("Input vis? : ")
# Just want the number of SPWs
tb.open(os.path.join(vis, "SPECTRAL_WINDOW"))
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(len(nchans))
default('fl... |
import sys
import os
'''
Easier searching for good RFI flagging values
'''
try:
ms_name = sys.argv[1]
except IndexError:
ms_name = raw_input("Input vis? : ")
# Just want the number of SPWs
tb.open(os.path.join(ms_name, "SPECTRAL_WINDOW"))
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(len(nchans))
... | CHange name so it isn't reset | CHange name so it isn't reset
| Python | mit | e-koch/canfar_scripts,e-koch/canfar_scripts |
689dd5cb67516fd091a69e39708b547c66f96750 | nap/dataviews/models.py | nap/dataviews/models.py |
from .fields import Field
from .views import DataView
from django.utils.six import with_metaclass
class MetaView(type):
def __new__(mcs, name, bases, attrs):
meta = attrs.get('Meta', None)
try:
model = meta.model
except AttributeError:
if name != 'ModelDataView'... |
from django.db.models.fields import NOT_PROVIDED
from django.utils.six import with_metaclass
from . import filters
from .fields import Field
from .views import DataView
# Map of ModelField name -> list of filters
FIELD_FILTERS = {
'DateField': [filters.DateFilter],
'TimeField': [filters.TimeFilter],
'Da... | Add Options class Add field filters lists Start proper model field introspection | Add Options class
Add field filters lists
Start proper model field introspection
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap |
10e23fdd5c0427ad1ff5a5284410c755378a0e6d | SoftLayer/CLI/object_storage/list_accounts.py | SoftLayer/CLI/object_storage/list_accounts.py | """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageM... | """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageM... | Fix object storage apiType for S3 and Swift. | Fix object storage apiType for S3 and Swift.
| Python | mit | allmightyspiff/softlayer-python,softlayer/softlayer-python,kyubifire/softlayer-python |
a50a46ee26e5d7d325a228559bc701c86d1b392d | arg-reader.py | arg-reader.py | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
Read arguments from a file
'''
parser = argparse.ArgumentParser(descrip... | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, p... | Add more comments about usage. | Add more comments about usage.
| Python | mit | beepscore/argparse |
da05390fa11a12d0491caff18d38e71a1e134b82 | spicedham/sqlalchemywrapper/models.py | spicedham/sqlalchemywrapper/models.py | from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import UniqueConstraint
Base = declarative_base()
class Store(Base):
__tablename__ = 'store'
id = Column(Integer, primary_key=True, autoincrement=True)
key = Column(String)
tag... | from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import PrimaryKeyConstraint
Base = declarative_base()
class Store(Base):
__tablename__ = 'store'
key = Column(String)
tag = Column(String)
value = Column(String)
__table_ar... | Make tag and key be a composite primary key | Make tag and key be a composite primary key
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
63d1eb69fc614cb3f019e7b37dd4ec10896c644e | chartflo/views.py | chartflo/views.py | # -*- coding: utf-8 -*-
from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack
class ChartsView(TemplateView):
template_name = 'chartflo/charts.html'
graph_type = "pie"
title = ""
def get_data(self):
return {}
def get_context_data(self, **kwargs):
... | # -*- coding: utf-8 -*-
from django.views.generic import TemplateView
from chartflo.factory import ChartDataPack
class ChartsView(TemplateView):
template_name = 'chartflo/charts.html'
chart_type = "pie"
title = ""
def get_data(self):
return {}
def get_context_data(self, **kwargs):
... | Change graph_type for chart_type and remove it from context | Change graph_type for chart_type and remove it from context
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo |
e66468faaf9c4885f13545329baa20fe4914f49c | historia.py | historia.py | from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
accou... | from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
accou... | Use MD5 to encode passwords | Use MD5 to encode passwords
| Python | mit | waoliveros/historia |
68724546ba4f6063559ba14b8625c7e7ecdf9732 | src/read_key.py | src/read_key.py | #!/usr/bin/python
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
| #!/usr/bin/python
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
| Remove newline and carraige return characters from key files so that API calls work | Remove newline and carraige return characters from key files so that API calls work
| Python | mit | nilnullzip/StalkerBot,nilnullzip/StalkerBot |
5456bee257cb36e4d1400da7e27480beadbf21fd | examples/arabic.py | examples/arabic.py | #!/usr/bin/env python
"""
Example using Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file__)
# R... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file... | Change the title of the example | Change the title of the example
| Python | mit | amueller/word_cloud |
e35d55f46ffb9d42736ad4e57ae2a6c29838b054 | board/tests.py | board/tests.py | from django.test import TestCase
# Create your tests here.
| from test_plus.test import TestCase
class BoardTest(TestCase):
def test_get_board_list(self):
board_list_url = self.reverse("board:list")
self.get_check_200(board_list_url)
| Add board list test code. | Add board list test code.
| Python | mit | 9XD/9XD,9XD/9XD,9XD/9XD,9XD/9XD |
3d2b4536803df4a202d8c1c9b5d0e689f1053378 | tests/config.py | tests/config.py | import sys
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import unittest
testing_community = 'fiveheads.ideascale.com'
testing_token = '5b3326f8-50a5-419d-8f02-eef6a42fd61a'
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = c... | import os
import sys
import unittest
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
testing_community = 'fiveheads.ideascale.com'
testing_token = os.environ.get('TOKEN', '')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = cre... | Read token from environment variable | Read token from environment variable
| Python | mit | joausaga/ideascaly |
7845e017b264a38472d0dc94988a0afe6938132f | tests/acceptance/conftest.py | tests/acceptance/conftest.py | # -*- coding: utf-8 -*-
import mock
import pytest
@pytest.fixture
def default_trace_id_generator(dummy_request):
return lambda dummy_request: '17133d482ba4f605'
@pytest.fixture
def settings():
return {
'zipkin.tracing_percent': 100,
'zipkin.trace_id_generator': default_trace_id_generator,
... | # -*- coding: utf-8 -*-
import mock
import pytest
@pytest.fixture
def default_trace_id_generator(dummy_request):
return lambda dummy_request: '17133d482ba4f605'
@pytest.fixture
def settings():
return {
'zipkin.tracing_percent': 100,
'zipkin.trace_id_generator': default_trace_id_generator,
... | Allow any ip in the get_span expected span since it's not deterministic | Allow any ip in the get_span expected span since it's not deterministic
| Python | apache-2.0 | Yelp/pyramid_zipkin |
c96e82caaa3fd560263c54db71772b44e9cd78d7 | examples/upgrade_local_charm_k8s.py | examples/upgrade_local_charm_k8s.py | """
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with ... | """
This example:
1. Connects to the current model
2. Deploy a bundle and waits until it reports itself active
3. Upgrades the charm with a local path
4. Destroys the units and applications
"""
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to mode... | Make the example more informative | Make the example more informative
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju |
1b9b4365a46cdbfbfe88e2f5e271ba387fe4274f | var_log_dieta/constants.py | var_log_dieta/constants.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import logging
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
DATA_DIR = 'data'
DEFAULT_CONVERSIONS = {
'kg': {'g': 1000},
'l': {'ml': 1000},
} # yapf: disable
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import logging
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
DATA_DIR = 'data'
DEFAULT_CONVERSIONS = {
'kg': {'g': 1000},
'l': {'ml': 1000},
'taza': {'ml': 250},
't... | Add taza, tazon and vaso global conversions | Add taza, tazon and vaso global conversions
| Python | bsd-3-clause | pignacio/vld |
18da33bd5524a7e9a043de90fb9b7aa78a26412d | addons/meme.py | addons/meme.py | import discord
import random
from discord.ext import commands
class Meme:
"""
Meme commands.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.has_permissions(kick_members=True)
@commands.command(pass_context=True... | import discord
import random
from discord.ext import commands
class Meme:
"""
Meme commands.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.command(pass_context=True, hidden=True, name="bam")
async def bam_memb... | Allow everyone to bam and warm, hide commands | Allow everyone to bam and warm, hide commands | Python | apache-2.0 | 916253/Kurisu-Reswitched |
cbadf5c564d7f5f701499409e2ae77ff90ba477c | tests/test_tensorflow.py | tests/test_tensorflow.py | import unittest
import numpy as np
import tensorflow as tf
from common import gpu_test
class TestTensorflow(unittest.TestCase):
def test_addition(self):
op = tf.add(2, 3)
sess = tf.Session()
result = sess.run(op)
self.assertEqual(5, result)
@gpu_test
... | import unittest
import numpy as np
import tensorflow as tf
from common import gpu_test
class TestTensorflow(unittest.TestCase):
def test_addition(self):
op = tf.add(2, 3)
sess = tf.Session()
result = sess.run(op)
self.assertEqual(5, result)
def test_conv2d(... | Add conv2d test for tensorflow | Add conv2d test for tensorflow
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python |
dfd4a6f6b23447538b2b22da11666f5218d791db | mots_vides/constants.py | mots_vides/constants.py | """
Constants for mots-vides
"""
import os
DATA_DIRECTORY = os.path.join(
os.path.dirname(
os.path.abspath(__file__)),
'datas/'
)
| """
Constants for mots-vides
"""
import os
DATA_DIRECTORY = os.path.join(
os.path.dirname(
os.path.abspath(__file__)),
'datas/'
)
LANGUAGE_CODES = {
'af': 'afrikaans',
'ar': 'arabic',
'az': 'azerbaijani',
'bg': 'bulgarian',
'be': 'belarusian',
'bn': 'bengali',
'br': 'breton... | Define a complete list of language code, for easy future maintenance | Define a complete list of language code, for easy future maintenance
| Python | bsd-3-clause | Fantomas42/mots-vides,Fantomas42/mots-vides |
8dc6c7567f9bc94dc1b4a96b80d059f1231039bc | st2auth_flat_file_backend/__init__.py | st2auth_flat_file_backend/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Fix code so it also works under Python 3. | Fix code so it also works under Python 3.
| Python | apache-2.0 | StackStorm/st2-auth-backend-flat-file |
4abd7baafcd982993471d5c0137d4b506ea49e8b | src/runcommands/util/enums.py | src/runcommands/util/enums.py | import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
class Terminal:
def __getattr__(self, name):
return ""
TERM = Terminal()
class Color(enum.Enum):
none = ... | import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
# XXX: Mock terminal that returns "" for all attributes
class TerminalValue:
registry = {}
@classmethod
d... | Fix Color enum setup when TERM isn't set | Fix Color enum setup when TERM isn't set
The previous version of this didn't work right because all the values
were the same empty string.
This works around that by creating distinct values that evaluate to "".
Amends 94b55ead63523f7f5677989f1a4999994b205cdf
| Python | mit | wylee/runcommands,wylee/runcommands |
c4ee061f62e34c70cc67286ed0291423353cbcbe | imgur_cli/utils.py | imgur_cli/utils.py | import json
def cli_arg(*args, **kwargs):
"""Decorator for CLI args"""
def _decorator(func):
add_arg(func, *args, **kwargs)
return func
return _decorator
def add_arg(func, *args, **kwargs):
"""Bind CLI arguments a 'cmd_' format function"""
if not hasattr(func, 'arguments'):
... | import json
def cli_arg(*args, **kwargs):
"""Decorator for CLI args"""
def _decorator(func):
add_arg(func, *args, **kwargs)
return func
return _decorator
def add_arg(func, *args, **kwargs):
"""Bind CLI arguments to a 'cmd_' format function"""
if not hasattr(func, 'arguments'):
... | Define function and decorators for subparsers | Define function and decorators for subparsers
| Python | mit | ueg1990/imgur-cli |
5ff58311b6cf2dc8ad03351e818d05fca9e33e1b | hastexo/migrations/0010_add_user_foreign_key.py | hastexo/migrations/0010_add_user_foreign_key.py | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations, models
import django.db.models.deletion
import logging
logger = logging.getLogger(__name__)
class Migration(migrations.Migration):
def backfill_learner(apps, schema_editor):
"""
... | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations, models
import django.db.models.deletion
import logging
logger = logging.getLogger(__name__)
class Migration(migrations.Migration):
def backfill_learner(apps, schema_editor):
"""
... | Apply additional fix to add_user_foreign_key migration | Apply additional fix to add_user_foreign_key migration
The hack in 583fb729b1e201c830579345dca5beca4b131006 modified
0010_add_user_foreign_key in such a way that it ended up *not* setting
a database constraint when it should have.
Enable the database-enforced constraint in the right place.
Co-authored-by: Florian Ha... | Python | agpl-3.0 | hastexo/hastexo-xblock,hastexo/hastexo-xblock,hastexo/hastexo-xblock,hastexo/hastexo-xblock |
7519bebe1d9d87930275858a537dcc0a0a64f007 | tools/strip_filenames.py | tools/strip_filenames.py | #!/bin/python
import os
directory = os.listdir()
illegal_characters = "%?_'*+$!\""
tolowercase=True
for a in range(len(directory)):
newname=""
for c in directory[a]:
if c in illegal_characters:
continue
if c.isalnum() or c == '.':
newname=newname+c.lower()
print("con... | #!/bin/env python3
"""
Use only legal characters from files or current directory
Usage:
strip_filenames.py [<filename>...]
Options:
-l, --lowercase Only lowercase
-h, --help Show this screen and exit.
"""
import sys
import os
from docopt import docopt
# docopt(doc, argv=None, help=True, version=None, op... | Use legal characters for stripping filenames | Use legal characters for stripping filenames
| Python | mit | dgengtek/scripts,dgengtek/scripts |
c0b76d401b305c1bcd2ed5814a89719d4c6a3d83 | heat_cfnclient/tests/test_cli.py | heat_cfnclient/tests/test_cli.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | Disable tests until new repo is stable | Disable tests until new repo is stable
Change-Id: Ic6932c1028c72b5600d03ab59102d1c1cff1b36c
| Python | apache-2.0 | openstack-dev/heat-cfnclient |
79c6c71ab6edd8313fd6c9c6441d69ad04d50721 | update-database/stackdoc/namespaces/microsoftkb.py | update-database/stackdoc/namespaces/microsoftkb.py | import re
import urllib
############### Functions called by stackdoc
def get_version():
return 1
def get_ids(title, body, tags):
ids = []
if "http://support.microsoft.com/":
urls = re.findall(r'<a href="([^"]+)"', body)
for url in urls:
m = re.match("http://support\.microsoft... | import re
import urllib
############### Functions called by stackdoc
def get_version():
return 1
def get_ids(title, body, tags):
ids = []
if "http://support.microsoft.com/":
urls = re.findall(r'<a href="([^"]+)"', body)
for url in urls:
m = re.match("http://support\.microsoft... | Support another form of KB URL. | Support another form of KB URL.
| Python | bsd-3-clause | alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc |
640ad3ed45eef21f2b7a71b4fd73a469ebed4b44 | reobject/models/fields.py | reobject/models/fields.py | import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyT... | import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyT... | Fix tests on Python 3.3 and 3.4 | Fix tests on Python 3.3 and 3.4
| Python | apache-2.0 | onyb/reobject,onyb/reobject |
c32bdff4b0ee570ed58cd869830d89e3251cf82a | pytils/test/__init__.py | pytils/test/__init__.py | # -*- coding: utf-8 -*-
"""
Unit tests for pytils
"""
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"]
import unittest
def get_django_suite():
try:
import django
except ImportError:
return unittest.TestSuite()
import pytils.test.templatetags
return... | # -*- coding: utf-8 -*-
"""
Unit tests for pytils
"""
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"]
import unittest
import sys
def get_django_suite():
try:
import django
except ImportError:
return unittest.TestSuite()
import pytils.test.templatetags... | Exit with non-0 status if there are failed tests or errors. | Py3: Exit with non-0 status if there are failed tests or errors.
| Python | mit | Forever-Young/pytils,j2a/pytils |
7e25472dab7732dc76bfb81d720946c18811962f | src/appengine/driver.py | src/appengine/driver.py | """List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
... | """List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
... | Fix 'put is not a command' error on static commands | Fix 'put is not a command' error on static commands
| Python | mit | tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation |
14dd9f6cab99be6832ab98291337f4d38faae936 | fellowms/forms.py | fellowms/forms.py | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
... | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"user",
"home_lon",
"home_lat",
"inauguration_year",
"fun... | Exclude user field from form | Exclude user field from form
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat |
d028f66964249bab928a29d92ab4cff075352546 | integration/main.py | integration/main.py | from spec import Spec, skip
class Tessera(Spec):
def is_importable(self):
import tessera
assert tessera.app
assert tessera.db
| from contextlib import contextmanager
import os
from shutil import rmtree
from tempfile import mkdtemp
from spec import Spec, skip
@contextmanager
def _tmp():
try:
tempdir = mkdtemp()
yield tempdir
finally:
rmtree(tempdir)
@contextmanager
def _db():
with _tmp() as tempdir:
... | Add temp DB test harness + basic test | Add temp DB test harness + basic test
| Python | apache-2.0 | tessera-metrics/tessera,jmptrader/tessera,aalpern/tessera,Slach/tessera,filippog/tessera,aalpern/tessera,aalpern/tessera,section-io/tessera,urbanairship/tessera,aalpern/tessera,urbanairship/tessera,Slach/tessera,jmptrader/tessera,urbanairship/tessera,Slach/tessera,urbanairship/tessera,urbanairship/tessera,tessera-metri... |
1100830d3b48262dd9b94d96eb50d75c8ff69fe4 | Cogs/Emoji.py | Cogs/Emoji.py | import discord
from discord.ext import commands
from Cogs import GetImage
def setup(bot):
bot.add_cog(Emoji(bot))
class Emoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def emoji(self, ctx, emoji = None):
'''Outputs your CUSTOM emoji... but bigge... | import discord
from discord.ext import commands
from Cogs import GetImage
def setup(bot):
bot.add_cog(Emoji(bot))
class Emoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def emoji(self, ctx, emoji = None):
'''Outputs the passed emoji... but bigger... | Add support for built-in emojis | Add support for built-in emojis | Python | mit | corpnewt/CorpBot.py,corpnewt/CorpBot.py |
6464028097b13b5d03969c20bae56f9f70acbbd1 | saleor/cart/middleware.py | saleor/cart/middleware.py | from __future__ import unicode_literals
from . import SessionCart, CART_SESSION_KEY
class CartMiddleware(object):
'''
Saves the cart instance into the django session.
'''
def process_request(self, request):
try:
cart_data = request.session[CART_SESSION_KEY]
cart = Ses... | from __future__ import unicode_literals
from . import SessionCart, CART_SESSION_KEY
class CartMiddleware(object):
'''
Saves the cart instance into the django session.
'''
def process_request(self, request):
try:
cart_data = request.session[CART_SESSION_KEY]
cart = Ses... | Store cart in session only when it was modified | Store cart in session only when it was modified
| Python | bsd-3-clause | HyperManTT/ECommerceSaleor,taedori81/saleor,car3oon/saleor,UITools/saleor,rodrigozn/CW-Shop,mociepka/saleor,spartonia/saleor,UITools/saleor,arth-co/saleor,UITools/saleor,paweltin/saleor,hongquan/saleor,Drekscott/Motlaesaleor,UITools/saleor,avorio/saleor,josesanch/saleor,tfroehlich82/saleor,maferelo/saleor,spartonia/sal... |
3dfa781ce8e073f40eda3d80794ad1caff5d5920 | samples/migrateAccount.py | samples/migrateAccount.py | #### Migrate person to a new account within the same Org
# Requires admin role
# Useful when migrating to Enterprise Logins.
# Reassigns all items/groups to new owner and
# adds userTo to all groups which userFrom is a member.'''
from agoTools.admin import Admin
myAgol = Admin('<username>') # Replace <userna... | #### Migrate a member to a new account within the same Organization
# Requires admin role
# Useful when migrating to Enterprise Logins
# Reassigns all items/groups to new owner
# Adds userTo to all groups which userFrom is a member
from agoTools.admin import Admin
myAgol = Admin('<username>') # Replace <user... | Enhance comments in Migrate Account sample | Enhance comments in Migrate Account sample
| Python | apache-2.0 | oevans/ago-tools |
a90c2eecf95323a6f968e1313c3d7852e4eb25b2 | speeches/management/commands/populatespeakers.py | speeches/management/commands/populatespeakers.py | from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.PO... | import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, ... | Update speaker population command to set popit_url instead of popit_id | Update speaker population command to set popit_url instead of popit_id
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit |
a5ef9a5d141ba5fd0d1d6c983cd8ac82079a1782 | run_tests.py | run_tests.py | #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-te... | #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-te... | Update run_test.py to fix coverage | tests: Update run_test.py to fix coverage
| Python | agpl-3.0 | Asalle/coala,ManjiriBirajdar/coala,jayvdb/coala,Asnelchristian/coala,RJ722/coala,abhiroyg/coala,FeodorFitsner/coala,meetmangukiya/coala,sils1297/coala,Tanmay28/coala,yashLadha/coala,Asalle/coala,scottbelden/coala,stevemontana1980/coala,sophiavanvalkenburg/coala,Tanmay28/coala,JohnS-01/coala,Nosferatul/coala,yashLadha/c... |
81f2a561ac27d13fb43edae1fb94b237951ff9cc | tests/rietveld/test_braggtree.py | tests/rietveld/test_braggtree.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld.braggtree import BraggTree, BankRegexException
class BraggTreeTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
def tearDown(self):
s... | from __future__ import absolute_import, print_function
import pytest
from addie.main import MainWindow
from addie.rietveld.braggtree import BraggTree, BankRegexException
@pytest.fixture
def braggtree():
return BraggTree(None)
def test_get_bank_id(qtbot, braggtree):
"""Test we can extract a bank id from bank ... | Refactor BraggTree test to use pytest-qt | Refactor BraggTree test to use pytest-qt
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR |
5daa628d59576f00d0c5d49358a800dd728c6fdf | necropsy/models.py | necropsy/models.py | # -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
class Necropsy (models.Model):
clinical_information = models.TextField(null=True, blank=True)
macroscopic = models.TextField(null=True, blank=True)
microscopic = models.TextField(null=True, blank=True)
conclusion = models.TextField(nul... | # -*- coding: utf-8 -*-
from django.db import models
from modeling.exam import Exam
from modeling.report import ReportStatus
class NecropsyStatus(models.Model):
description = models.CharField(max_length=50)
class Necropsy(models.Model):
clinical_information = models.TextField(null=True, blank=True)
main... | Add NecropsyReport in Model Necropsy | Add NecropsyReport in Model Necropsy
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub |
2ba4e0758c04bebcd1dcde78e99605d0b9460abf | foldatlas/monitor.py | foldatlas/monitor.py | import os
# must call "sudo apt-get install sendmail" first...
# if sts != 0:
# print("Sendmail exit status "+str(sts))
def send_error(recipient, error_details):
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % SENDMAIL, "w")
p.write("To: "+recipient+"\n")
p.write("Subject: Fold... | import traceback
import os
import urllib.request # the lib that handles the url stuff
test_url = "http://www.foldatlas.com/transcript/AT2G45180.1"
recipient = "matthew.gs.norris@gmail.com"
search_str = "AT2G45180.1"
def run_test():
try:
data = urllib.request.urlopen(test_url) # it's a file like object and works ... | Monitor now checks and emails | Monitor now checks and emails
| Python | mit | mnori/foldatlas,mnori/foldatlas,mnori/foldatlas,mnori/foldatlas |
6b0774eab70c42fbdd28869b6bcdab9b81183b8e | run_tests.py | run_tests.py | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
from bluesky.testing.noseclasses import KnownFailure
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pv... | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pvdb = {
'VAL': {
'prec': 3... | Remove deleted subpackage. Add better args to pytest | TST: Remove deleted subpackage. Add better args to pytest
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky |
c3a184a188d18f87bad2d7f34a2dfd3a7cca4827 | signac/common/errors.py | signac/common/errors.py | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len... | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
from . import six
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self... | Fix py27 issue in error module. | Fix py27 issue in error module.
Inherit signac internal FileNotFoundError class from IOError
instead of FileNotFoundError in python 2.7.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac |
54e78b61db2660a57762b0f0115d532b308386e4 | opal/tests/test_core_commandline.py | opal/tests/test_core_commandline.py | """
Unittests for opal.core.commandline
"""
from opal.core.test import OpalTestCase
from opal.core import commandline
| """
Unittests for opal.core.commandline
"""
from mock import patch, MagicMock
from opal.core.test import OpalTestCase
from opal.core import commandline
class StartprojectTestCase(OpalTestCase):
def test_startproject(self):
mock_args = MagicMock(name='Mock Args')
mock_args.name = 'projectname'
... | Add simple basic unittests for some of our commandline argparse target functions | Add simple basic unittests for some of our commandline argparse target functions
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal |
c00a55b8337dbc354921c195dfa4becc7ee1346a | ipython/profile_default/startup/00-imports.py | ipython/profile_default/startup/00-imports.py | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
except ImportError:
pass
try:
fr... | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
from rich import pretty
pretty.in... | Use rich for printing in ipython | Use rich for printing in ipython
| Python | mit | jalanb/jab,jalanb/dotjab,jalanb/dotjab,jalanb/jab |
80ca0bebce22f64d0d01377493126ed95d8a64cb | falcom/luhn.py | falcom/luhn.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
def get_check_digit_from_checkable_int (number):
return (9 * ((number // 10) + rotate_digit(number % 10))) % 10
def rotate_digit (digit)... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
def rotate_digit (digit):
if digit > 4:
return (digit * 2) - 9
else:
return digit * 2
def get_check_digit_from_chec... | Reorder methods to make sense | Reorder methods to make sense
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
a6e46fc5429840fd3ff47c03d8b0d9f3b28c7811 | src/sentry/api/endpoints/group_events_latest.py | src/sentry/api/endpoints/group_events_latest.py | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... | Handle no latest event (fixes GH-1727) | Handle no latest event (fixes GH-1727)
| Python | bsd-3-clause | imankulov/sentry,hongliang5623/sentry,fotinakis/sentry,BuildingLink/sentry,gencer/sentry,mitsuhiko/sentry,BuildingLink/sentry,beeftornado/sentry,mvaled/sentry,daevaorn/sentry,wong2/sentry,ifduyue/sentry,jean/sentry,ifduyue/sentry,Kryz/sentry,jean/sentry,kevinlondon/sentry,fotinakis/sentry,pauloschilling/sentry,korealer... |
666fc19e2949a30cbe40bf6020c141e84dfcae1e | app/soc/models/project_survey.py | app/soc/models/project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Set the default prefix for ProjectSurveys to gsoc_program. | Set the default prefix for ProjectSurveys to gsoc_program.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son |
1b9aa9909b284489c9f8a5d38b1c5520d5916dc7 | feature_extraction/measurements/__init__.py | feature_extraction/measurements/__init__.py | from collections import defaultdict
from feature_extraction.util import DefaultAttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
... | from collections import defaultdict
from feature_extraction.util import AttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
"""
... | Switch back to AttributeDict for measurement options | Switch back to AttributeDict for measurement options
| Python | apache-2.0 | widoptimization-willett/feature-extraction |
f0bca27d58fb4bc74b6627275486dbfd159954d6 | tests/test_datafeed_fms_teams.py | tests/test_datafeed_fms_teams.py | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | Update test case for 2014 | Update test case for 2014
| Python | mit | tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,1fish2/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,verycumber... |
c43e120319248a804328893aad34fc774c4928d3 | stdup/kde.py | stdup/kde.py | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# 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 o... | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# 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 o... | Add KDE show & hide logging | Add KDE show & hide logging
| Python | apache-2.0 | waawal/standup-desktop,waawal/standup-desktop |
e4e3f0d7270e93e6123dbf05e1f51993e38d970c | tests/cpydiff/types_exception_subclassinit.py | tests/cpydiff/types_exception_subclassinit.py | """
categories: Types,Exception
description: Exception.__init__ raises TypeError if overridden and called by subclass
cause: Unknown
workaround: Unknown
"""
class A(Exception):
def __init__(self):
Exception.__init__(self)
a = A()
| """
categories: Types,Exception
description: Exception.__init__ method does not exist.
cause: Subclassing native classes is not fully supported in MicroPython.
workaround: Call using ``super()`` instead::
class A(Exception):
def __init__(self):
super().__init__()
"""
class A(Exception):
def __init__(se... | Update subclassing Exception case and give work-around. | tests/cpydiff: Update subclassing Exception case and give work-around.
| Python | mit | adafruit/micropython,pfalcon/micropython,adafruit/circuitpython,blazewicz/micropython,adafruit/circuitpython,blazewicz/micropython,ryannathans/micropython,ryannathans/micropython,henriknelson/micropython,MrSurly/micropython,trezor/micropython,adafruit/micropython,adafruit/micropython,dmazzella/micropython,pramasoul/mic... |
1f7979edaa918a52702bea5de6f2bdd7a8e60796 | encryption.py | encryption.py | import base64
from Crypto.Cipher import AES
from Crypto import Random
def encrypt(raw, key):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(enc, key):
enc = base64.b64decode(enc)
iv = e... | import base64
from Crypto.Cipher import AES
from Crypto import Random
def encrypt(raw, key):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8')
def decrypt(enc, key):
enc = base64.b64decode... | Add decode(utf-8) to return on encrypt | Add decode(utf-8) to return on encrypt | Python | mit | regexpressyourself/passman |
68374c16d66cdeea9dbce620dc29d375e3009070 | bcbio/bam/fasta.py | bcbio/bam/fasta.py | from Bio import SeqIO
def sequence_length(fasta):
"""
return a dict of the lengths of sequences in a fasta file
"""
file_handle = open(fasta)
in_handle = SeqIO.parse(file_handle, "fasta")
records = {record.id: len(record) for record in in_handle}
file_handle.close()
return records
| from Bio import SeqIO
def sequence_length(fasta):
"""
return a dict of the lengths of sequences in a fasta file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = {record.id: len(record) for record in sequences}
return records
def sequence_names(fasta):
"""
return a list of the sequ... | Add function to get list of sequence names from a FASTA file. | Add function to get list of sequence names from a FASTA file.
Refactor to be simpler.
| Python | mit | vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,chapmanb/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,vladsaveliev/bcbio-nextgen,brainstorm/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,a113n/bcbio-nextgen... |
e6d7ec55bf00960d42b3288ae5e0e501030d5fa9 | test/library/gyptest-shared-obj-install-path.py | test/library/gyptest-shared-obj-install-path.py | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
import... | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
# Pyth... | Add with_statement import for python2.5. | Add with_statement import for python2.5.
See http://www.python.org/dev/peps/pep-0343/ which describes
the with statement.
Review URL: http://codereview.chromium.org/5690003 | Python | bsd-3-clause | witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp |
4e1d0ce04c762d60eedf5bd2ecdd689fb706cbc2 | anserv/cronjobs/__init__.py | anserv/cronjobs/__init__.py | registered = {}
registered_lock = {}
parameters = {}
def register(f=None, lock=True, params={}):
"""Decorator to add the function to the cronjob library.
@cronjobs.register
def my_task():
print('I can be run once/machine at a time.')
@cronjobs.register(lock=False)
def ... | registered = {}
registered_lock = {}
parameters = {}
from decorator import decorator
def register(f=None, lock=True, params={}):
"""Decorator to add the function to the cronjob library.
@cronjobs.register
def my_task():
print('I can be run once/machine at a time.')
@cronjobs.r... | Change decorators in cron to preserve signature | Change decorators in cron to preserve signature
| Python | agpl-3.0 | edx/edxanalytics,edx/edxanalytics,edx/edxanalytics,edx/insights,edx/insights,edx/edxanalytics |
6fa5c20f4d3b6ea9716adbf4c5fd50739f2f987e | protractor/test.py | protractor/test.py | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | Add hook for protactor params | Add hook for protactor params
| Python | mit | jpulec/django-protractor,penguin359/django-protractor |
ac850c8f9284fbe6fd8e6318431d5e4856f26c7c | openquake/calculators/tests/classical_risk_test.py | openquake/calculators/tests/classical_risk_test.py | import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self... | import unittest
from nose.plugins.attrib import attr
from openquake.qa_tests_data.classical_risk import (
case_1, case_2, case_3, case_4)
from openquake.calculators.tests import CalculatorTestCase
class ClassicalRiskTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_risk')
def test_case_1(self... | Work on classical_risk test_case_1 and test_case_2 | Work on classical_risk test_case_1 and test_case_2
| Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
5da51e1820c03a76dfdb9926023848b7399691da | inthe_am/taskmanager/models/usermetadata.py | inthe_am/taskmanager/models/usermetadata.py | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.ForeignKey(
User, related_name="metadata", unique=True, on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted... | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.OneToOneField(
User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.... | Change mapping to avoid warning | Change mapping to avoid warning
| Python | agpl-3.0 | coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am |
95fffa0fbe744b9087547a14a97fb7dd0e68ba76 | chainer/functions/__init__.py | chainer/functions/__init__.py | # Non-parameterized functions
from accuracy import accuracy
from basic_math import exp, log
from concat import concat
from copy import copy
from dropout import dropout
from identity import identity
from leaky_relu import leaky_relu
from lstm import lstm
from mean_squared_error import mean_squared... | """Collection of :class:`~chainer.Function` implementations."""
# Parameterized function classes
from batch_normalization import BatchNormalization
from convolution_2d import Convolution2D
from embed_id import EmbedID
from inception import Inception
from linear import Linear
from... | Sort function imports to fit with documentation order | Sort function imports to fit with documentation order
| Python | mit | kikusu/chainer,niboshi/chainer,ttakamura/chainer,wkentaro/chainer,okuta/chainer,cupy/cupy,ktnyt/chainer,nushio3/chainer,cupy/cupy,ytoyama/yans_chainer_hackathon,chainer/chainer,okuta/chainer,jnishi/chainer,keisuke-umezawa/chainer,kashif/chainer,cupy/cupy,cupy/cupy,muupan/chainer,chainer/chainer,masia02/chainer,jnishi/c... |
896f402c79dd3bbe7d5cbc6e59787398a96b3747 | runtests.py | runtests.py | import argparse
import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
f... | import argparse
import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
f... | Add ability to run subset of tests | Add ability to run subset of tests
| Python | mit | aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce |
5e2697b55f1720c4c144840e680004fb28a3cfcc | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | Add more flexibity to run tests independantly | Add more flexibity to run tests independantly
| Python | mit | TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio |
946220075802cc59f3b34d3557c0b749c526c4b1 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
this_dir = os.path.abspath(os.path.dirname(__file__))
if this_dir not in sys.path:
sys.path.insert(0, this_dir)
from django.test.utils import get_runner
from django.conf import settings
def runtests():... | #!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
this_dir = os.path.abspath(os.path.dirname(__file__))
if this_dir not in sys.path:
sys.path.insert(0, this_dir)
from django.test.utils import get_runner
from django.conf import settings
def runtests():... | Add workshift to the list of tests | Add workshift to the list of tests
| Python | bsd-2-clause | knagra/farnsworth,knagra/farnsworth,knagra/farnsworth,knagra/farnsworth |
94788bd7a7ba0a7799689c4613a2afbcc377649b | games/migrations/0016_auto_20161209_1256.py | games/migrations/0016_auto_20161209_1256.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-09 11:56
from __future__ import unicode_literals
from django.db import migrations
from django.core.management import call_command
def create_revisions(apps, schema_editor):
call_command('createinitialrevisions')
class Migration(migrations.Migratio... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-09 11:56
from __future__ import unicode_literals
from django.db import migrations
from django.core.management import call_command
def create_revisions(apps, schema_editor):
call_command('createinitialrevisions')
class Migration(migrations.Migratio... | Add dependency to reversion data migration | Add dependency to reversion data migration
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website |
4c3a2a61c6a8cb5e0ece14bced4ec8b33df45400 | tests/simple/_util.py | tests/simple/_util.py | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... | Add proper logging to tests when in verbose mode | Add proper logging to tests when in verbose mode
| Python | bsd-3-clause | arrayfire/arrayfire_python,pavanky/arrayfire-python,arrayfire/arrayfire-python |
361af42be2c3044a15480572befb1405a603b4ab | VALDprepare.py | VALDprepare.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
# My imports
import argparse
import gzip
def _parser():
parser = argparse.ArgumentParser(description='Prepare the data downloaded '
'from VALD.')
parser.add_argument('input', help='input compressed file')
parser.add_argumen... | #!/usr/bin/env python
# -*- coding: utf8 -*-
# My imports
import argparse
import gzip
import os
def _parser():
parser = argparse.ArgumentParser(description='Prepare the data downloaded '
'from VALD.')
parser.add_argument('input', help='input compressed file', type=str)
... | Check if the file exists before doing anything else. | Check if the file exists before doing anything else.
| Python | mit | DanielAndreasen/astro_scripts |
62f681803401d05fd0a5e554d4d6c7210dcc7c17 | cbv/management/commands/load_all_django_versions.py | cbv/management/commands/load_all_django_versions.py | import os
import re
from django.conf import settings
from django.core.management import call_command, BaseCommand
class Command(BaseCommand):
"""Load the Django project fixtures and all version fixtures"""
def handle(self, **options):
fixtures_dir = os.path.join(settings.DIRNAME, 'cbv', 'fixtures')
... | import glob
import os
from django.core.management import call_command, BaseCommand
class Command(BaseCommand):
"""Load the Django project fixtures and all version fixtures"""
def handle(self, **options):
self.stdout.write('Loading project.json')
call_command('loaddata', 'cbv/fixtures/project... | Use glob for finding version fixtures | Use glob for finding version fixtures
Thanks @ghickman!
| Python | bsd-2-clause | refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector |
b6416ba4c32aaeddb567be4486854d6415c3048e | tornwamp/customize.py | tornwamp/customize.py | """
TornWAMP user-configurable structures.
"""
from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc
from tornwamp.messages import Code
processors = {
Code.HELLO: HelloProcessor,
Code.GOODBYE: GoodbyeProcessor,
Code.SUBSCRIBE: pubsub.SubscribeProcessor,
Code.CALL: rpc.CallProces... | """
TornWAMP user-configurable structures.
"""
from tornwamp.processors import GoodbyeProcessor, HelloProcessor, pubsub, rpc
from tornwamp.messages import Code
processors = {
Code.HELLO: HelloProcessor,
Code.GOODBYE: GoodbyeProcessor,
Code.SUBSCRIBE: pubsub.SubscribeProcessor,
Code.CALL: rpc.CallProces... | Add PublishProcessor to processors' list | Add PublishProcessor to processors' list
| Python | apache-2.0 | ef-ctx/tornwamp |
369964986df0ca558c2e340bc8d15272296af67e | tools/debug_launcher.py | tools/debug_launcher.py | from __future__ import print_function
import sys
import os
import time
import socket
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--launch-adapter')
parser.add_argument('--lldb')
parser.add_argument('--wait-port')
args = parser.parse_args()
if args.launch_adapter:
lld... | from __future__ import print_function
import sys
import os
import time
import socket
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--launch-adapter')
parser.add_argument('--lldb')
parser.add_argument('--wait-port')
args = parser.parse_args()
if args.launch_adapter:
lld... | Fix python debugging on Windows. | Fix python debugging on Windows.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb |
d4aa2b1a0a72696ce34f5aa2f5e588fc3a72e622 | cfgrib/__main__.py | cfgrib/__main__.py |
import argparse
import sys
from . import eccodes
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--selfcheck', default=False, action='store_true')
args = parser.parse_args()
if args.selfcheck:
eccodes.codes_get_api_version()
print("Your system is ready.")
else... | #
# Copyright 2017-2018 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | Add copyright noticeand Authors comment. | Add copyright noticeand Authors comment.
| Python | apache-2.0 | ecmwf/cfgrib |
9fec06c6acf57b4d49b9c49b7e1d3b5c90e2c9c4 | blog/admin.py | blog/admin.py | from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
# list view
date_hierarchy = 'pub_date'
list_display = ('title', 'pub_date')
list_filter = ('pub_date',)
search_fields = ('title', 'text')
# form view
fieldsets = (
(... | from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
# list view
date_hierarchy = 'pub_date'
list_display = ('title', 'pub_date')
list_filter = ('pub_date',)
search_fields = ('title', 'text')
# form view
fieldsets = (
(... | Use horizontal filter for M2M in PostAdmin. | Ch23: Use horizontal filter for M2M in PostAdmin.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.