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 |
|---|---|---|---|---|---|---|---|---|---|
8278da2e22bc1a10ada43585685aa4a0841d14c5 | apps/bluebottle_utils/tests.py | apps/bluebottle_utils/tests.py | import uuid
from django.contrib.auth.models import User
class UserTestsMixin(object):
""" Mixin base class for tests requiring users. """
def create_user(self, username=None, password=None):
""" Create, save and return a new user. """
if not username:
# Generate a random usernam... | import uuid
from django.contrib.auth.models import User
class UserTestsMixin(object):
""" Mixin base class for tests requiring users. """
def create_user(self, username=None, password=None):
""" Create, save and return a new user. """
# If no username is set, create a random unique username... | Make sure generated usernames are unique. | Make sure generated usernames are unique.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
ea250cdd086059ea7976a38c8e94cb4a39709357 | feincms/views/decorators.py | feincms/views/decorators.py | try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps
from feincms.models import Page
def add_page_to_extra_context(view_func):
def inner(request, *args, **kwargs):
kwargs.setdefault('extra_context', {})
kwargs['extra_context']['feincms_page'] = Pa... | try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps
from feincms.models import Page
def add_page_to_extra_context(view_func):
def inner(request, *args, **kwargs):
kwargs.setdefault('extra_context', {})
kwargs['extra_context']['feincms_page'] = Pa... | Call the setup_request page method too in generic views replacements | Call the setup_request page method too in generic views replacements
| Python | bsd-3-clause | mjl/feincms,matthiask/django-content-editor,pjdelport/feincms,hgrimelid/feincms,nickburlett/feincms,mjl/feincms,matthiask/feincms2-content,michaelkuty/feincms,joshuajonah/feincms,michaelkuty/feincms,matthiask/feincms2-content,feincms/feincms,hgrimelid/feincms,mjl/feincms,matthiask/django-content-editor,pjdelport/feincm... |
d1a868ab1ac8163828479e61d1d3efcae127543b | fileapi/tests/test_qunit.py | fileapi/tests/test_qunit.py | import os
from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import modify_settings
from django.utils.functional import empty
from selenium import webdriver
from selenium.webdriver.comm... | import os
from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import modify_settings
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver... | Remove code which worked around a Django bug which is fixed in 1.8+ | Remove code which worked around a Django bug which is fixed in 1.8+
| Python | bsd-2-clause | mlavin/fileapi,mlavin/fileapi,mlavin/fileapi |
b6c44e90df31c42137a80a64f6069056b16e3239 | plugins/auth/crypto/algo_bcrypt.py | plugins/auth/crypto/algo_bcrypt.py | # coding=utf-8
from plugins.auth.crypto.algo_base import BaseAlgorithm
import bcrypt
__author__ = 'Gareth Coles'
class BcryptAlgo(BaseAlgorithm):
def check(self, hash, value, salt=None):
return hash == self.hash(value, hash)
def hash(self, value, salt):
return bcrypt.hashpw(
va... | # coding=utf-8
import bcrypt
from kitchen.text.converters import to_bytes
from plugins.auth.crypto.algo_base import BaseAlgorithm
__author__ = 'Gareth Coles'
class BcryptAlgo(BaseAlgorithm):
def check(self, hash, value, salt=None):
return hash == self.hash(value, hash)
def hash(self, value, salt):
... | Make bcrypt work with Unicode passwords | [Auth] Make bcrypt work with Unicode passwords
| Python | artistic-2.0 | UltrosBot/Ultros,UltrosBot/Ultros |
83f606e50b2a2ba2f283434d6449a46ad405e548 | flask_mongorest/utils.py | flask_mongorest/utils.py | import json
import decimal
import datetime
from bson.dbref import DBRef
from bson.objectid import ObjectId
from mongoengine.base import BaseDocument
isbound = lambda m: getattr(m, 'im_self', None) is not None
class MongoEncoder(json.JSONEncoder):
def default(self, value, **kwargs):
if isinstance(value, Ob... | import json
import decimal
import datetime
from bson.dbref import DBRef
from bson.objectid import ObjectId
from mongoengine.base import BaseDocument
isbound = lambda m: getattr(m, 'im_self', None) is not None
class MongoEncoder(json.JSONEncoder):
def default(self, value, **kwargs):
if isinstance(value, Ob... | Fix bad call to superclass method | Fix bad call to superclass method
| Python | bsd-3-clause | elasticsales/flask-mongorest,DropD/flask-mongorest,elasticsales/flask-mongorest,DropD/flask-mongorest |
0e1dd74c70a2fa682b3cd3b0027162ad50ee9998 | social/app/views/friend.py | social/app/views/friend.py | from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from social.app.models.author import Author
class FriendRequestsListView(generic.ListView):
context_object_name = "all_friend_requests"
template_name = "app/friend_requests_list.html"
def get_qu... | from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from social.app.models.author import Author
class FriendRequestsListView(generic.ListView):
context_object_name = "all_friend_requests"
template_name = "app/friend_requests_list.html"
def get_qu... | Put in a raise for status for now | Put in a raise for status for now
| Python | apache-2.0 | TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution |
8e87689fd0edaf36349c3a6390fd8a6d18038f41 | fortuitus/fcore/views.py | fortuitus/fcore/views.py | from django.contrib import messages, auth
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.views.generic.base import TemplateView
from fortuitus.fcore import forms
class Home(TemplateView):
""" Home page. """
template_name = 'fortuitus/fcore/home.html'
... | from django.contrib import messages, auth
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.views.generic.base import TemplateView
from fortuitus.fcore import forms
class Home(TemplateView):
""" Home page. """
t... | Add auto-login feature for demo view | Add auto-login feature for demo view
| Python | mit | elegion/djangodash2012,elegion/djangodash2012 |
cbb11e996381197d551425585fca225d630fa383 | tests/test_simpleflow/utils/test_misc.py | tests/test_simpleflow/utils/test_misc.py | import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
1/0
except Exception as e:
line = format_exc(e)
self.assertEqual("ZeroDivisionError: division by zero", line)... | import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__m... | Remove version-specific exception text test | Remove version-specific exception text test
Signed-off-by: Yves Bastide <3b1fe340dba76bf37270abad774f327f50b5e1d8@botify.com>
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow |
39314b70125d41fb57a468684209bdcfdfb8096f | frigg/builds/serializers.py | frigg/builds/serializers.py | from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'priv... | from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'priv... | Add still_running to build result serializer | Add still_running to build result serializer
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq |
2c2604527cfe0ceb3dbf052bbcaf9e2e660b9e47 | app.py | app.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ephemeral by st0le
# quick way share text between your network devices
from flask import Flask, request, render_template, redirect, url_for
db = {}
app = Flask(__name__)
@app.route('/')
def get():
ip = request.remote_addr
return render_template("index.html", t... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ephemeral by st0le
# quick way share text between your network devices
from flask import Flask, request, render_template, redirect, url_for
db = {}
app = Flask(__name__)
def get_client_ip(request):
# PythonAnywhere.com calls our service through a loabalancer
#... | Fix for PythonAnywhere LoadBalancer IP | Fix for PythonAnywhere LoadBalancer IP
| Python | mit | st0le/ephemeral,st0le/ephemeral |
816b222dd771c84267b3f8c64fd2c1ec7dabfbc4 | ex6.py | ex6.py | x = f"There are {10} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print("I said: {x}.")
print("I also said: '{y}'.")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
w = "Thi... | # left out assignment for types_of_people mentioned in intro
types_of_people = 10
# change variable from 10 to types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
# left out f in front of strin... | Add missing variable and correct f-strings | fix: Add missing variable and correct f-strings
See commented lines for changes to ex6.py:
- add types_of_people variable assigment
- change variable from 10 to types_of_people
- add letter f before f-strings
- omit unnecessary periods
| Python | mit | zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code |
0260e50ab4d1449fa95b8e712861b7e44ac21965 | umessages/appsettings.py | umessages/appsettings.py | # Umessages settings file.
#
# Please consult the docs for more information about each setting.
from django.conf import settings
gettext = lambda s: s
"""
Boolean value that defines ifumessages should use the django messages
framework to notify the user of any changes.
"""
UMESSAGES_USE_MESSAGES = getattr(settings,
... | # Umessages settings file.
#
# Please consult the docs for more information about each setting.
from django.conf import settings
gettext = lambda s: s
CRISPY_TEMPLATE_PACK = getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
"""
Boolean value that defines ifumessages should use the django messages
framework to n... | Use bootstrap template pack by default | Use bootstrap template pack by default
| Python | bsd-3-clause | euanlau/django-umessages,euanlau/django-umessages |
bc9c0120523548d5a28c6a21f48831c1daa39af3 | tests/test_data_structures.py | tests/test_data_structures.py | try:
import unittest2 as unittest
except ImportError:
import unittest
import zstd
class TestCompressionParameters(unittest.TestCase):
def test_init_bad_arg_type(self):
with self.assertRaises(TypeError):
zstd.CompressionParameters()
with self.assertRaises(TypeError):
... | try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import hypothesis
import hypothesis.strategies as strategies
except ImportError:
hypothesis = None
import zstd
class TestCompressionParameters(unittest.TestCase):
def test_init_bad_arg_type(self):
with self.ass... | Add hypothesis test to randomly generate CompressionParameters | Add hypothesis test to randomly generate CompressionParameters | Python | bsd-3-clause | terrelln/python-zstandard,indygreg/python-zstandard,terrelln/python-zstandard,terrelln/python-zstandard,indygreg/python-zstandard,indygreg/python-zstandard,indygreg/python-zstandard,terrelln/python-zstandard |
4ca1c0bf5e950ab9710d8a76aa788a5f22641395 | wagtail_mvc/tests.py | wagtail_mvc/tests.py | # -*- coding: utf-8 -*-
"""
wagtail_mvc tests
"""
from __future__ import unicode_literals
from django.test import TestCase
from mock import Mock
from wagtail_mvc.models import WagtailMvcViewWrapper
class WagtailMvcViewWrapperTestCase(TestCase):
"""
Tests the WagtailMvcViewWrapper
"""
def setUp(self):
... | # -*- coding: utf-8 -*-
"""
wagtail_mvc tests
"""
from __future__ import unicode_literals
from django.test import TestCase
from mock import Mock
from wagtail_mvc.models import WagtailMvcViewWrapper
class WagtailMvcViewWrapperTestCase(TestCase):
"""
Tests the WagtailMvcViewWrapper
"""
def setUp(self):
... | Add test stubs for Model Mixin behaviour | Add test stubs for Model Mixin behaviour
| Python | mit | fatboystring/Wagtail-MVC,fatboystring/Wagtail-MVC |
9c596afebfe5fb6746ec2a157d71bb315b02c0cf | tests/unit/test_exceptions.py | tests/unit/test_exceptions.py | #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licens... | #!/usr/bin/env
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licens... | Add test to check excplicitly if the attribute is set | Add test to check excplicitly if the attribute is set
| Python | apache-2.0 | boto/botocore,pplu/botocore |
e4580a598e7d930ad90f5480751804fc1fa89826 | pronto/__init__.py | pronto/__init__.py | import pkg_resources
__author__ = "Martin Larralde <martin.larralde@embl.de>"
__license__ = "MIT"
__version__ = pkg_resources.resource_string(__name__, "_version.txt").decode('utf-8').strip()
from .ontology import Ontology # noqa: F401
from .term import Term # noqa: F401
from .definition import Definition # noqa: ... | import pkg_resources
__author__ = "Martin Larralde <martin.larralde@embl.de>"
__license__ = "MIT"
__version__ = (
__import__('pkg_resources')
.resource_string(__name__, "_version.txt")
.decode('utf-8')
.strip()
)
from .ontology import Ontology # noqa: F401
from .term import Term # noqa: F401
from .d... | Remove `pkg_resources` from the top-level package | Remove `pkg_resources` from the top-level package
| Python | mit | althonos/pronto |
1c65f476c34345267cadb4851fb4fb2ca21333c4 | axelrod/strategies/__init__.py | axelrod/strategies/__init__.py | from cooperator import *
from defector import *
from grudger import *
from rand import *
from titfortat import *
from gobymajority import *
from alternator import *
from averagecopier import *
from grumpy import *
strategies = [
Defector,
Cooperator,
TitForTat,
Grudger,
GoByMaj... | from cooperator import *
from defector import *
from grudger import *
from rand import *
from titfortat import *
from gobymajority import *
from alternator import *
from averagecopier import *
from grumpy import *
from inverse import *
strategies = [
Defector,
Cooperator,
TitForTat,
Gr... | Change init to add inverse strategy | Change init to add inverse strategy | Python | mit | bootandy/Axelrod,emmagordon/Axelrod,mojones/Axelrod,drvinceknight/Axelrod,emmagordon/Axelrod,kathryncrouch/Axelrod,bootandy/Axelrod,risicle/Axelrod,uglyfruitcake/Axelrod,kathryncrouch/Axelrod,mojones/Axelrod,uglyfruitcake/Axelrod,risicle/Axelrod |
074c6fb8bf3f7092920ccae04de26a1a822c38a9 | tohu/v3/derived_generators.py | tohu/v3/derived_generators.py | from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
self.func = func
self.orig_arg_gens = arg_gens
self.orig_kwarg_gens = kwarg_gens
... | from .base import TohuBaseGenerator
DERIVED_GENERATORS = ['Apply']
__all__ = DERIVED_GENERATORS + ['DERIVED_GENERATORS']
class Apply(TohuBaseGenerator):
def __init__(self, func, *arg_gens, **kwarg_gens):
super().__init__()
self.func = func
self.orig_arg_gens = arg_gens
self.orig... | Add spawn method to Apply; initialise clones by calling super().__init__() | Add spawn method to Apply; initialise clones by calling super().__init__()
| Python | mit | maxalbert/tohu |
e2fc339b20f013d561ed7365a20d0b39c24dcb46 | scikits/talkbox/__init__.py | scikits/talkbox/__init__.py | from lpc import *
import lpc
__all__ = lpc.__all__
| from lpc import *
import lpc
__all__ = lpc.__all__
from tools import *
import tools
__all__ += tools.__all__
| Add tools general imports to talkbox namespace. | Add tools general imports to talkbox namespace.
| Python | mit | cournape/talkbox,cournape/talkbox |
e9fd097aac951e6d38246fc4fb01db0e0b6513eb | scikits/talkbox/__init__.py | scikits/talkbox/__init__.py | from linpred import *
import linpred
__all__ = linpred.__all__
from tools import *
import tools
__all__ += tools.__all__
| from linpred import *
import linpred
__all__ = linpred.__all__
from tools import *
import tools
__all__ += tools.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
| Add module-wide bench and test functions. | Add module-wide bench and test functions.
| Python | mit | cournape/talkbox,cournape/talkbox |
a9bdf9ec691f0e688af41be1216977b9ce9c8976 | helpers.py | helpers.py | """ A bunch of helper functions that, when fixed up, will return the things we
need to make this website work! These functions use the weather and twitter APIs!!!
"""
## Import python libraries we need up here.
###############################################
### Problem One! ###
#########... | """ A bunch of helper functions that, when fixed up, will return the things we
need to make this website work! These functions use the weather and twitter APIs!!!
"""
## Import python libraries we need up here.
###############################################
### Problem One! ###
#########... | Set tweet limit to 30 tweets | Set tweet limit to 30 tweets
| Python | apache-2.0 | samanehsan/spark_github,samanehsan/spark_github,samanehsan/learn-git,samanehsan/learn-git |
93bd76fc99ef6f399393761aef11c0840e587b2d | update-zips.py | update-zips.py | #!/usr/bin/env python3
"""Remake the ziptestdata.zip file.
Run this to rebuild the importlib_resources/tests/data/ziptestdata.zip file,
e.g. if you want to add a new file to the zip.
This will replace the file with the new build, but it won't commit anything to
git.
"""
import contextlib
import os
import pathlib
fr... | #!/usr/bin/env python3
"""Remake the ziptestdata.zip file.
Run this to rebuild the importlib_resources/tests/data/ziptestdata.zip file,
e.g. if you want to add a new file to the zip.
This will replace the file with the new build, but it won't commit anything to
git.
"""
import contextlib
import os
import pathlib
fr... | Use relative_to instead of string manipulation | Use relative_to instead of string manipulation
| Python | apache-2.0 | python/importlib_resources |
97940ed6ddd7d50feb47a932be096be5b223b1f0 | assassins/assassins/views.py | assassins/assassins/views.py | from django.shortcuts import render, redirect
from django.contrib.auth import views as auth_views
# Create your views here.
def index(request):
pass
def login(request, **kwargs):
if request.user.is_authenticated():
return redirect('index')
else:
return auth_views.login(request)
| from django.shortcuts import render, redirect
from django.contrib.auth import views as auth_views
from django.views.decorators.http import require_POST
# Create your views here.
def index(request):
pass
@require_POST
def login(request, **kwargs):
if request.user.is_authenticated():
return redirect('index')
else:... | Modify login view to be a post endpoint | Modify login view to be a post endpoint
| Python | mit | Squa256/assassins,bobandbetty/assassins,bobandbetty/assassins,bobandbetty/assassins,Squa256/assassins,Squa256/assassins |
da990bff61c0088f239defac486da1303f97c08a | app/admin/routes.py | app/admin/routes.py | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... | Add a route to admin/news | Add a route to admin/news
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is |
992525f8b371582598fa915128eccd3528e427a6 | main.py | main.py | # coding: utf-8
from flask import Flask, abort, request, redirect, render_template, url_for
from log import log
import util
app = Flask(__name__)
app.config.from_pyfile('config.cfg', silent=True)
@app.route('/')
def home():
log.info('Fetching demo gist.')
gist_id = '5123482'
gist = util.get_gist_by_id(gis... | # coding: utf-8
from flask import Flask, abort, request, redirect, render_template, url_for
from log import log
import util
import os
app = Flask(__name__)
app.config.from_pyfile(os.path.join(os.path.dirname(__file__), 'config.cfg'), silent=True)
@app.route('/')
def home():
log.info('Fetching demo gist.')
gis... | Fix config file path error on the server | Fix config file path error on the server
| Python | mit | moreati/remarks,greatghoul/remarks,greatghoul/remarks,moreati/remarks,greatghoul/remarks,moreati/remarks |
2d8b7253445193131d027bd12d3389bbc03858e5 | massa/__init__.py | massa/__init__.py | # -*- coding: utf-8 -*-
from flask import Flask, render_template, g
from .container import build
from .web import bp as web
from .api import bp as api
from .middleware import HTTPMethodOverrideMiddleware
def create_app(config=None):
app = Flask('massa')
app.config.from_object(config or 'massa.config.Producti... | # -*- coding: utf-8 -*-
from flask import Flask, g
from .container import build
from .web import bp as web
from .api import bp as api
from .middleware import HTTPMethodOverrideMiddleware
def create_app(config=None):
app = Flask('massa')
app.config.from_object(config or 'massa.config.Production')
app.conf... | Remove unused render_template from import statement. | Remove unused render_template from import statement. | Python | mit | jaapverloop/massa |
a1e1340285e190f5b0cc3cce2c4155cb313df6a7 | wafer/schedule/serializers.py | wafer/schedule/serializers.py | from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page = serializers.PrimaryKeyRelatedField(
allow_null=True, quer... | from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page = serializers.PrimaryKeyRelatedField(
allow_null=True, quer... | Clear extra fields when changing items through the schedule view | Clear extra fields when changing items through the schedule view
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
8684376106d2b6763823573662ffde574d075d1b | workers/subscriptions.py | workers/subscriptions.py | import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.... | import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
sen... | Remove collecting plugins every second | Remove collecting plugins every second
| Python | mit | sevazhidkov/leonard |
854b0968afc41894d8cf79d712175b497df9828e | bolt/spark/utils.py | bolt/spark/utils.py | def get_kv_shape(shape, key_axes):
func = lambda axis: shape[axis]
return _get_kv_func(func, shape, key_axes)
def get_kv_axes(shape, key_axes):
func = lambda axis: axis
return _get_kv_func(func, shape, key_axes)
def _get_kv_func(func, shape, key_axes):
key_res = [func(axis) for axis in key_axes]
... | def get_kv_shape(shape, key_axes):
func = lambda axis: shape[axis]
return _get_kv_func(func, shape, key_axes)
def get_kv_axes(shape, key_axes):
func = lambda axis: axis
return _get_kv_func(func, shape, key_axes)
def _get_kv_func(func, shape, key_axes):
key_res = [func(axis) for axis in key_axes]
... | Fix for count with one partition | Fix for count with one partition
| Python | apache-2.0 | bolt-project/bolt,andrewosh/bolt,jwittenbach/bolt |
d53ff6a32f9de757c7eef841d35d110a389419ae | cattle/plugins/docker/agent.py | cattle/plugins/docker/agent.py | from cattle import Config
from cattle.plugins.docker.util import add_to_env
from urlparse import urlparse
def setup_cattle_config_url(instance, create_config):
if instance.get('agentId') is None:
return
if 'labels' not in create_config:
create_config['labels'] = {}
create_config['labels'... | from cattle import Config
from cattle.plugins.docker.util import add_to_env
from urlparse import urlparse
def _has_label(instance):
try:
return instance.labels['io.rancher.container.cattle_url'] == 'true'
except:
pass
return False
def setup_cattle_config_url(instance, create_config):
... | Add label io.rancher.container.cattle_url=true to get CATTLE_URL env var | Add label io.rancher.container.cattle_url=true to get CATTLE_URL env var
| Python | apache-2.0 | rancherio/python-agent,rancherio/python-agent,rancher/python-agent,rancher/python-agent |
44d437e7c7daf3255c3ab9b0dbaa9bdd700008a4 | foliant/gdrive.py | foliant/gdrive.py | import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.LocalWebserverAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
... | import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
... | Switch from local server to command line auth to fix upload in Docker. | GDrive: Switch from local server to command line auth to fix upload in Docker.
| Python | mit | foliant-docs/foliant |
45f56adc0e9c935f5377791f3735e692b6e57c74 | pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py | pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py | from django import template
from django.contrib.messages.utils import get_level_tags
from django.utils.encoding import force_text
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "... | from django import template
from django.contrib.messages.utils import get_level_tags
from django.utils.encoding import force_text
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "... | Handle instances where level_tag is undefined | Handle instances where level_tag is undefined
Better mimics the implementation of message.tags in Django 1.7
| Python | mit | foraliving/foraliving,druss16/danslist,grahamu/pinax-theme-bootstrap,foraliving/foraliving,jacobwegner/pinax-theme-bootstrap,druss16/danslist,jacobwegner/pinax-theme-bootstrap,druss16/danslist,foraliving/foraliving,grahamu/pinax-theme-bootstrap,grahamu/pinax-theme-bootstrap,jacobwegner/pinax-theme-bootstrap |
427a4b50934e4c4353d98851a33352961d05d051 | backend/submissions/types.py | backend/submissions/types.py | import graphene
from graphene_django import DjangoObjectType
from voting.types import VoteType
from .models import Submission
from .models import SubmissionType as ModelSubmissionType
class SubmissionTypeType(DjangoObjectType):
class Meta:
model = ModelSubmissionType
only_fields = ("id", "name")... | import graphene
from graphene_django import DjangoObjectType
from voting.models import Vote
from voting.types import VoteType
from .models import Submission
from .models import SubmissionType as ModelSubmissionType
class SubmissionTypeType(DjangoObjectType):
class Meta:
model = ModelSubmissionType
... | Add logged user vote field to SubmissionType | Add logged user vote field to SubmissionType
| Python | mit | patrick91/pycon,patrick91/pycon |
ab7a8335bae22bae6f729fc9805810c0c8925703 | isitbullshit/__init__.py | isitbullshit/__init__.py | # -*- coding: utf-8 -*-
__version__ = 0, 1, 1
from .core import isitbullshit, raise_for_problem, WHATEVER # NOQA
from .exceptions import ItIsBullshitError # NOQA
from .testcase_mixin import IsItBullshitMixin # NOQA
# silence for pyflakes
assert isitbullshit
assert raise_for_problem
assert WHATEVER
assert ItIsB... | # -*- coding: utf-8 -*-
__author__ = "Sergey Arkhipov <serge@aerialsounds.org>"
__version__ = 0, 1, 1
from .core import isitbullshit, raise_for_problem, WHATEVER # NOQA
from .exceptions import ItIsBullshitError # NOQA
from .testcase_mixin import IsItBullshitMixin # NOQA
# silence for pyflakes
assert isitbullsh... | Add myself to the module | Add myself to the module
| Python | mit | 9seconds/isitbullshit |
88a6708061ccdc7d3ac4d031c48de44039937b54 | frontends/etiquette_flask/etiquette_flask_entrypoint.py | frontends/etiquette_flask/etiquette_flask_entrypoint.py | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_entrypoint:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.contrib.fixers
import backend
backend.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(backend.site.wsgi_ap... | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_entrypoint:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.... | Replace werkzeug.contrib with werkzeug.middleware proxyfix. | Replace werkzeug.contrib with werkzeug.middleware proxyfix.
werkzeug.contrib has been deprecated, this is the new location
of the proxyfix.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette |
601962d1a34a00c79b0e56b302a17b5673eb8168 | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.leases import Lease
from etcd3.locks import Lock
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@... | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.leases import Lease
from etcd3.locks import Lock
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@... | Reorder '__all__' entries to respect import order | Reorder '__all__' entries to respect import order
| Python | apache-2.0 | kragniz/python-etcd3 |
ee441c445bf8a9401af045993ed4bd5c65db9eff | garnish/utils.py | garnish/utils.py | import sys
def fill_template(temp, args, longname, filename, url):
"""
Takes a template string (temp) and replaces all template keywords with
information from commandline arguments.
"""
temp = temp.replace('OWNER_NAME', args.copyright_holder)
temp = temp.replace('COPYRIGHT_YEAR', args.year)
... | import sys
import textwrap
def fill_template(temp, args, longname, filename, url):
"""
Takes a template string (temp) and replaces all template keywords with
information from commandline arguments.
"""
temp = temp.replace('OWNER_NAME', args.copyright_holder)
temp = temp.replace('COPYRIGHT_YEAR'... | Add function that extends textwrap.wrap to multi-paragraph inputs. | Add function that extends textwrap.wrap to multi-paragraph inputs.
| Python | mit | radicalbiscuit/garnish |
dca788c815fb4375258f7ec0ec85af1c86aab70d | datastore/tasks.py | datastore/tasks.py | from __future__ import absolute_import
import logging
import traceback
from celery import shared_task
from celery.utils.log import get_task_logger
from datastore.models import ProjectRun
logger = get_task_logger(__name__)
@shared_task
def execute_project_run(project_run_pk):
try:
project_run = Projec... | from __future__ import absolute_import
import logging
import traceback
from celery import shared_task
from celery.utils.log import get_task_logger
from datastore.models import ProjectRun
logger = get_task_logger(__name__)
@shared_task
def execute_project_run(project_run_pk):
try:
project_run = Projec... | Add project run to project result. | Add project run to project result.
| Python | mit | impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore |
98ba04f92d5f95c363bf89c0bb937463a6f95eab | tests/test_main.py | tests/test_main.py | import asyncio
import sys
import pytest
pytestmark = pytest.mark.asyncio()
async def test_command_line_send(smtpd_server, hostname, port):
proc = await asyncio.create_subprocess_exec(
sys.executable,
b"-m",
b"aiosmtplib",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.sub... | import asyncio
import sys
import pytest
pytestmark = pytest.mark.asyncio()
async def test_command_line_send(smtpd_server, hostname, port):
proc = await asyncio.create_subprocess_exec(
sys.executable,
b"-m",
b"aiosmtplib",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.sub... | Fix deadlock in subprocess pipes | Fix deadlock in subprocess pipes
| Python | mit | cole/aiosmtplib |
659321fafc7379f32f45f86eb4c366de884cce35 | tests/test_ping.py | tests/test_ping.py | from rohrpost.handlers import handle_ping
def test_ping(message):
handle_ping(message, request={'id': 123})
assert message.reply_channel.closed is False
assert len(message.reply_channel.data) == 1
data = message.reply_channel.data[-1]
assert data['id'] == 123
assert data['type'] == 'pong'
... | from rohrpost.handlers import handle_ping
def test_ping(message):
handle_ping(message, request={'id': 123})
assert message.reply_channel.closed is False
assert len(message.reply_channel.data) == 1
data = message.reply_channel.data[-1]
assert data['id'] == 123
assert data['type'] == 'pong'
... | Add a failing test that demonstrates wrong handling of data | [tests] Add a failing test that demonstrates wrong handling of data
The ping handler adds the data directly to the response_kwargs,
allowing internal kwargs to be overwritten.
`send_message()` and `build_message()` should not accept
`**additional_data`, but `additional_data: dict = None` instead.
| Python | mit | axsemantics/rohrpost,axsemantics/rohrpost |
8830e4e86a9b9e807017a55da5c4faab76e01b69 | tests/test_util.py | tests/test_util.py | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | import pytest
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
def t... | Cover unknown time format case | Cover unknown time format case
| Python | mit | CodersOfTheNight/verata |
8dc7035d10f648489bbdfd3087a65f0355e1a72c | tests/test_mapping.py | tests/test_mapping.py | from unittest import TestCase
from prudent.mapping import Mapping
class MappingTest(TestCase):
def setUp(self):
self.mapping = Mapping([(1, 2), (2, 3), (3, 4)])
def test_iter(self):
keys = [1, 2, 3]
for _ in range(2):
assert list(self.mapping) == keys
def test_contain... | from unittest import TestCase
from prudent.mapping import Mapping
class MappingTest(TestCase):
def setUp(self):
self.mapping = Mapping([(1, 2), (2, 3), (3, 4)])
def test_iter_preserves_keys(self):
keys = [1, 2, 3]
for _ in range(2):
assert list(self.mapping) == keys
d... | Use a more descriptive test case name | Use a more descriptive test case name
| Python | mit | eugene-eeo/prudent |
6848eb77af8dc274f881e5895e541923f34e5354 | elections/admin.py | elections/admin.py | from django.contrib import admin
from .models import (Election, VacantPosition, Candidature, Vote)
@admin.register(Election)
class ElectionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Candida... | from django.contrib import admin
from .models import (Election, VacantPosition, Candidature, Vote)
class VacantPositionInline(admin.StackedInline):
model = VacantPosition
extra = 0
@admin.register(Election)
class ElectionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
inlines = [Va... | Move VacantPosition to Election as an inline. Remove Vote. | Move VacantPosition to Election as an inline. Remove Vote.
| Python | mit | QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation |
69b33f8f87b6dfc0fbaf96eca25c02535c9e09e7 | src/test/almost_equal.py | src/test/almost_equal.py | def datetime_almost_equal(datetime1, datetime2, seconds=60):
dd = datetime1 - datetime2
sd = (dd.days * 24 * 60 * 60) + dd.seconds
return abs(sd) <= seconds
| from datetime import datetime
import pytz
def datetime_almost_equal(datetime1:datetime, datetime2:datetime, seconds:int=60):
if not(datetime1.tzinfo):
datetime1 = pytz.utc.localize(datetime1)
datetime1 = datetime1.astimezone(pytz.utc)
if not(datetime2.tzinfo):
datetime2 = pytz.utc.localiz... | Make sure all datetimes are UTC | Make sure all datetimes are UTC
| Python | apache-2.0 | sffjunkie/astral,sffjunkie/astral |
f4e5f0587c1214433de46fc5d86e77d849fdddc4 | src/robot/utils/robotio.py | src/robot/utils/robotio.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | Replace TODO with comment explaining why it wasn't possible | Replace TODO with comment explaining why it wasn't possible
| Python | apache-2.0 | alexandrul-ci/robotframework,synsun/robotframework,jaloren/robotframework,snyderr/robotframework,joongh/robotframework,HelioGuilherme66/robotframework,HelioGuilherme66/robotframework,alexandrul-ci/robotframework,synsun/robotframework,synsun/robotframework,snyderr/robotframework,joongh/robotframework,synsun/robotframewo... |
ffdf13c8217f3a785fe8768697b3e3da4b6ff9cb | cherrypy/py3util.py | cherrypy/py3util.py | """
A simple module that helps unify the code between a python2 and python3 library.
"""
import sys
def sorted(lst):
newlst = list(lst)
newlst.sort()
return newlst
def reversed(lst):
newlst = list(lst)
return iter(newlst[::-1])
| """
A simple module that helps unify the code between a python2 and python3 library.
"""
import sys
try:
sorted = sorted
except NameError:
def sorted(lst):
newlst = list(lst)
newlst.sort()
return newlst
try:
reversed = reversed
except NameError:
def reversed(lst):
newls... | Use builtin sorted, reversed if available. | Use builtin sorted, reversed if available.
| Python | bsd-3-clause | cherrypy/cheroot,Safihre/cherrypy,cherrypy/cherrypy,Safihre/cherrypy,cherrypy/cherrypy |
a978d79bf1a7c9ec9b38841c3e809bd2dc52f3c0 | corehq/apps/commtrack/admin.py | corehq/apps/commtrack/admin.py | from django.contrib import admin
from .models import StockState
class StockStateAdmin(admin.ModelAdmin):
model = StockState
list_display = [
'section_id',
'case_id',
'product_id',
'stock_on_hand',
'daily_consumption',
'last_modified_date'
]
list_filter =... | from django.contrib import admin
from .models import StockState
class StockStateAdmin(admin.ModelAdmin):
model = StockState
list_display = [
'section_id',
'case_id',
'product_id',
'stock_on_hand',
'daily_consumption',
'last_modified_date'
]
list_filter =... | Use product/case id's in search rather than filter | Use product/case id's in search rather than filter
| Python | bsd-3-clause | dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttar... |
1e73195e33c384605072e36ac1551bd6d67ba7cb | QGL/BasicSequences/__init__.py | QGL/BasicSequences/__init__.py | from RabiAmp import RabiAmp
from Ramsey import Ramsey
from FlipFlop import FlipFlop
from SPAM import SPAM
from RB import SingleQubitRB, SingleQubitRB_AC, SingleQubitRBT | from RabiAmp import RabiAmp
from Ramsey import Ramsey
from FlipFlop import FlipFlop
from SPAM import SPAM
from RB import SingleQubitRB, SingleQubitRB_AC, SingleQubitRBT
from itertools import product
import operator
from ..PulsePrimitives import Id, X
def create_cal_seqs(qubits, numCals):
"""
Helper function to c... | Add a helper function to create calibration sequences. | Add a helper function to create calibration sequences.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,calebjordan/PyQLab,BBN-Q/PyQLab,rmcgurrin/PyQLab |
519aff5c44c6801c44981b059654e598c6d8db49 | second/blog/models.py | second/blog/models.py | from __future__ import unicode_literals
from django.db import models
# Create your models here.
| from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(de... | Create Post model in model.py | Create Post model in model.py
| Python | mit | ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects |
f59adf7887d26c09257b16438a2d920861be3f33 | eventtools/tests/_inject_app.py | eventtools/tests/_inject_app.py | from django.test import TestCase
from django.conf import settings
from django.db.models.loading import load_app
from django.core.management import call_command
from _fixture import fixture
APP_NAME = 'eventtools.tests.eventtools_testapp'
class TestCaseWithApp(TestCase):
"""Make sure to call super(..).setUp and t... | from django.db.models.loading import load_app
from django.conf import settings
from django.core.management import call_command
from django.template.loaders import app_directories
from django.template import loader
from django.test import TestCase
from _fixture import fixture
APP_NAME = 'eventtools.tests.eventtools_te... | Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there) | Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there) | Python | bsd-3-clause | ixc/glamkit-eventtools,ixc/glamkit-eventtools |
155f53100148ffd09e9e0e0f1f9de073974ea97b | osgtest/tests/test_89_condor.py | osgtest/tests/test_89_condor.py | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopCondor(osgunittest.OSGTestCase):
def test_01_stop_condor(self):
core.skip_ok_unless_installed('condor')
self.skip_ok_i... | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopCondor(osgunittest.OSGTestCase):
def test_01_stop_condor(self):
core.skip_ok_unless_installed('condor')
self.skip_ok_u... | Use skip_ok_unless instead of a comparison against 'False' | Use skip_ok_unless instead of a comparison against 'False'
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
73373c893c1fe8412b5a3fecc83767988b1bccdf | genshi/__init__.py | genshi/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consist... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consist... | Remove pkg_resources import from top-level package, will just need to remember updating the version in two places. | Remove pkg_resources import from top-level package, will just need to remember updating the version in two places.
| Python | bsd-3-clause | hodgestar/genshi,hodgestar/genshi,hodgestar/genshi,hodgestar/genshi |
1edf69ac029bf8e35cd897fa123ad4e0943d6bc9 | src/wikicurses/__init__.py | src/wikicurses/__init__.py | from enum import Enum
class BitEnum(int, Enum):
def __new__(cls, *args):
value = 1 << len(cls.__members__)
return int.__new__(cls, value)
formats = BitEnum("formats", "i b blockquote")
| from enum import IntEnum
class formats(IntEnum):
i, b, blockquote = (1<<i for i in range(3))
| Remove BitEnum class, use IntEnum | Remove BitEnum class, use IntEnum
| Python | mit | ids1024/wikicurses |
96e0f2621dafd691e4560afe9b59df21aad3d2a8 | taskwiki/cache.py | taskwiki/cache.py | import vim
from taskwiki.task import VimwikiTask
class TaskCache(object):
"""
A cache that holds all the tasks in the given file and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, tw):
self.cache = dict()
self.tw = tw
def __getitem__(self, key):
... | import copy
import vim
from taskwiki.task import VimwikiTask
class TaskCache(object):
"""
A cache that holds all the tasks in the given file and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, tw):
self.uuid_cache = dict()
self.cache = dict()
self.tw... | Index tasks by uuid as well as line number | Cache: Index tasks by uuid as well as line number
| Python | mit | phha/taskwiki,Spirotot/taskwiki |
be1d11bcf53ecab1fbb0e69191c62c83492363d2 | cmn_color_helper.py | cmn_color_helper.py | class ColorStr:
_HEADER = '\033[95m'
_OKBLUE = '\033[94m'
_OKGREEN = '\033[92m'
_WARNING = '\033[93m'
_FAIL = '\033[91m'
_ENDC = '\033[0m'
_BOLD = '\033[1m'
_UNDERLINE = '\033[4m'
@staticmethod
def color_fun_name(fun):
return ColorStr._UNDERLINE + ColorStr._BOLD + Color... | class ColorStr:
_HEADER = '\033[95m'
_OKBLUE = '\033[94m'
_OKGREEN = '\033[92m'
_WARNING = '\033[93m'
_FAIL = '\033[91m'
_ENDC = '\033[0m'
_BOLD = '\033[1m'
_UNDERLINE = '\033[4m'
@staticmethod
def color_fun_name(fun):
return ColorStr._HEADER + ColorStr._BOLD + fun + Co... | Change function and pkg color style. | Change function and pkg color style.
| Python | mit | fanchen1988/sc-common-helper |
a175dbf2f239690cb5128698d5896233467e285e | huxley/settings/pipeline.py | huxley/settings/pipeline.py | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from os.path import join
from .roots import PROJECT_ROOT
PIPELINE_COMPILERS = (
'huxley.utils.pipeline.PySCSSCompiler',
'pipeline_browserify.compiler.Browserify... | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from os.path import join
from .roots import PROJECT_ROOT
PIPELINE_COMPILERS = (
'huxley.utils.pipeline.PySCSSCompiler',
'pipeline_browserify.compiler.Browserify... | Clean up file patterns in PIPELINE_CSS setting. | Clean up file patterns in PIPELINE_CSS setting.
| Python | bsd-3-clause | ctmunwebmaster/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,bmun/huxley,bmun/huxley,nathanielparke/huxley,nathanielparke/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,bmun/huxley,ctmunwebmaster/huxley,bmun/huxley |
85ff7e048a1e9c913adb7749cfed0aa903366197 | data/load_data.py | data/load_data.py | import csv
from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint
def main(path):
with open(path, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
points = []
for row in reader:
if... | import csv
from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint
def main(path):
with open(path, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
points = []
count = 0
for row in read... | Add indicator for how many datapoints have been loaded | Add indicator for how many datapoints have been loaded
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp |
dd69f35b623fa93579930e03c3aea8fc8f290136 | lc0001_two_sum.py | lc0001_two_sum.py | """Leetcode 1. Two Sum
Easy
URL: https://leetcode.com/problems/two-sum/description/
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given n... | """Leetcode 1. Two Sum
Easy
URL: https://leetcode.com/problems/two-sum/description/
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given n... | Revise to var n & add space line | Revise to var n & add space line
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
bbc65d55d247d290a427ac5ba2c43b9d0033654d | WeatherServer/weather/views.py | WeatherServer/weather/views.py | import IP
from flask import Blueprint, request, render_template, jsonify
weather = Blueprint('weather', __name__, url_prefix='/weather')
@weather.route('/', methods=['GET'])
def index():
ip = request.remote_addr
location = IP.find(ip)
return jsonify(location=location, ip=ip)
| import IP
from flask import Blueprint, request, render_template, jsonify
weather = Blueprint('weather', __name__, url_prefix='/weather')
@weather.route('/', methods=['GET'])
def index():
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip... | Fix user's real ip address. | Fix user's real ip address.
| Python | mit | keysona/WeatherServer,keysona/WeatherServer,keysona/WeatherServer,keysona/WeatherServer |
6b73de9fea31b7a5176601d7f19370291ba4e130 | tests/test_transpiler.py | tests/test_transpiler.py | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
transpiler.main(["--output-dir", "/tmp"])
assert os.path.isfile("/tmp/auto_functions.cpp")
assert os.path.isfile("/tmp/auto_functions.h")
def test_transpiler_cre... | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pass
transpiler.main(["--ou... | Make transpiler test remove files if they already exist | Make transpiler test remove files if they already exist
| Python | mit | WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler |
903a618cbde1f6d4c18a806e9bb8c3d17bc58b3b | flocker/control/test/test_script.py | flocker/control/test/test_script.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from twisted.web.server import Site
from twisted.trial.unittest import SynchronousTestCase
from ..script import ControlOptions, ControlScript
from ...testtools import MemoryCoreReactor
class ControlOptionsTests():
"""
Tests for ``ControlOptions``.... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from twisted.web.server import Site
from twisted.trial.unittest import SynchronousTestCase
from ..script import ControlOptions, ControlScript
from ...testtools import MemoryCoreReactor, StandardOptionsTestsMixin
class ControlOptionsTests(StandardOptionsTe... | Make sure options tests run. | Make sure options tests run.
| Python | apache-2.0 | 1d4Nf6/flocker,runcom/flocker,w4ngyi/flocker,lukemarsden/flocker,agonzalezro/flocker,w4ngyi/flocker,hackday-profilers/flocker,achanda/flocker,mbrukman/flocker,runcom/flocker,jml/flocker,1d4Nf6/flocker,achanda/flocker,adamtheturtle/flocker,agonzalezro/flocker,Azulinho/flocker,lukemarsden/flocker,moypray/flocker,1d4Nf6/f... |
6642c377d579a8401eb5827f25a1aaf6ab117921 | tests/benchmark/plugins/clear_buffer_cache.py | tests/benchmark/plugins/clear_buffer_cache.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Update clear buffer cache plugin to only flush page cache. | Update clear buffer cache plugin to only flush page cache.
More detail: http://linux-mm.org/Drop_Caches
Change-Id: I7fa675ccdc81f375d88e9cfab330fca3bc983ec8
Reviewed-on: http://gerrit.ent.cloudera.com:8080/1157
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
Reviewed-by: Lenni Kuff <724... | Python | apache-2.0 | cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala |
ceadcb80150278ae29fb60b339049f4c840c135d | astroquery/nist/tests/test_nist_remote.py | astroquery/nist/tests/test_nist_remote.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
import requests
import imp
from ... import nist
imp.reload(requests)
@remote_data
class TestNist:
def tes... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import numpy as np
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
from ... import nist
@remote_data
class TestNist:
def test_query_async(self):
... | Add missing numpy import, and cleanup the rest | Add missing numpy import, and cleanup the rest
| Python | bsd-3-clause | ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery |
76728fcba7671575053620da9e1e26aaa279547a | awx/main/notifications/webhook_backend.py | awx/main/notifications/webhook_backend.py | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import logging
import requests
import json
from django.utils.encoding import smart_text
from awx.main.notifications.base import TowerBaseEmailBackend
logger = logging.getLogger('awx.main.notifications.webhook_backend')
class WebhookBackend(TowerBaseEmailBac... | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import logging
import requests
import json
from django.utils.encoding import smart_text
from awx.main.notifications.base import TowerBaseEmailBackend
from awx.main.utils import get_awx_version
logger = logging.getLogger('awx.main.notifications.webhook_backen... | Set a user agent for the webhook if not provided | Set a user agent for the webhook if not provided
| Python | apache-2.0 | wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx |
4630b898e37d0653baa22c98578eb06c82eebfe6 | kobo/hub/admin.py | kobo/hub/admin.py | # -*- coding: utf-8 -*-
import django.contrib.admin as admin
from models import *
class TaskAdmin(admin.ModelAdmin):
list_display = ("id", "method", "label", "state", "owner", "dt_created", "dt_finished", "time", "arch", "channel")
list_filter = ("method", "state")
search_fields = ("id", "method", "lab... | # -*- coding: utf-8 -*-
import django.contrib.admin as admin
from models import *
class TaskAdmin(admin.ModelAdmin):
list_display = ("id", "method", "label", "state", "owner", "dt_created", "dt_finished", "time", "arch", "channel")
list_filter = ("method", "state")
search_fields = ("id", "method", "lab... | Fix TaskAdmin to search for user in correct db field. | Fix TaskAdmin to search for user in correct db field.
| Python | lgpl-2.1 | pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo |
3189b35f4fea14962cc5dcff7385d7e02bba4e01 | plata/product/feincms/models.py | plata/product/feincms/models.py | from django.utils.translation import get_language, ugettext_lazy as _
from feincms.models import Base
from plata.product.models import Product, ProductManager
class CMSProduct(Product, Base):
"""
FeinCMS-based product model
"""
class Meta:
app_label = 'product'
verbose_name = _('pro... | from django.utils.translation import get_language, ugettext_lazy as _
from feincms.models import Base
from plata.product.models import Product, ProductManager
class CMSProduct(Product, Base):
"""
FeinCMS-based product model
The admin integration requires FeinCMS >=1.2 to work correctly.
"""
cl... | Add note about FeinCMS version requirements | Add note about FeinCMS version requirements
| Python | bsd-3-clause | armicron/plata,armicron/plata,stefanklug/plata,armicron/plata,allink/plata |
8528f21397672b5719fcf4edecd8efa3a1eec60a | cellardoor/serializers/json_serializer.py | cellardoor/serializers/json_serializer.py | import re
import json
from datetime import datetime
from . import Serializer
class CellarDoorJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
if isinstance(obj, datetime):
return obj.isoformat()
return s... | import re
import json
from datetime import datetime
import collections
from . import Serializer
class CellarDoorJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, collections.Iterable):
return list(obj)
if isinstance(obj, datetime):
return obj.isoformat()
return super(Cell... | Use more reliable method of detecting iterables | Use more reliable method of detecting iterables
| Python | mit | cooper-software/cellardoor |
daeabec6f055ca232903f50f307b5ab8a518b1aa | apps/domain/src/main/core/manager/environment_manager.py | apps/domain/src/main/core/manager/environment_manager.py | from typing import List
from typing import Union
from .database_manager import DatabaseManager
from ..database.environment.environment import Environment
from ..database.environment.user_environment import UserEnvironment
from ..exceptions import (
EnvironmentNotFoundError,
)
class EnvironmentManager(DatabaseMana... | from typing import List
from typing import Union
from .database_manager import DatabaseManager
from ..database.environment.environment import Environment
from ..database.environment.user_environment import UserEnvironment
from ..exceptions import (
EnvironmentNotFoundError,
)
class EnvironmentManager(DatabaseMana... | ADD delete_associations method at EnvironmentManager | ADD delete_associations method at EnvironmentManager
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
600ec67b175ca78c4dd72b4468368920ce390316 | flask_controllers/GameModes.py | flask_controllers/GameModes.py | from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
digits = GameObject.digits_used
guesses = GameObject.gues... | from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode',... | Add text only mode to get game modes | Add text only mode to get game modes
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
8d409ab4ca35b38d97d17f0f443c8cdb62d5e58e | tests/tests/mendertesting.py | tests/tests/mendertesting.py | import pytest
class MenderTesting(object):
slow = pytest.mark.skipif(not pytest.config.getoption("--runslow"), reason="need --runslow option to run")
fast = pytest.mark.skipif(not pytest.config.getoption("--runfast"), reason="need --runfast option to run")
nightly = pytest.mark.skipif(not pytest.config.get... | import pytest
class MenderTesting(object):
slow_cond = False
fast_cond = False
nightly_cond = False
slow = None
fast = None
nightly = None
if pytest.config.getoption("--runslow"):
MenderTesting.slow_cond = True
else:
MenderTesting.slow_cond = False
if pytest.config.getoption("--runfa... | Fix no tests running when not passing any options. | Fix no tests running when not passing any options.
Signed-off-by: Kristian Amlie <505e66ae45028a0596c853559221f0b72c1cee21@mender.io>
| Python | apache-2.0 | pasinskim/integration,GregorioDiStefano/integration,pasinskim/integration,GregorioDiStefano/integration,pasinskim/integration |
4585c5d0a69b190f55486a2cfb94a5c361bd4365 | tests/pytests/functional/states/test_npm.py | tests/pytests/functional/states/test_npm.py | import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.pkg.install("npm")
except CommandExecutionError:
pytest.skip("Unable to install npm")
@pytest.mark.slow_test
@pytest.mark.destructive... | import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.pkg.install("npm")
# Just name the thing we're looking for
sminion.functions.npm # pylint: disable=pointless-statement
except ... | Check npm name as well | Check npm name as well
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
a16cffb7c3fe100e5e68a71e2dfcca26bf124464 | prime-factors/prime_factors.py | prime-factors/prime_factors.py | # File: prime_factors.py
# Purpose: Compute the prime factors of a given natural number.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Monday 26 September 2016, 12:05 AM
def prime_factors(number, n=2, factors=None):
if factors is None:
factors = []
for num in range(n, num... | # File: prime_factors.py
# Purpose: Compute the prime factors of a given natural number.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Monday 26 September 2016, 12:05 AM
def prime_factors(number):
num = 2
factors = []
while num <= number:
if (number % ... | Change if condition to while with reformat | Change if condition to while with reformat
| Python | mit | amalshehu/exercism-python |
7619513d29c5f7ae886963ced70315d42dbd1a9b | ogbot/core/researcher.py | ogbot/core/researcher.py | from base import BaseBot
from scraping import research, general
class ResearcherBot(BaseBot):
def __init__(self, browser, config, planets):
self.research_client = research.Research(browser, config)
self.general_client = general.General(browser, config)
self.planets = planets
supe... | from base import BaseBot
from scraping import research, general
class ResearcherBot(BaseBot):
def __init__(self, browser, config, planets):
self.research_client = research.Research(browser, config)
self.general_client = general.General(browser, config)
self.planets = planets
supe... | Add logging if no research available | Add logging if no research available
| Python | mit | yosh778/OG-Bot,yosh778/OG-Bot,yosh778/OG-Bot,winiciuscota/OG-Bot |
b8792d9164f669133032eb26ab78281acb17c9c5 | appengine/standard/conftest.py | appengine/standard/conftest.py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Fix lint issue and review comments | Fix lint issue and review comments
Change-Id: I02a53961b6411247ef06d84dad7b533cb97d89f7
| Python | apache-2.0 | canglade/NLP,hashems/Mobile-Cloud-Development-Projects,sharbison3/python-docs-samples,JavaRabbit/CS496_capstone,GoogleCloudPlatform/python-docs-samples,sharbison3/python-docs-samples,sharbison3/python-docs-samples,sharbison3/python-docs-samples,hashems/Mobile-Cloud-Development-Projects,JavaRabbit/CS496_capstone,Brandon... |
e921df4218053b1afe2a60262516873e96ac2679 | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import she... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import she... | Use tools/tsan.supp for TSAN suppressions. | Use tools/tsan.supp for TSAN suppressions.
BUG=skia:
R=borenet@google.com, mtklein@google.com
Author: mtklein@chromium.org
Review URL: https://codereview.chromium.org/266393003
| Python | bsd-3-clause | Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Ti... |
a3f9b4d7a82335cadaba09167a6ac873733646fa | lambda_function.py | lambda_function.py | #!/usr/bin/env python2
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def lambda_handler(event=None, context=None):
users = get_users()
csvo = StringIO()
write_contacts_csv(users, csvo)
... | #!/usr/bin/env python2
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def lambda_handler(event=None, context=None):
users = get_users()
csvo = StringIO()
write_contacts_csv(users, csvo)
... | Add main routine to lambda handler | Add main routine to lambda handler
| Python | apache-2.0 | ajorg/DMR_contacts |
b7a80f92b4e2e7227efe5712e512f5a75bc4e67c | locales/seattle/librenms.py | locales/seattle/librenms.py | #!/usr/bin/env python
import json
import urllib2
librenms = json.loads(
urllib2.urlopen(urllib2.Request(
'https://librenms.hamwan.org/api/v0/devices',
headers={'X-Auth-Token': '600dc6857a6e2bf200b46e56b78c0049'},
)).read()
)
inventory = {
"_meta": {
"hostvars": {}
}
}
for ke... | #!/usr/bin/env python
import json
import urllib2
librenms = json.loads(
urllib2.urlopen(urllib2.Request(
'https://librenms.hamwan.org/api/v0/devices',
headers={'X-Auth-Token': '600dc6857a6e2bf200b46e56b78c0049'},
)).read()
)
inventory = {
"_meta": {
"hostvars": {}
},
"all... | Add seattle group to LibreNMS dynamic inventory to trigger seattle group vars. | Add seattle group to LibreNMS dynamic inventory to trigger seattle group vars.
| Python | apache-2.0 | HamWAN/infrastructure-configs,HamWAN/infrastructure-configs,HamWAN/infrastructure-configs |
46b8a4d0668c764df85f1e8a94672d81dd112beb | maps/api/views.py | maps/api/views.py | from django.http import HttpResponse
def list_question_sets(request):
return HttpResponse('Lol, udachi')
| import json
from django.http import HttpResponse
from maps.models import QuestionSet
def list_question_sets(request):
objects = QuestionSet.objects.all()
items = []
for obj in objects:
items.append({
'title': obj.title,
'max_duration': obj.max_duration.seconds,
... | Add API method for question sets list | Add API method for question sets list
| Python | mit | sevazhidkov/greenland,sevazhidkov/greenland |
3152ee5ca2f21708e428faac5eaadbb403d0a1dc | spacy/tests/serialize/test_serialize_tokenizer.py | spacy/tests/serialize/test_serialize_tokenizer.py | # coding: utf-8
from __future__ import unicode_literals
from ..util import make_tempdir
import pytest
@pytest.mark.parametrize('text', ["I can't do this"])
def test_serialize_tokenizer_roundtrip_bytes(en_tokenizer, text):
tokenizer_b = en_tokenizer.to_bytes()
new_tokenizer = en_tokenizer.from_bytes(tokenize... | # coding: utf-8
from __future__ import unicode_literals
from ...util import get_lang_class
from ..util import make_tempdir, assert_packed_msg_equal
import pytest
def load_tokenizer(b):
tok = get_lang_class('en').Defaults.create_tokenizer()
tok.from_bytes(b)
return tok
@pytest.mark.parametrize('text', ... | Update serialization tests for tokenizer | Update serialization tests for tokenizer
| Python | mit | honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaC... |
f8290954b27e655562878d16df7e4793262f50d7 | wafer/tickets/management/commands/import_quicket_guest_list.py | wafer/tickets/management/commands/import_quicket_guest_list.py | import csv
from django.core.management.base import BaseCommand, CommandError
from wafer.tickets.views import import_ticket
class Command(BaseCommand):
args = '<csv file>'
help = "Import a guest list CSV from Quicket"
def handle(self, *args, **options):
if len(args) != 1:
raise Comma... | import csv
from django.core.management.base import BaseCommand, CommandError
from wafer.tickets.views import import_ticket
class Command(BaseCommand):
args = '<csv file>'
help = "Import a guest list CSV from Quicket"
def handle(self, *args, **options):
if len(args) != 1:
raise Comma... | Check CSV header, not column count (and refactor) | Check CSV header, not column count (and refactor)
| Python | isc | CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
4a8dbde660361a53a3206097bff9ae95b0edfec7 | alg_strongly_connected_graph.py | alg_strongly_connected_graph.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dfs_recur():
pass
def traverse_dfs_recur():
pass
def transpose_graph():
pass
def strongly_connected_graph():
"""Find strongly connected graphs by Kosaraju's Algorithm."""
def main():
adjace... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def dfs_recur():
pass
def traverse_dfs_recur():
pass
def transpose_graph():
pass
def strongly_connected_graph():
"""Find strongly connected graphs by Kosaraju's Algorithm."""
def main():
# 3 stron... | Add comment for strongly connected graphs | Add comment for strongly connected graphs
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
14d0669f54b1207d8764a97bd4a73e1d4c45f679 | sep/sep_search_result.py | sep/sep_search_result.py | from lxml import html
import re
import requests
from constants import SEP_URL
class SEPSearchResult():
query = None
results = None
def __init__(self, query):
self.set_query(query)
def set_query(self, query):
self.query = str(query).lower().split()
@property
def url(self):
... | from lxml import html
import re
import requests
from constants import SEP_URL
class SEPSearchResult():
query = None
results = None
def __init__(self, query):
self.set_query(query)
def set_query(self, query):
pattern = re.compile('[^a-zA-Z\d\s]')
stripped_query = re.sub(patte... | Use regex to remove non alphanumerics from post titles | New: Use regex to remove non alphanumerics from post titles
| Python | mit | AFFogarty/SEP-Bot,AFFogarty/SEP-Bot |
9c91cdeaed24ab994924b9a5485b6cc3feb9dfc0 | tutorials/models.py | tutorials/models.py | from django.db import models
# Create your models here.
class Tutorial(models.Model):
title = models.TextField()
html = models.TextField()
markdown = models.TextField() | from django.db import models
from markdownx.models import MarkdownxField
# Create your models here.
class Tutorial(models.Model):
# ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ??
# Category = models.TextField()
title = models.TextField()
html = models.TextFie... | Add missing Fields according to mockup, Add markdownfield | Add missing Fields according to mockup, Add markdownfield
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
44e9e06c7db64682340505754af0b69b99cae305 | diceware.py | diceware.py | #!/usr/bin/env python
import random
def read_list(filename):
words = []
with open(filename, "r") as wordfile:
started = False
for line in wordfile:
if not started and line == "\n":
started = True
elif started:
if line == "\n":
... | #!/usr/bin/env python
import random
def read_list(filename):
words = []
with open(filename, "r") as wordfile:
started = False
for line in wordfile:
if not started and line == "\n":
started = True
elif started:
if line == "\n":
... | Use SystemRandom to access urandom where available | Use SystemRandom to access urandom where available
| Python | mit | davb5/pydiceware |
5081734e07497e26834485891d634a7f3ac7ef28 | pies/collections.py | pies/collections.py | from __future__ import absolute_import
from collections import *
from .version_info import PY2
if PY2:
from UserString import *
from UserList import *
from ordereddict import OrderedDict
| from __future__ import absolute_import
from collections import *
from .version_info import PY2
if PY2:
from UserString import *
from UserList import *
import sys
if sys.version_info < (2, 7):
from ordereddict import OrderedDict
| Fix import of ordered dict on python 2.7 | Fix import of ordered dict on python 2.7
| Python | mit | AbsoluteMSTR/pies,timothycrosley/pies,lisongmin/pies,AbsoluteMSTR/pies,lisongmin/pies,timothycrosley/pies |
fca148d85b0deb16c988473ddab651529653e9de | cheroot/__init__.py | cheroot/__init__.py | """High-performance, pure-Python HTTP server used by CherryPy."""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
try:
import pkg_resources
except ImportError:
pass
try:
__version__ = pkg_resources.get_distribution('cheroot').version
except Exception:
__version_... | """High-performance, pure-Python HTTP server used by CherryPy."""
try:
import pkg_resources
except ImportError:
pass
try:
__version__ = pkg_resources.get_distribution('cheroot').version
except Exception:
__version__ = 'unknown'
| Remove compatibility code from cheroot | Remove compatibility code from cheroot
| Python | bsd-3-clause | cherrypy/cheroot |
1a93c58e278712a2c52f36b098a570a7f48c7ef2 | taOonja/game/views.py | taOonja/game/views.py | from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from game.models import *
class LocationListView(ListView):
template_name = 'game/location_list.html'
context_object_name = 'location_list'
def get_queryset(self):
... | from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from game.models import Location
class LocationListView(ListView):
template_name = 'game/location_list.html'
context_object_name = 'location_list'
def get_queryset(self):
... | Change View According to model Changes | Change View According to model Changes
| Python | mit | Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja |
99880b935c939ab7128a788cc09cd759f3d397b2 | src/passgen.py | src/passgen.py | import string
import random
def passgen(length=8):
"""Generate a strong password with *length* characters"""
pool = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.SystemRandom().choice(pool) for _ in range(length))
def main():
for _ in range(10):
print ... | import string
import random
import argparse
def passgen(length=8):
"""Generate a strong password with *length* characters"""
pool = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.SystemRandom().choice(pool) for _ in range(length))
def main():
parser = argparse.... | Add length argument to the main script | Add length argument to the main script
| Python | mit | soslan/passgen |
0053cba05e19f640b5d30d02a130f6c994f68f8e | speedcenter/codespeed/admin.py | speedcenter/codespeed/admin.py | # -*- coding: utf-8 -*-
from codespeed.models import Project, Revision, Executable, Benchmark, Result, Environment
from django.contrib import admin
class ProjectAdmin(admin.ModelAdmin):
list_display = ('name', 'repo_type', 'repo_path', 'track')
admin.site.register(Project, ProjectAdmin)
class RevisionAdmin(a... | # -*- coding: utf-8 -*-
from codespeed.models import Project, Revision, Executable, Benchmark, Result, Environment
from django.contrib import admin
class ProjectAdmin(admin.ModelAdmin):
list_display = ('name', 'repo_type', 'repo_path', 'track')
admin.site.register(Project, ProjectAdmin)
class RevisionAdmin(a... | Order Benchmark by name in the Admin | Order Benchmark by name in the Admin
| Python | lgpl-2.1 | cykl/codespeed,alex/codespeed,nomeata/codespeed,alex/codespeed,cykl/codespeed,nomeata/codespeed |
4ace9edb7432b5c0de677924301477ce86480486 | common/safeprint.py | common/safeprint.py | import multiprocessing, sys
from datetime import datetime
from common import settings
print_lock = multiprocessing.RLock()
def safeprint(msg, verbosity=0):
"""Prints in a thread-lock, taking a single object as an argument"""
string = ("[" + str(multiprocessing.current_process().pid) + "] " +
da... | import multiprocessing, sys
from datetime import datetime
from common import settings
print_lock = multiprocessing.RLock()
max_digits = 0
def safeprint(msg, verbosity=0):
"""Prints in a thread-lock, taking a single object as an argument"""
pid = str(multiprocessing.current_process().pid)
max_digits = max(... | Make thread marker consistent length | Make thread marker consistent length | Python | mit | gappleto97/Senior-Project |
ac8dbe8f70061906035ea24ae6bae91f0432dca8 | astropy/utils/setup_package.py | astropy/utils/setup_package.py | from distutils.core import Extension
from os.path import dirname, join
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[join(ROOT, 'src', 'compiler.c')])
]
| from distutils.core import Extension
from os.path import dirname, join, relpath
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[relpath(join(ROOT, 'src', 'compiler.c'))])
]
| Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes can... | Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes c... | Python | bsd-3-clause | MSeifert04/astropy,pllim/astropy,funbaker/astropy,stargaser/astropy,lpsinger/astropy,DougBurke/astropy,larrybradley/astropy,AustereCuriosity/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,tbabej/astropy,DougBurke/astropy,kelle/astropy,AustereCuriosity/astropy,saimn/astropy,mhvk/astropy,bsipocz/astropy,funbaker/ast... |
bab9464394c91f63786c50080292347339aa122a | bonemapy_version.py | bonemapy_version.py |
__version__ = '0.2.2' | # -*- coding: utf-8 -*-
# Copyright (C) 2013 Michael Hogg
# This file is part of bonemapy - See LICENSE.txt for information on usage and redistribution
__version__ = '0.2.2' | Add license + redist info to version file | Add license + redist info to version file
| Python | mit | mhogg/bonemapy |
6d816ac65cd26601440876295cf70955f172d6d0 | organizer/models.py | organizer/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | Add options to Startup model fields. | Ch03: Add options to Startup model fields. [skip ci]
Field options allow us to easily customize behavior of a field.
Global Field Options:
https://docs.djangoproject.com/en/1.8/ref/models/fields/#db-index
https://docs.djangoproject.com/en/1.8/ref/models/fields/#help-text
https://docs.djangoproject.com/en... | Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
58eb2f88821f7284c744838725351ddff67dd7f4 | website/views.py | website/views.py | from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_gr... | from django.template import RequestContext
from website.models import Restaurant, OpenTime, BaseModel
from website.api import export_data
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
import hashlib
import json
def restaurant_gr... | Add pretty printing for API | Add pretty printing for API
| Python | apache-2.0 | srct/whats-open,srct/whats-open,srct/whats-open |
50783ead4aab7dc2ea32b0045ff12a0bacf2b21d | challenge/models.py | challenge/models.py | from datetime import datetime, timedelta
from django.db import models
CHALLENGE_STATUS_CHOICES = (
('NW', 'New'),
('IP', 'In Progress'),
('CP', 'Completed'),
)
class Challenge(models.Model):
title = models.CharField('Challenge Title', max_length = 200)
starts = models.DateTimeField('Start Date', d... | from datetime import datetime, timedelta
from django.db import models
from django.core.urlresolvers import reverse
CHALLENGE_STATUS_CHOICES = (
('NW', 'New'),
('IP', 'In Progress'),
('CP', 'Completed'),
)
class Challenge(models.Model):
title = models.CharField('Challenge Title', max_length = 200)
... | Use reverse() instead of a hardcoded url for Challenge | Use reverse() instead of a hardcoded url for Challenge
Instead of hardcoding the url in Challenge.get_absolute_url(), use
reverse().
Signed-off-by: Sebastian Nowicki <72cef2e23c539c1a2a17e6651ec7265f998b0d23@gmail.com>
| Python | bsd-3-clause | wraithan/archcode |
b149e2089ee819f59e920f8c295c623dce813ab7 | was/photo/urls.py | was/photo/urls.py | from django.conf.urls import url
from .views import (upload_photo_artist, delete_photo_artist,
AlbumListView, CreateAlbumView)
urlpatterns = [
url(r'^upload/?$', upload_photo_artist, name='upload_photo_artist'),
url(r'^(?P<photo_id>\d+)/delete/$', delete_photo_artist, name='delete_photo_ar... | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from .views import (upload_photo_artist, delete_photo_artist,
AlbumListView, CreateAlbumView)
urlpatterns = [
url(r'^upload/?$', upload_photo_artist, name='upload_photo_artist'),
url(r'^(?P<photo_id>... | Add login requirement on create album view | Add login requirement on create album view
| Python | mit | KeserOner/where-artists-share,KeserOner/where-artists-share |
f3875956cda23c4b0086dbc083161dc6f2c1a771 | spicedham/split_tokenizer.py | spicedham/split_tokenizer.py | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
is_not_blan... | from re import split
from spicedham.tokenizer import BaseTokenizer
class SplitTokenizer(BaseTokenizer):
"""
Split the text on punctuation and newlines, lowercase everything, and
filter the empty strings
"""
def tokenize(self, text):
text = split('[ ,.?!\n\r]', text)
text = [tok... | Make mapping & filtering into a list comprehension | Make mapping & filtering into a list comprehension
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
1f90a3d733de99cc9c412cdd559ed3ad26519acc | autoencoder/api.py | autoencoder/api.py | from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=c... | from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None, reduced=False,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=... | Add reduce option to API | Add reduce option to API
| Python | apache-2.0 | theislab/dca,theislab/dca,theislab/dca |
679f20fc8747020f08f1e18a47772b18d886d29f | circuit/_twisted.py | circuit/_twisted.py | # Copyright 2012 Edgeware AB.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2012 Edgeware AB.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Remove print statements from TwistedCircuitBreaker | Remove print statements from TwistedCircuitBreaker | Python | apache-2.0 | edgeware/python-circuit |
ec72bfd00fdb81415efac782d224b17e534849c4 | mfh.py | mfh.py | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfhclient_pro... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfh... | Add condition to only launch server if -s or --server is specified | Add condition to only launch server if -s or --server is specified
Now you can launch client, server or updater on its own, launch
nothing, or launch the whole thing altogether!
| Python | mit | Zloool/manyfaced-honeypot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.