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 |
|---|---|---|---|---|---|---|---|---|---|
b8359e6b04d13f550aec308308f2e91e194bc372 | uberlogs/handlers/kill_process.py | uberlogs/handlers/kill_process.py | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | Remove repetitive getMessage calls in KillProcesshandler | Remove repetitive getMessage calls in KillProcesshandler
| Python | mit | odedlaz/uberlogs,odedlaz/uberlogs |
be5eecf2a043abf7585022f1dda3b79572eba192 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_ndmeasure._pycompat
def test_irange():
r = dask_ndmeasure._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| Add a basic test for irange | Add a basic test for irange
Make sure `irange` is there, it doesn't return a list, and it acts like
`range` on some test arguments.
| Python | bsd-3-clause | dask-image/dask-ndmeasure |
e90a60b1da00a6c6a5e1b4235c4009d7477986ca | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | Copy find modules to root of module path | conan: Copy find modules to root of module path
| Python | mit | polysquare/cppcheck-target-cmake |
59afb96f2211983ee2a2786c60791074b13c3e7f | ni/__main__.py | ni/__main__.py | """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records:... | """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records:... | Tweak comment about 202 response | Tweak comment about 202 response
| Python | apache-2.0 | python/the-knights-who-say-ni,python/the-knights-who-say-ni |
9cfe03ab06f126406a51c0945e990fc849d8dfb9 | scripts/crontab/gen-crons.py | scripts/crontab/gen-crons.py | #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
... | #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
... | Add local site-packages to PYTHONPATH. | Add local site-packages to PYTHONPATH.
To pick up the local version of PyOpenSSL.
| Python | bsd-3-clause | philipp-sumo/kitsune,iDTLabssl/kitsune,orvi2014/kitsune,silentbob73/kitsune,NewPresident1/kitsune,MziRintu/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,YOTOV-LIMITED/kitsune,safwanrahman/kitsune,silentbob73/kitsune,safwanrahman/linuxdesh,mythmon/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune... |
cac3099b9ab07d5ac2180e0b2796f55668ddda1e | generate_keyczart.py | generate_keyczart.py | import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.listdir(directory):
os.makedirs(directory)
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczart.main(['addkey','--location=keyset'... | import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.path.exists(directory):
os.makedirs(directory)
if not os.listdir(directory):
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczar... | Make the directory if it doesn't exist | Make the directory if it doesn't exist
| Python | apache-2.0 | arubdesu/Crypt-Server,arubdesu/Crypt-Server,arubdesu/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server |
9d0798904160f86d7f580dde3bfba8cc28b5a23f | troposphere/ram.py | troposphere/ram.py | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare(AWSObject):
resource_type = "AWS::RAM::ResourceShare"
props = {
"AllowExternalP... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.3.0
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare... | Update RAM per 2021-06-10 changes | Update RAM per 2021-06-10 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
eb4456b752313383a573bacfc102db9149ee1854 | django_transfer/urls.py | django_transfer/urls.py | from __future__ import unicode_literals
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'',
url(r'^download/.*$', 'django_transfer.views.download', name='download'),
url(r'^upload/$', 'django_transfer.... | from __future__ import unicode_literals
try:
from django.conf.urls import url
def patterns(*args):
return args
except ImportError:
from django.conf.urls.defaults import patterns, url
from django_transfer.views import download, upload
urlpatterns = patterns(
url(r'^download/.*$', download, ... | Fix URL patterns for different Django versions. | Fix URL patterns for different Django versions.
| Python | mit | smartfile/django-transfer |
4cff7dd08fdb345b6e091570a2ca5500ef871318 | flask_authorization_panda/basic_auth.py | flask_authorization_panda/basic_auth.py | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, Response, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
di... | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, jsonify, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
dic... | Remove use of assert statements since this does not conform to general best practice. | Remove use of assert statements since this does not conform to general best practice.
This is unfortunate, because the code is much more verbose than before and NOT as clear.
| Python | mit | eikonomega/flask-authorization-panda |
e33a2879fbafe36c8c29d48042dad8277b068e91 | umap/tests/test_plot.py | umap/tests/test_plot.py | from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at... | from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at... | Add more basic plotting tests | Add more basic plotting tests
| Python | bsd-3-clause | lmcinnes/umap,lmcinnes/umap |
bf23c87c7606cbcf8afcd2c5120c25ede92675c0 | irc/functools.py | irc/functools.py | from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, we save the args and
kwargs with which it was called.
>>> class MyClass(object):
... @save_method_args
... | from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass(object):
... @save_method_args
... d... | Update docstring and expand doctests. | Update docstring and expand doctests.
| Python | mit | jaraco/irc |
dfc7d629956f708cf5b69e464fe3a7298ffb6cfa | BotHandler.py | BotHandler.py | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_w... | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_w... | Print a quit message when shutting down a bot | Print a quit message when shutting down a bot
| Python | mit | HubbeKing/Hubbot_Twisted |
982f4af638e83ee49c87a0dffad2b47daf872749 | workers/data_refinery_workers/downloaders/test_utils.py | workers/data_refinery_workers/downloaders/test_utils.py | import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an ... | import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
@tag('downloaders')
def test_no_jobs_to_create(self):
"""Make sure this fu... | Add tag to downloaders test so it is actually run. | Add tag to downloaders test so it is actually run.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery |
813970150109450e53be44715913e5fb3c680c77 | uscampgrounds/models.py | uscampgrounds/models.py | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... | Include an override to the default manager to allow geospatial querying. | Include an override to the default manager to allow geospatial querying.
| Python | bsd-3-clause | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds |
f0dd6411458a19985408404d511584f7c7e26e38 | useful/tests/tasks/call_management_command.py | useful/tests/tasks/call_management_command.py | from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_management_command(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'S... | from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_success(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
... | Add failed management command test | Add failed management command test
| Python | isc | yprez/django-useful,yprez/django-useful |
bfa98f350a3da827da8359a4e6e7373fc11626cd | changeling/models.py | changeling/models.py | import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
},
'additionalProperties': False,
}
def __init__(self, id=None, nam... | import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
'description': {'type': 'string'},
},
'additionalProperties': Fa... | Add description attr to Change | Add description attr to Change
| Python | apache-2.0 | bcwaldon/changeling,bcwaldon/changeling |
46ab04db26f6330e732abdf4284242bd83179684 | lametro/management/commands/refresh_guid.py | lametro/management/commands/refresh_guid.py | from django.core.management.base import BaseCommand
from django.conf import settings
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = LegistarAPIBillScraper()
scraper.BASE_UR... | from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import IntegrityError
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = Legi... | Update API path, handle updated SubjectGuid | Update API path, handle updated SubjectGuid
| Python | mit | datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic |
7798d5d8c625a4cbdb689cb7ffa38c2f90c0dc02 | dduplicated/fileManager.py | dduplicated/fileManager.py | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | Fix in error when analyze directories without duplicates | Fix in error when analyze directories without duplicates
| Python | mit | messiasthi/dduplicated-cli |
63935d3c62dad19d2668d0e0633ebd4ce6e6ed26 | actions/kvstore.py | actions/kvstore.py | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | Fix create action for key value pair | Fix create action for key value pair
| Python | apache-2.0 | StackStorm/st2cd,StackStorm/st2cd |
c18f21995ff76681fdfa7e511019f5f27bfea749 | playserver/trackchecker.py | playserver/trackchecker.py | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | Send data in trackChecker callbacks | Send data in trackChecker callbacks
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver |
51080ad6e8ad38ea8c22593b07d70b27965545bd | api/views/users.py | api/views/users.py | from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset =... | from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset =... | Make signup not require token in API | Make signup not require token in API
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq |
7c60024684024b604eb19a02d119adab547ed0d1 | ovp_organizations/migrations/0023_auto_20170627_0236.py | ovp_organizations/migrations/0023_auto_20170627_0236.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
]
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
('o... | Add ovp_core_0011 migration as dependency for ovp_organizations_0023 | Add ovp_core_0011 migration as dependency for ovp_organizations_0023
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations |
b2f40d9b1ed9d78a4fdc1f73e64575a26d117d0c | nuitka/tools/release/msi_create/__main__.py | nuitka/tools/release/msi_create/__main__.py | # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | Copy created MSI to dedicated folder. | Release: Copy created MSI to dedicated folder.
* The "dist" folder is erased each time and we determine the result
name from being the only MSI file.
| Python | apache-2.0 | kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka |
beb8f12e4a8290d4107cdb91a321a6618a038ef9 | rose_trellis/util.py | rose_trellis/util.py | from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.... | from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.... | Make easy_run better by taking the generator from coroutines | Make easy_run better by taking the generator from coroutines
| Python | mit | dmwyatt/rose_trellis |
2c15d96a7d77269fbe41e5b2940873fc849d411a | random_projection.py | random_projection.py | """
Random projection, Assignment 1c
"""
| """
Random projection, Assignment 1c
"""
import numpy as np
import matplotlib.pylab as plt
import random, mnist_dataloader
from numpy import dtype
"""
Generate random projection matrix R
@param: k, the reduced number of dimensions
@param: d, the original number of dimensions
@return: R, the generated random projection... | Add random projection matrix generation and random projection. | Add random projection matrix generation and random projection.
| Python | mit | lidalei/DataMining |
5596f599287d36126b3a6e30e7579eb00ed07d73 | downstream_farmer/utils.py | downstream_farmer/utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to k... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to keep
th... | Fix method to use quote, not quote_plus | Fix method to use quote, not quote_plus
| Python | mit | Storj/downstream-farmer |
f842cf7605018e85b13f27f3a0886122e4cbb80c | expert_tourist/views.py | expert_tourist/views.py | from collections import namedtuple
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected... | from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt... | Return the whole user in successful login | Return the whole user in successful login
| Python | mit | richin13/expert-tourist |
01a9b6457d78dd583637bf8174edda40e2bd3276 | django_website/blog/feeds.py | django_website/blog/feeds.py | from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self)... | from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self)... | Add author name and body to the weblog RSS feed. | Add author name and body to the weblog RSS feed.
| Python | bsd-3-clause | alawnchen/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,khkaminska/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,rmoorman/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,xavierdutreilh/djangoproj... |
5adb6de6b926a54dc9a6dd334a34d42dd2044481 | src/pushover_complete/pushover_api.py | src/pushover_complete/pushover_api.py | import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound... | import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound... | Split send_message out in to _send_message to reuse functionality later | Split send_message out in to _send_message to reuse functionality later
| Python | mit | scolby33/pushover_complete |
f87b8c5b94e3e163f19ea0414d1fb2c42f09c166 | test/test_genmidi.py | test/test_genmidi.py | import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInst... | import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInst... | Test for sequence of chords | Test for sequence of chords
| Python | mit | palmerev/pyknon,kroger/pyknon |
86cf16611fe4126f4345477b24da5c15fed4c1e8 | eval_kernel/eval_kernel.py | eval_kernel/eval_kernel.py | from __future__ import print_function
from jupyter_kernel import MagicKernel
import os
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
... | from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
... | Update eval kernel to use python magic. | Update eval kernel to use python magic.
| Python | bsd-3-clause | Calysto/metakernel |
b0b4bad0ca68ebd1927229e85e7116fb63126c65 | src/olympia/zadmin/helpers.py | src/olympia/zadmin/helpers.py | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
... | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
... | Remove generate error page from admin site | Remove generate error page from admin site
| Python | bsd-3-clause | bqbn/addons-server,wagnerand/olympia,harry-7/addons-server,wagnerand/addons-server,harikishen/addons-server,psiinon/addons-server,lavish205/olympia,mstriemer/addons-server,kumar303/addons-server,Prashant-Surya/addons-server,mstriemer/olympia,mozilla/addons-server,harikishen/addons-server,Revanth47/addons-server,mstriem... |
be964b02036159567efcaecce5b5d905f23985af | deduper/scanfiles.py | deduper/scanfiles.py | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to... | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to... | Check that fullpath is a regular file before continuing | Check that fullpath is a regular file before continuing
| Python | bsd-3-clause | cgspeck/filededuper |
a95e891b637f0182031f229465bcded966100889 | readthedocs/core/models.py | readthedocs/core/models.py | from django.db import models
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(User, unique=True, related_name='profile')
whitelisted = models.BooleanField()
... | from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(U... | Add post save signal for user creation | Add post save signal for user creation
| Python | mit | safwanrahman/readthedocs.org,raven47git/readthedocs.org,sunnyzwh/readthedocs.org,agjohnson/readthedocs.org,d0ugal/readthedocs.org,GovReady/readthedocs.org,kenshinthebattosai/readthedocs.org,jerel/readthedocs.org,jerel/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,titiushko/readthedocs.org,wijerasa/rea... |
bf6565d3bf3c2345a7187d07585bdbf08db06f61 | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
si... | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
si... | Add loggedin keyword to adzerk Ads. | Add loggedin keyword to adzerk Ads.
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk |
ad17f4a48bdee7ca57e8fe66e4658821b3c8789e | corehq/apps/userreports/migrations/0018_ucrexpression.py | corehq/apps/userreports/migrations/0018_ucrexpression.py | # Generated by Django 2.2.27 on 2022-04-12 10:28
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name=... | # Generated by Django 3.2.12 on 2022-04-12 15:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name='UCRExpression',
fields=[
... | Use django 3 to make migration | Use django 3 to make migration
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
7ee5692a98a6dfc714a05f1add8e72b09c52929e | students/psbriant/final_project/clean_data.py | students/psbriant/final_project/clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
# print(data["Date Text"].head(... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dat... | Add code to split month and year into new columns. | Add code to split month and year into new columns.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 |
d52a7b19f7b5596e88d7233dfea35a70b2645385 | osmaxx-py/excerptconverter/converter_manager.py | osmaxx-py/excerptconverter/converter_manager.py | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
export_options = {}
for Converter in BaseExcerptConverter.available_converters:
export_options[Converter.__name__] = Converter.converter_confi... | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
return {Converter.__name__: Converter.converter_configuration()
for Converter in BaseExcerptConverter.available_converters}
def __init__(self... | Replace loop by dictionary comprehension | Refactoring: Replace loop by dictionary comprehension
| Python | mit | geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend |
f5d864c2a5c9b4d2ea1ff95e59d60adf2ebd176e | recipes/sos-bash/run_test.py | recipes/sos-bash/run_test.py | import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
@unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32')
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as k... | import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as kc:
execute(kc=kc, code='a = 1')
stdout, stderr = a... | Test does not have to fail under windows | Test does not have to fail under windows
| Python | bsd-3-clause | birdsarah/staged-recipes,synapticarbors/staged-recipes,SylvainCorlay/staged-recipes,kwilcox/staged-recipes,johanneskoester/staged-recipes,synapticarbors/staged-recipes,asmeurer/staged-recipes,SylvainCorlay/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,hadim/staged-recipes,had... |
c7bc130efaaba1e079bc8a0f39f37ef3c2534413 | Yank/tests/test_utils.py | Yank/tests/test_utils.py | #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#====... | #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#====... | Add more informative error message for yank options assertion test. | Add more informative error message for yank options assertion test.
| Python | mit | andrrizzi/yank,andrrizzi/yank,choderalab/yank,andrrizzi/yank,choderalab/yank |
81dc92b3c2875b6775d33321b1bcd9f994be8a10 | txircd/modules/extra/snotice_remoteconnect.py | txircd/modules/extra/snotice_remoteconnect.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
re... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
re... | Fix checking a name against an object | Fix checking a name against an object
| Python | bsd-3-clause | Heufneutje/txircd |
8ecf97b338dd37eaf5a4e2672e33e27cc40d215d | sacred/observers/__init__.py | sacred/observers/__init__.py | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observer... | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observer... | Add TinyDbReader to observers init | Add TinyDbReader to observers init
| Python | mit | IDSIA/sacred,IDSIA/sacred |
04fec1c50ac81c1b80c22f37bd43845a0e08c1a3 | fancypages/assets/models.py | fancypages/assets/models.py | from django.db import models
from django.utils.translation import ugettext as _
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now... | from django.db import models
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=... | Add support for custom user model (Django 1.5+) | Add support for custom user model (Django 1.5+)
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages |
7629afde2627457b4f4b19e1542a87e695c1837d | tests/events/test_models.py | tests/events/test_models.py | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | Make sure slug gets updated on date change | Make sure slug gets updated on date change
| Python | mit | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx |
8209b77a16c899436418dbc85dc891f671949bfc | bot/logger/message_sender/asynchronous.py | bot/logger/message_sender/asynchronous.py | from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sende... | from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sende... | Clarify work action in AsynchronousMessageSender | Clarify work action in AsynchronousMessageSender
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
5f6fb5866ca74793b05308ac27c4698033068cfe | tvtk/tests/test_garbage_collection.py | tvtk/tests/test_garbage_collection.py | """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from t... | """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.tvtk_scene import TVTKScene
from tvtk.pyface.scene import Scene
from tvt... | Test TVTKScene garbage collection and renaming | Test TVTKScene garbage collection and renaming
| Python | bsd-3-clause | alexandreleroux/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi,dmsurti/mayavi,dmsurti/mayavi |
6af828b3f541adf0c42e73d76d7998bc21a072cb | sample_proj/polls/filters.py | sample_proj/polls/filters.py | from datafilters.filterform import FilterForm
from datafilters.specs import (GenericSpec, DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = GenericSpec('choice__votes')
has_choice_with_votes = GreaterThanZero... | from datafilters.filterform import FilterForm
from datafilters.filterspec import FilterSpec
from datafilters.specs import (DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = FilterSpec('choice__votes')
has_cho... | Use FilterSpec instead of GenericSpec in sample_proj | Use FilterSpec instead of GenericSpec in sample_proj
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters |
d611eb18b234c7d85371d38d8c875aaae447c231 | testing/urls.py | testing/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.views.generic import View
urlpatterns = patterns('',
url(r'foo$', View.as_view(), name="foo"),
)
| # -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import View
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
| Fix tests remove unneccessary imports | Fix tests remove unneccessary imports
| Python | bsd-3-clause | niwinz/django-sites,niwinz/django-sites |
af2b561cd1a25fc4abd7c7948e5ff8ceb507a497 | tests/cli/test_rasa_shell.py | tests/cli/test_rasa_shell.py | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN... | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_... | Adjust rasa shell help test to changes. | Adjust rasa shell help test to changes.
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu |
43ca4bf6a9c30055385519bb4c4472a530cce4dd | site_scons/site_tools/build_and_compress.py | site_scons/site_tools/build_and_compress.py | def build_and_compress(env, source, target):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
d... | def build_and_compress(env, target, source):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
d... | Fix argument order in BuildAndCompress pseudo-builder | Fix argument order in BuildAndCompress pseudo-builder
| Python | mit | robobrobro/terminus |
cc7da0c83a27e42619f0d800b11ef7bf7f82e4bb | setup.py | setup.py | from distutils.core import setup
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = '0.3.0',
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/... | from distutils.core import setup
VERSION='0.3.1'
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'h... | Include LICENSE.txt in the package tarball | Include LICENSE.txt in the package tarball
| Python | mit | bb4242/sdnotify |
1fd8ea9c746bc1c3fa0dc95a3b00244f97373976 | setup.py | setup.py | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | Remove download URL since Github doesn't get his act together. Damnit | Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <48255722c72bb2e7f7bec0fff5f60dc7fb5357fb@12edf5ea-513a-0410-8a8c-37067077e60f>
| Python | bsd-3-clause | Jythoner/django-robots,Jythoner/django-robots |
f4fb4e90725cec378634c22ee8803eeb29ccf143 | conveyor/processor.py | conveyor/processor.py | from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(sel... | from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(sel... | Switch from returning a set to returning a list | Switch from returning a set to returning a list
| Python | bsd-2-clause | crateio/carrier |
22ab7f94c3b8b04a50cd11e73b2963bddb0470a5 | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings... | Fix migrations - drop old domain | Fix migrations - drop old domain
| Python | mit | rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia |
73feddb22ad3a2543ad4f8047061d909c64fd75d | server/system/CommonMySQL.py | server/system/CommonMySQL.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCfg('MYSQL', 'idF... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
import logging
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCf... | Remove some bug on mysql elements. | Remove some bug on mysql elements.
| Python | mit | Deisss/webservice-notification,Deisss/webservice-notification |
9ffb43c969288bdb06de20aded660bd7e4e5c337 | plugins/witai.py | plugins/witai.py | import os
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
@respond_to('')
def wit(message):
message.react('+1')
message.reply('You... | import os
import random
import string
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
wit_context = {}
def random_word(length):
return... | Create new session on restart | Create new session on restart
| Python | mit | sanjaybv/netbot |
25351cd6b9119ea27123a2fddbbcc274c3620886 | examples/examples.py | examples/examples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size =... | Add plot legend in the example | Add plot legend in the example
| Python | mit | khrapovs/multidensity |
cde9dd479b2974f26f2e50b3611bfd0756f86c2b | game_of_thrones/__init__.py | game_of_thrones/__init__.py | class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
return [pair for pair in zip(text[0::1], text[1::1])]
| class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya'... | Add docstring to the `pair_symbols` method | Add docstring to the `pair_symbols` method
| Python | mit | Matt-Deacalion/Name-of-Thrones |
c8cbd2c660a2e10cc021bdc0a2fead872f77967d | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyErro... | # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyErro... | Use iterator in resultset data migration | Use iterator in resultset data migration
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
32d2d6069191cd2f7e98d1dedce13ddc1a6b1f32 | config.py | config.py | dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://sixpak.org/finance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| Use example.com for API URL. | Use example.com for API URL. | Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash |
8c950b364cc22d800cfac7af347b6bed3d012d6b | pyseeta/config.py | pyseeta/config.py |
import os
import sys
config = {
'win32': {
'detector': 'seeta_fd_lib.dll',
'aligner': 'seeta_fa_lib.dll',
'identifier': 'seeta_fi_lib.dll'
},
'darwin': {
'detector': 'libseeta_fd_lib.dylib',
'aligner': 'libseeta_fa_lib.dylib',
'identifier': 'libseeta_fi_lib.... |
import os
import sys
config = {
'win32': {
'detector': 'seeta_fd_lib.dll',
'aligner': 'seeta_fa_lib.dll',
'identifier': 'seeta_fi_lib.dll'
},
'darwin': {
'detector': 'libseeta_fd_lib.dylib',
'aligner': 'libseeta_fa_lib.dylib',
'identifier': 'libseeta_fi_lib.... | Fix crash when Ubuntu 16.04 x64 Python 2.7.12 (default, Nov 19 2016, 06:48:10) sys.platform return 'linux2' | Fix crash
when Ubuntu 16.04 x64 Python 2.7.12 (default, Nov 19 2016, 06:48:10) sys.platform return 'linux2'
| Python | mit | TuXiaokang/pyseeta |
21a4c6c5cdf3461ef2bd6048a7399044e8b1a0e8 | spyder_unittest/backend/pytestworker.py | spyder_unittest/backend/pytestworker.py | # -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Script for running py.test tests.
This script is meant to be run in a separate process by a PyTestRunner.
It runs tests via the py.test framework and prints the res... | # -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Script for running py.test tests.
This script is meant to be run in a separate process by a PyTestRunner.
It runs tests via the py.test framework and prints the res... | Add py.test plugin which prints out test names as they are collected | Add py.test plugin which prints out test names as they are collected
| Python | mit | jitseniesen/spyder-unittest |
2fdc5943bc6f23c6d56d6bb86e6a5bf33338237e | digikey/admin.py | digikey/admin.py | from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups
class ComponentInline(admin.TabularInline):
model = Order_Details
extra = 1
class OrderInline(admin.TabularInline):
model = Orders
extra = 1
fieldsets = [
('Payment information', {... | from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups
class ComponentInline(admin.TabularInline):
model = Order_Details
extra = 1
class OrderInline(admin.TabularInline):
model = Orders
extra = 1
fieldsets = [
('Payment information', {... | Add Filter option for order amd order group | Add Filter option for order amd order group
| Python | mit | sonicyang/chiphub,sonicyang/chiphub,sonicyang/chiphub |
de2568dd1feec001098574e28848ca0ef8bca475 | search/sorting.py | search/sorting.py |
def sort_by_popularity(items):
return sorted(items, key=lambda product: product.popularity, reverse=True)
|
def sort_by_property(prop):
def _sort_by_property(items):
return sorted(items,
key=lambda item: getattr(item, prop),
reverse=True)
return _sort_by_property
sort_by_popularity = sort_by_property('popularity')
| Redefine sort function to a generic one. Some overhead but can use for any property | Redefine sort function to a generic one. Some overhead but can use for
any property | Python | mit | vanng822/geosearch,vanng822/geosearch,vanng822/geosearch |
05001e4a60d7fe0babf8f66ba9a5cecd2ffc4e85 | geotrek/trekking/templatetags/trekking_tags.py | geotrek/trekking/templatetags/trekking_tags.py | from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
... | from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
... | Fix pretty duration for null value | Fix pretty duration for null value
| Python | bsd-2-clause | mabhub/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,mabhub/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,johan--/Geotrek,makinacorpus/Geot... |
d5817c04a57d8c593335450b0613fd683fdf5aec | pycalphad/__init__.py | pycalphad/__init__.py | #first import dill, which populates itself into pickle's dispatch
import dill
import pickle
# save the MethodDescriptorType from dill
MethodDescriptorType = type(type.__dict__['mro'])
if pickle.__dict__.get('_Pickler', None):
MethodDescriptorWrapper = pickle._Pickler.dispatch[MethodDescriptorType]
else:
MethodD... | # This unfortunate monkey patch is necessary to make Py27, Py33 and Py34 work
# Source: http://stackoverflow.com/questions/34124270/pickling-method-descriptor-objects-in-python
# first import dill, which populates itself into pickle's dispatch
import dill
import pickle
# save the MethodDescriptorType from dill
MethodD... | Add source of pickle hack | DOC: Add source of pickle hack
| Python | mit | tkphd/pycalphad,tkphd/pycalphad,tkphd/pycalphad |
27a33628310cbd68632f0e8b514de731a033f8e6 | IPython/utils/tests/test_shimmodule.py | IPython/utils/tests/test_shimmodule.py | import sys
import warnings
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
import IPython.config
assert len(w) == 1
assert issubclass(w[-1]... | import pytest
import sys
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with pytest.warns(ShimWarning):
import IPython.config
| Make test_shim_warning not fail on unrelated warnings | Make test_shim_warning not fail on unrelated warnings
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
8c01b3536026d56abb42daaf9d300e53e7c6dc18 | detox/main.py | detox/main.py | import sys
import py
import detox
from detox.proc import Detox
def parse(args):
from tox.session import prepare
return prepare(args)
def main(args=None):
if args is None:
args = sys.argv[1:]
config = parse(args)
#now = py.std.time.time()
detox = Detox(config)
detox.startloopreport(... | import sys
import py
import detox
from detox.proc import Detox
def parse(args):
from tox.session import prepare
return prepare(args)
def main(args=None):
if args is None:
args = sys.argv[1:]
config = parse(args)
#now = py.std.time.time()
detox = Detox(config)
detox.startloopreport(... | Raise system code on exit from `python -m detox` | Raise system code on exit from `python -m detox` | Python | mit | tox-dev/detox |
97b7ba9d4d6bf948435ce58dd21b60d78d75fd29 | lib-dynload/lzo/__init__.py | lib-dynload/lzo/__init__.py | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... | Adjust maximum block size for lzo | Adjust maximum block size for lzo
| Python | mit | sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs |
6a8f5bcc6dd42e125f7219d7d692c3af610c38c3 | masters/master.client.polymer/polymer_repos.py | masters/master.client.polymer/polymer_repos.py | # 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.
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'ShadowDOM',
'HTMLImports',
)
| # 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.
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'PointerEvents',
'ShadowDOM',
'HTMLImports',
)
| Add PointerEvents repo to master.client.polymer. | Add PointerEvents repo to master.client.polymer.
R=hinoka@google.com
BUG=chromium:237914
Review URL: https://codereview.chromium.org/15783003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@201643 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
d74ded300b9f40ecca883b4940eb67ed9cb04b18 | Rasp/weight_sensor/weight_sensor.py | Rasp/weight_sensor/weight_sensor.py | import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
Not test yet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPI... | import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPIO.OUT) # SCK comm... | Change the DT call, now the coding is working | Change the DT call, now the coding is working
| Python | mit | CarlosPena00/Mobbi,CarlosPena00/Mobbi |
327413aa982dec1c56691ea0017298a2ae7af2c1 | integration_tests/hello_world/__init__.py | integration_tests/hello_world/__init__.py | integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
| integration_test = True
name = 'HelloWorldTest'
package = 'helloworld'
can_crash = True
can_shutdown = True
def check_state(state):
assert('Hello World!' in state.console)
assert('not in console' in state.console)
| Add an integration test that deliberately fails | Add an integration test that deliberately fails
| Python | bsd-2-clause | unigornel/unigornel,unigornel/unigornel |
096f9e86755a6967d732986c51ae00855551cf4d | project_name/urls.py | project_name/urls.py | from django.conf import settings
from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.views.generic import TemplateView
import django_js_reverse.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^jsreverse/$', django_js_reverse.views.urls_js, name='js_rev... | from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.views.generic import TemplateView
import django_js_reverse.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^jsreverse/$', django_js_reverse.views.urls_js, name='js_reverse'),
url(r'^$', TemplateV... | Remove usage from debug toolbar | Remove usage from debug toolbar
| Python | mit | vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate |
74d7c55ab6584daef444923c888e6905d8c9ccf1 | expense/admin.py | expense/admin.py | from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
readonly_fields = ['amount']
fields =... | from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
fields = ('date', 'contact', 'number', 'd... | Allow editing amount field in expensenote | Allow editing amount field in expensenote
| Python | mpl-2.0 | jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django |
3ef77edcbf4b3268399f439b89f15ef087bd06bb | chamber/utils/logging.py | chamber/utils/logging.py | import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
... | import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
... | Set default value for json.dumps | Set default value for json.dumps
Use default value when type cannot be serialized.
| Python | bsd-3-clause | druids/django-chamber |
af3f0b520a868832f708e7692736005e6aee9c4b | core/admin.py | core/admin.py | from django.contrib import admin
from .models import FileUpload
class FileUploadAdmin(admin.ModelAdmin):
readonly_fields = ['owner']
def get_fields(self, request, obj=None):
if request.user.is_superuser:
return ['file', 'url_name', 'owner']
else:
return ['file', 'url_... | from django.contrib import admin
from .models import FileUpload
class FileUploadAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
return {'owner': request.user}
def get_fields(self, request, obj=None):
if request.user.is_superuser:
return ['file', 'url_name... | Make owner visible to superusers | Make owner visible to superusers
| Python | mit | swarmer/files,swarmer/files |
fac8f1af6bd3eb46fe2a26689b0d85f358934f7a | network_checker/url_access_checker/cli.py | network_checker/url_access_checker/cli.py | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | Add EDITOR variable in urlaccesschecker | Add EDITOR variable in urlaccesschecker
This variable required by cmd2 library to work.
Without - it fails on bootstrap with traceback:
File "/usr/lib/python2.6/site-packages/cmd2.py", line 424, in Cmd
if subprocess.Popen(['which', editor])
Change-Id: I061f88b65d7bc7181752cd076da4067df2f84131
Related-Bug: 1439686
| Python | apache-2.0 | prmtl/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,SmartInfrastructures/fuel-web-dev,nebril/fuel-web,huntxu/fuel-web,prmtl/fuel-web,eayunstack/fuel-web,stackforge/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,eayunstack/fuel-web,SmartInfrastructures/fuel-web-dev,nebril/fuel-web,SmartI... |
6a7a553dd51abbd6ade2e448bae0e4e2a8036f23 | generate-data.py | generate-data.py | #!/usr/bin/env python
import random
from nott_params import *
num_samples = int(gridDim[0] * gridDim[1] * 10)
def generate_data(numx, numy):
data = ['0' for i in range(numx * numy)]
stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1))
data[stimulus[1] * numx + stimulus[0]] = '1'
retu... | #!/usr/bin/env python
import random
from nott_params import *
num_samples = int(gridDim[0] * gridDim[1] * 10)
def generate_data(numx, numy):
ldata = ['0' for i in range(numx * numy)]
rdata = ['0' for i in range(numx * numy)]
stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1))
ldata[... | Add separate left and right eye data generation | Add separate left and right eye data generation
| Python | mit | jeffames-cs/nnot |
b8848917db13e374238f052f701b2f11e7ab8d36 | tests/config_test.py | tests/config_test.py | ### Going to fill this out in a subsequent PR
| import os
import tempfile
from unittest import TestCase
from dusty import constants, config
class TestConfig(TestCase):
def setUp(self):
self.temp_config_path = tempfile.mkstemp()[1]
self.old_config_path = constants.CONFIG_PATH
constants.CONFIG_PATH = self.temp_config_path
self.te... | Add some tests for the config module | Add some tests for the config module
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty |
7635f6dd4a208982f68617c5aeec36fbc6d69dc9 | tests/test_compat.py | tests/test_compat.py | from unittest import TestCase
from ddt import ddt, data
from aioresponses.compat import (
_vanilla_merge_url_params, _yarl_merge_url_params
)
@ddt
class CompatTestCase(TestCase):
use_default_loop = False
def setUp(self):
self.url = 'http://example.com/api?foo=bar#fragment'
@data(
_... | from unittest import TestCase
from ddt import ddt, data
from aioresponses.compat import (
_vanilla_merge_url_params, _yarl_merge_url_params, URL
)
@ddt
class CompatTestCase(TestCase):
use_default_loop = False
def setUp(self):
self.url = 'http://example.com/api?foo=bar#fragment'
self.yarn_... | Fix tests when yarn is not available | Fix tests when yarn is not available
| Python | mit | pnuckowski/aioresponses |
b65c733949b02531b14e7eb7868d275deff4c192 | tests/test_trivia.py | tests/test_trivia.py |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parenthes... |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parenthes... | Test trivia answer with wrong encoding | [Tests] Test trivia answer with wrong encoding
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
cd084fced40beb429474fabf33dff675e9ccb522 | syncplay/__init__.py | syncplay/__init__.py | version = '1.6.7'
revision = ''
milestone = 'Yoitsu'
release_number = '94'
projectURL = 'https://syncplay.pl/'
| version = '1.6.8'
revision = ' development'
milestone = 'Yoitsu'
release_number = '95'
projectURL = 'https://syncplay.pl/'
| Mark as 1.6.8 dev (build 95) | Mark as 1.6.8 dev (build 95)
| Python | apache-2.0 | alby128/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay |
547e2cbddd26f2e158fbbdab8ae22605cbd270c9 | joby/items.py | joby/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class JobItem(Item):
website_url = Field()
website_language = Field()
publication_date = Field()
posting_id = Field()... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
from scrapy.loader import Identity, ItemLoader
from scrapy.loader.processors import TakeFirst
class JobItem(Item):
website_url = F... | Add JobItemLoader and DataScienceJobsItemLoader class. | Add JobItemLoader and DataScienceJobsItemLoader class.
| Python | mit | cyberbikepunk/job-spiders |
49891ea015c082443b2c709650d125a649e36187 | poolwatcher/poolWatcher.py | poolwatcher/poolWatcher.py | #
# Description:
# This is the main of the poolWatcher
#
# Arguments: (eventually)
# $1 = poll period (in seconds)
# $2 = advertize rate (every $2 loops)
# $3 = glidein submit_dir
#
# Author:
# Igor Sfiligoi (Feb 13th 2007)
#
import os
import os.path
import sys
import traceback
import time
sys.path.append(".... | #
# Description:
# This is the main of the poolWatcher
#
# Arguments: (eventually)
# $1 = poll period (in seconds)
# $2 = advertize rate (every $2 loops)
# $3 = glidein submit_dir
#
# Author:
# Igor Sfiligoi (Feb 13th 2007)
#
import os
import os.path
import sys
import traceback
import time
sys.path.append(".... | Add distinction between claimed and unclaimed | Add distinction between claimed and unclaimed
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old |
c8e1c9720a29d0efa719467774e12ccf06a7989b | tests/test_frog.py | tests/test_frog.py | import csv
from io import StringIO
import logging
from nose.tools import assert_equal
from unittest import SkipTest
from nlpipe.modules.frog import FrogLemmatizer
from tests.tools import check_status
def test_process():
"""
Test Frog lemmatizing
Make sure a frog server is listening at port 9000, e.g.:
... | import csv
from io import StringIO
import logging
from nose.tools import assert_equal
from unittest import SkipTest
from nlpipe.modules.frog import FrogLemmatizer
from tests.tools import check_status
def test_process():
"""
Test Frog lemmatizing
Make sure a frog server is listening at port 9000, e.g.:
... | Add test for frog csv format | Add test for frog csv format
| Python | mit | vanatteveldt/nlpipe,vanatteveldt/nlpipe,vanatteveldt/nlpipe |
a736a7573745af7d72e4297dbfe8799ed472217a | bookmarks/models.py | bookmarks/models.py | from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.dialects.mysql import BIGINT
from sqlalchemy.orm import relationship
from bookmarks.database import Base
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=Tru... | from sqlalchemy import Column, Integer, BigInteger, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from bookmarks.database import Base
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False)
name = Col... | Use sqlalchemy BigInteger instead of mysql BIGINT | Use sqlalchemy BigInteger instead of mysql BIGINT
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks |
e97fabb025e66671edbe4446efa966d853f1d6df | tools/utils.py | tools/utils.py | #!/usr/bin/env python
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.... | #!/usr/bin/env python
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
python_path = os.environ.get('PYTHONPATH')
if python_path:... | Add depot_tools to PYTHONPATH for pylint | Add depot_tools to PYTHONPATH for pylint
Otherwise, pylint will fail on trybot.
| Python | bsd-3-clause | weiyirong/crosswalk-1,qjia7/crosswalk,baleboy/crosswalk,pozdnyakov/crosswalk,rakuco/crosswalk,jpike88/crosswalk,baleboy/crosswalk,baleboy/crosswalk,huningxin/crosswalk,jpike88/crosswalk,myroot/crosswalk,Pluto-tv/crosswalk,Pluto-tv/crosswalk,jondong/crosswalk,DonnaWuDongxia/crosswalk,ZhengXinCN/crosswalk,tomatell/crossw... |
ec784672ec59274e4bb4c227935439d6c0b31155 | numatuned/virsh.py | numatuned/virsh.py | import glob
import subprocess
from .read import read
class Virsh:
"""Class can be used to execute virsh commands for a given domain"""
domain = ""
def __init__(self, domain):
self.domain = domain
@staticmethod
def get_domain_list():
pid_files = glob.glob('/var/run/libvirt/qemu/*.p... | import glob
import subprocess
from .read import read
class Virsh:
"""Class can be used to execute virsh commands for a given domain"""
domain = ""
def __init__(self, domain):
self.domain = domain
@staticmethod
def get_domain_list():
pid_files = glob.glob('/var/run/libvirt/qemu/*.p... | Use numatune but use mode preferred | Use numatune but use mode preferred
| Python | mit | dionbosschieter/numatuned,dionbosschieter/numatuned |
c06d4ddc54bbe4b10dd0722f5a76d9cb7550da53 | tests/test_config.py | tests/test_config.py | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
def test_base_config_get_ri... | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | Test case when there's no riemann config | Test case when there's no riemann config
| Python | mit | CodersOfTheNight/oshino |
28bb18bae725af7c7af434c809dc2e32f8a3fcd6 | ticketus/ui/views.py | ticketus/ui/views.py | from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.http import require_POST
from ticketus.core.models import *
from ticketus.core.forms import CommentForm
def ticket_list(request, template='ui/ticket_list.html'):
tickets = Ticket.objects.all()
context = {'tickets': t... | from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.http import require_POST
from ticketus.core.models import *
from ticketus.core.forms import CommentForm
def ticket_list(request, template='ui/ticket_list.html'):
tickets = Ticket.objects.all()
context = {'tickets': t... | Set commenter to logged in user, not ticket requestor | Set commenter to logged in user, not ticket requestor
| Python | bsd-2-clause | sjkingo/ticketus,sjkingo/ticketus,sjkingo/ticketus,sjkingo/ticketus |
33ce8c19469b703b73727bd759b9655124919ae5 | script/coroutines.py | script/coroutines.py |
# -*- coding: ascii -*-
# A generator-based coroutine framework.
import select
def run(routines):
while routines:
for r in routines:
try:
result = r.next()
except StopIteration:
routines.remove(r)
|
# -*- coding: ascii -*-
# A generator-based coroutine framework.
import select
class Executor:
def __init__(self):
self.routines = {}
def add(self, routine):
self.routines[routine] = True
def _remove(self, routine):
self.routines.pop(routine, None)
def __call__(self):
... | Convert coroutine executor to OOP | [Scripts] Convert coroutine executor to OOP
| Python | mit | CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant |
29bf7ef7de9e0a5c66876b126f4df7ef279e30b6 | mediacloud/mediawords/db/exceptions/handler.py | mediacloud/mediawords/db/exceptions/handler.py | class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQu... | class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQu... | Revert "Add exception to be thrown by select()" | Revert "Add exception to be thrown by select()"
This reverts commit 1009bd3b5e5941aff2f7b3852494ee19f085dcce.
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud |
874d6f568a1367cbaad077648202f3328cd2eb8f | modules/Metadata/entropy.py | modules/Metadata/entropy.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections impor... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections impor... | Add conf arg to check function | Add conf arg to check function | Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,awest1339/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,mitre/multiscanner |
067a02fc5d4a432f4dc7f10cdc098b9ebdad9ccd | extract_options.py | extract_options.py | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['cuisines'] =... | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['categories']... | Add 'All' option to lists | Add 'All' option to lists
| Python | mit | earlwlkr/POICrawler |
552d1c02a46d70de92f4af4c77ce60f87d8811cc | mp3-formatter/rename_mp3.py | mp3-formatter/rename_mp3.py | #!/usr/bin/python3
import ID3
import os
import sys
mp3_extension = ".mp3"
names = ["final_name_1", "final_name_2", "final_name_3"]
files_all = os.listdir('.')
files = []
for f in files_all:
# Prune directories
if not os.path.isfile(f):
continue
# Prune non-MP3 files
filename, extension = o... | #!/usr/bin/python3
import ID3
import os
import sys
def read_tracklist():
tracklist = []
for line in sys.stdin:
tracklist.append(line)
return tracklist
tracklist = read_tracklist()
mp3_extension = ".mp3"
files_all = os.listdir('.')
files = []
for f in files_all:
# Prune directories
if n... | Replace hardcoded names with tracklist | MP3: Replace hardcoded names with tracklist
| Python | mit | jleung51/scripts,jleung51/scripts,jleung51/scripts |
fb3db1196a48199bc388f97f451098a530822ca7 | ecs/models.py | ecs/models.py | """Entity, Component, and System classes."""
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Entity(object):
"""Encapsulation of a GUID to use in the entity database."""
def __init__(self, guid):
""":param guid: globally unique identifier
:type guid: :class... | """Entity, Component, and System classes."""
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Entity(object):
"""Encapsulation of a GUID to use in the entity database."""
def __init__(self, guid):
""":param guid: globally unique identifier
:type guid: :class... | Remove unnecessary model docstrings, add repr. | Remove unnecessary model docstrings, add repr.
| Python | mit | seanfisk/ecs,seanfisk/ecs |
761d74c25fc54cba0c160380d17ab0ca14838dc9 | helpers/suggestions/match_suggestion_accepter.py | helpers/suggestions/match_suggestion_accepter.py | from helpers.match_manipulator import MatchManipulator
from models.match import Match
class MatchSuggestionAccepter(object):
"""
Handle accepting Match suggestions.
"""
@classmethod
def accept_suggestions(self, suggestions):
matches = map(lambda match_future: match_future.get_result(),... | from helpers.match_manipulator import MatchManipulator
from models.match import Match
class MatchSuggestionAccepter(object):
"""
Handle accepting Match suggestions.
"""
@classmethod
def accept_suggestions(self, suggestions):
if (len(suggestions) < 1):
return None
m... | Fix problem when not accepting any suggestions. | Fix problem when not accepting any suggestions.
| Python | mit | the-blue-alliance/the-blue-alliance,josephbisch/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-... |
e513e41dd10df009a3db7641774db1acba60a301 | tensormate/graph/__init__.py | tensormate/graph/__init__.py | from tensormate.graph.base import *
from tensormate.graph.data_pipeline import *
| from tensormate.graph.base import *
from tensormate.graph.data_pipeline import *
from tensormate.graph.image_graph import *
| Add an access from graph | Add an access from graph
| Python | apache-2.0 | songgc/tensormate |
ab342b6a90c34abbfc49c72a9f72251d238589b3 | git_helper.py | git_helper.py | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.... | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = os.path.realpath(view.file_name())
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(direct... | Resolve symbolic links for filename in Sublime view - without this all files available through symlinks are considered as new to git | Resolve symbolic links for filename in Sublime view - without this all files available through symlinks are considered as new to git
| Python | mit | robfrawley/sublime-git-gutter,jisaacks/GitGutter,robfrawley/sublime-git-gutter,akpersad/GitGutter,ariofrio/VcsGutter,natecavanaugh/GitGutter,biodamasceno/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,bradsokol/VcsGutter,tushortz/GitGutter,michaelhogg/GitGutter,natecavanaugh/GitGutter,akpersad/GitGutter,robfrawley/... |
5d5e9ff082eb6f277270045618812c4b2c49daab | 31-trinity/tf-31.py | 31-trinity/tf-31.py | #!/usr/bin/env python
import sys, re, operator, collections
#
# Model
#
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
stopwords = set(open('../stop_words.txt... | #!/usr/bin/env python
import sys, re, operator, collections
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
self.update(path_to_file)
def update(self, path... | Make the mvc example interactive | Make the mvc example interactive
| Python | mit | alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.