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 |
|---|---|---|---|---|---|---|---|---|---|
4d8ee930b772329b4c3ded17a5a04efb7dada977 | tests/test__compat.py | tests/test__compat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import dask
import dask.array as da
import dask.array.utils as dau
import dask_distance._compat
@pytest.mark.parametrize("x", [
list(range(5)),
np.random.randint(10, size=(15, 16)),
da.random.randint(10, size=(15, 16), chu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import dask.array as da
import dask.array.utils as dau
import dask_distance._compat
@pytest.mark.parametrize("x", [
list(range(5)),
np.random.randint(10, size=(15, 16)),
da.random.randint(10, size=(15, 16), chunks=(5, 5)),... | Drop unused import from _compat tests | Drop unused import from _compat tests
| Python | bsd-3-clause | jakirkham/dask-distance |
ac0fe94d5ced669bb1e5b5c0645b0597bf96c895 | tests/test_unicode.py | tests/test_unicode.py | import os
from tests.test_pip import here, reset_env, run_pip
def test_install_package_that_emits_unicode():
"""
Install a package with a setup.py that emits UTF-8 output and then fails.
This works fine in Python 2, but fails in Python 3 with:
Traceback (most recent call last):
...
File "... | import os
from tests.test_pip import here, reset_env, run_pip
def test_install_package_that_emits_unicode():
"""
Install a package with a setup.py that emits UTF-8 output and then fails.
This works fine in Python 2, but fails in Python 3 with:
Traceback (most recent call last):
...
File "... | Fix unicode tests to work with new temp file assertions | Fix unicode tests to work with new temp file assertions
| Python | mit | pjdelport/pip,patricklaw/pip,fiber-space/pip,dstufft/pip,esc/pip,prasaianooz/pip,wkeyword/pip,nthall/pip,fiber-space/pip,graingert/pip,davidovich/pip,luzfcb/pip,cjerdonek/pip,jythontools/pip,RonnyPfannschmidt/pip,pjdelport/pip,techtonik/pip,pradyunsg/pip,mindw/pip,prasaianooz/pip,ianw/pip,qwcode/pip,erikrose/pip,zenlam... |
2e95fa670bccd4b38aa1bf30932b152559c077f4 | fuse_util.py | fuse_util.py | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | Handle that Path can be none | Handle that Path can be none
| Python | mit | fusetools/Fuse.SublimePlugin,fusetools/Fuse.SublimePlugin |
63f7489066aeb23dbefc6f8de534ad05144431ad | boardinghouse/tests/test_sql.py | boardinghouse/tests/test_sql.py | """
Tests for the RAW sql functions.
"""
from django.conf import settings
from django.test import TestCase
from django.db.models import connection
from boardinghouse.models import Schema
class TestRejectSchemaColumnChange(TestCase):
def test_exception_is_raised(self):
Schema.objects.mass_create('a')
... | """
Tests for the RAW sql functions.
"""
from django.conf import settings
from django.test import TestCase
from django.db import connection
from boardinghouse.models import Schema
class TestRejectSchemaColumnChange(TestCase):
def test_exception_is_raised(self):
Schema.objects.mass_create('a')
cur... | Make test work with 1.7 | Make test work with 1.7
| Python | bsd-3-clause | luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse |
e3adb0e716cd3f200baa037f6d5a1dd0bb598202 | src/shield/__init__.py | src/shield/__init__.py | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
import inspect
from . import registry
class _method_wrapper(object):
"""A placeholder object used to wrap methods until the rules decorator
comes around and adds everything to the s... | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from . import registry
class rule:
"""Add the decorated rule to our registry"""
def __init__(self, *perms, **kwargs):
"""owner: The owner of the permissions.
permis... | Delete the class method shenannigans | Delete the class method shenannigans
| Python | mit | concordusapps/python-shield |
ce38ad1884cdc602d1b70d5a23d749ff3683f440 | reqon/utils.py | reqon/utils.py | def dict_in(value):
'''
Checks for the existence of a dictionary in a list
Arguments:
value -- A list
Returns:
A Boolean
'''
for item in value:
if isinstance(item, dict):
return True
return False
| def dict_in(value):
'''
Checks for the existence of a dictionary in a list
Arguments:
value -- A list
Returns:
A Boolean
'''
return any(isinstance(item, dict) for item in value)
| Make the dict_in function sleeker and sexier | Make the dict_in function sleeker and sexier
| Python | mit | dmpayton/reqon |
ad79f01358aa83162730b15507d7d6d3c3575ab3 | akanda/horizon/configuration/tabs.py | akanda/horizon/configuration/tabs.py | import collections
import logging
from django.utils.translation import ugettext as _
from horizon.api import quantum
from horizon import tabs
from akanda.horizon.configuration.tables.publicips import PublicIPsTable
# The table rendering code assumes it is getting an
# object with an "id" property and other propert... | import collections
import logging
from django.utils.translation import ugettext as _
from horizon.api import quantum
from horizon import tabs
from akanda.horizon.configuration.tables.publicips import PublicIPsTable
# The table rendering code assumes it is getting an
# object with an "id" property and other propert... | Handle missing port and router data | Handle missing port and router data
On some systems routers have no ports and ports
have no fixed IPs, so don't assume they do.
Also includes some pep8 fixes.
Change-Id: I73b5f22754958b897a6ae55e453c294f47bf9539
Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>
| Python | apache-2.0 | dreamhost/akanda-horizon,dreamhost/akanda-horizon |
b0b1be44c64ed48c15f9e796b90a21e7e4597df8 | jsrn/encoding.py | jsrn/encoding.py | # -*- coding: utf-8 -*-
import json
import registration
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
state = o.__getstate__()
state['$'] = o._meta.resource_name
... | # -*- coding: utf-8 -*-
import json
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields}
obj[resour... | Add extra documentation, remove use of __setstate__ and __getstate__ methods. | Add extra documentation, remove use of __setstate__ and __getstate__ methods.
| Python | bsd-3-clause | timsavage/jsrn,timsavage/jsrn |
f6e35897ce3b7e335310016c16a3bf76645bf077 | lib/authenticator.py | lib/authenticator.py | #
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from helpers.driver import HamperDriver
class HamperAuthenticator(object):
def __init... | #
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from helpers.driver import HamperDriver
from helpers.error import HamperError
from term... | Throw exception if invalid login details are used | Throw exception if invalid login details are used
| Python | mit | MobileXLabs/hamper |
4b93e5aa8c0ce90189fb852e75ee213d3be0d01a | flicks/base/urls.py | flicks/base/urls.py | from django.conf.urls.defaults import patterns, url
from flicks.base import views
urlpatterns = patterns('',
url(r'^/?$', views.home, name='flicks.base.home'),
url(r'^strings/?$', views.strings, name='flicks.base.strings'),
)
| from django.conf.urls.defaults import patterns, url
from flicks.base import views
urlpatterns = patterns('',
url(r'^/?$', views.home, name='flicks.base.home'),
url(r'^faq/?$', views.faq, name='flicks.base.faq'),
url(r'^strings/?$', views.strings, name='flicks.base.strings'),
)
| Add back in FAQ url that was removed accidentally. | Add back in FAQ url that was removed accidentally.
| Python | bsd-3-clause | mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks |
b236a7961dbc9930ed135602cbed783818bde16e | kolibri/utils/tests/test_cli_at_import.py | kolibri/utils/tests/test_cli_at_import.py | """
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_fun... | """
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_fun... | Add regression test against options evaluation during import in cli. | Add regression test against options evaluation during import in cli.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri |
013277886a3c9f5d4ab99f11da6a447562fe9e46 | benchexec/tools/cmaesfuzz.py | benchexec/tools/cmaesfuzz.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import re
import benchexec.util as util
import benchexec.tools.template
class Tool(benc... | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import re
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2)... | Update module to version 2 | Update module to version 2
| Python | apache-2.0 | sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec |
cde8c1b4c89a2e0ef3765372b4838373d5729cdb | alg_topological_sort.py | alg_topological_sort.py | def topological_sort_recur(adjacency_dict, start_vertex,
visited_set, finish_ls):
"""Topological Sorting by Recursion."""
visited_set.add(start_vertex)
for neighbor_vertex in adjacency_dict[start_vertex]:
if neighbor_vertex not in visited_set:
topological_sort_recur(
adjacency_dict, ... | def topological_sort_recur(adjacency_dict, start_vertex,
visited_set, finish_ls):
"""Topological Sorting by Recursion."""
visited_set.add(start_vertex)
for neighbor_vertex in adjacency_dict[start_vertex] - visited_set:
topological_sort_recur(
adjacency_dict, neighbor_vertex,
... | Revise for loop to find neighbor vertices | Revise for loop to find neighbor vertices
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
5496f501ff7da677ee76c442b6a5b544d595ce1d | epages/__init__.py | epages/__init__.py | # coding: utf-8
from epages.client import *
from epages.product_service import *
from epages.shop_service import *
from epages.shop import *
| # coding: utf-8
from epages.client import *
from epages.shop_service import *
from epages.shop import *
| Remove product_service from epages package | Remove product_service from epages package
| Python | mit | ooz/epages-rest-python,ooz/epages-rest-python |
a52bf3cbd84a6e1c9b0a685d3267934ec0ec0036 | misc/decode-mirax.py | misc/decode-mirax.py | #!/usr/bin/python
import struct, sys
f = open(sys.argv[1])
HEADER_OFFSET = 37
f.seek(HEADER_OFFSET)
try:
while True:
n = struct.unpack("<i", f.read(4))[0]
possible_lineno = (n - HEADER_OFFSET) / 4.0
if possible_lineno < 0 or int(possible_lineno) != possible_lineno:
print "%1... | #!/usr/bin/python
import struct, sys, os
f = open(sys.argv[1])
HEADER_OFFSET = 37
f.seek(HEADER_OFFSET)
filesize = os.stat(sys.argv[1]).st_size
num_items = (filesize - HEADER_OFFSET) / 4
skipped = False
i = 0
try:
while True:
n = struct.unpack("<i", f.read(4))[0]
possible_lineno = (n - HEADER... | Update decode mirax a bit | Update decode mirax a bit
| Python | lgpl-2.1 | openslide/openslide,openslide/openslide,openslide/openslide,openslide/openslide |
8dbf9d88be33537752f105cd8f8b60ec40de684a | docs/src/examples/over_play.py | docs/src/examples/over_play.py | import numpy as np
from scikits.audiolab import play
# output one second of stereo gaussian white noise at 48000 hz
play(0.05 * np.random.randn(2, 48000), rate=48000)
| import numpy as np
from scikits.audiolab import play
# output one second of stereo gaussian white noise at 48000 hz
play(0.05 * np.random.randn(2, 48000))
| Fix play example (thanks to Samuele CarCagno). | Fix play example (thanks to Samuele CarCagno).
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab |
e64d13486fe20c44dde0dea6a6fed5a95eddbbd1 | awx/main/notifications/email_backend.py | awx/main/notifications/email_backend.py | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import json
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
from django.utils.translation import ugettext_lazy as _
class CustomEmailBackend(EmailBackend):
init_parameters = {"host": {"label": "Host",... | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import json
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
from django.utils.translation import ugettext_lazy as _
class CustomEmailBackend(EmailBackend):
init_parameters = {"host": {"label": "Host",... | Remove Tower reference from email backend | Remove Tower reference from email backend
| Python | apache-2.0 | snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx |
fc25a6c4796ad008570974a682037bc575f15018 | astroquery/lamda/tests/test_lamda.py | astroquery/lamda/tests/test_lamda.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import lamda
def test_query():
Q = lamda.core.LAMDAQuery()
Q.lamda_query(mol='co', query_type='erg_levels')
Q.lamda_query(mol='co', query_type='rad_trans')
Q.lamda_query(mol='co', query_type='coll_rates')
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import lamda
def test_query():
lamda.print_mols()
lamda.query(mol='co', query_type='erg_levels')
lamda.query(mol='co', query_type='rad_trans')
lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
| Update tests for new style | Update tests for new style
Also added test for printing molecule list and made the collisional rate
test more complicated.
| Python | bsd-3-clause | imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery |
0cfd376b02da6ebc70ad66c913e3ee4750a6a04c | functional_tests.py | functional_tests.py | from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://localhost:8000')
assert 'Django' in browser.title
| from selenium import webdriver
import pytest
@pytest.fixture(scope='function')
def browser(request):
browser_ = webdriver.Firefox()
def fin():
browser_.quit()
request.addfinalizer(fin)
return browser_
def test_can_show_a_relevant_code_snippet(browser):
browser.get('http://localhost:800... | Refactor FTs to setup/teardown with pytest.fixture | Refactor FTs to setup/teardown with pytest.fixture
| Python | mit | jvanbrug/scout,jvanbrug/scout |
09eb16e94052cbf45708b20e783a602342a2b85b | photutils/__init__.py | photutils/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Photutils is an Astropy affiliated package to provide tools for
detecting and performing photometry of astronomical sources. It also
has tools for background estimation, ePSF building, PSF matching,
centroiding, and morphological measurements.
"""
im... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Photutils is an Astropy affiliated package to provide tools for
detecting and performing photometry of astronomical sources. It also
has tools for background estimation, ePSF building, PSF matching,
centroiding, and morphological measurements.
"""
im... | Add __all__ in package init for the test runner | Add __all__ in package init for the test runner
| Python | bsd-3-clause | larrybradley/photutils,astropy/photutils |
8fa1cae882c0ff020c0b9c3c2fac9e4248d46ce4 | deploy/common/sqlite_wrapper.py | deploy/common/sqlite_wrapper.py | import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=OFF")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, m... | import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA page_size=4096")
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=NORMAL")
self.conn.commit()
def query(self, sq... | Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096. | Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
| Python | mit | mikispag/bitiodine |
e2fa4b150546be4b4f0ae59f18ef6ba2b6180d1a | accounts/serializers.py | accounts/serializers.py | """Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and field definitions"""
model = User
... | """Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and field definitions"""
model = User
... | Change avatar to avatar_url in the user API | Change avatar to avatar_url in the user API
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,lutris/website |
9699d573fa459cb7ee90237d7fa64f7014c96db4 | scripts/update_centroid_reports.py | scripts/update_centroid_reports.py | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import mica.centroid_dashboard
# Cheat. Needs entrypoint scripts
mica.centroid_dashboard.update_observed_metrics()
| #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import mica.centroid_dashboard
# Cheat. Needs entrypoint scripts
mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
| Fix script default to actually save plots | Fix script default to actually save plots
| Python | bsd-3-clause | sot/mica,sot/mica |
733306f0953b9c80ead49529ba3e65b26a031426 | gaphor/diagram/classes/implementation.py | gaphor/diagram/classes/implementation.py | """
Implementation of interface.
"""
from gaphor import UML
from gaphor.diagram.diagramline import DiagramLine
class ImplementationItem(DiagramLine):
__uml__ = UML.Implementation
def __init__(self, id=None, model=None):
DiagramLine.__init__(self, id, model)
self._solid = False
def draw... | """
Implementation of interface.
"""
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, Text
from gaphor.diagram.support import represents
@represents(UML.Implementation)
class ImplementationItem(L... | Use new line style for Implementation item | Use new line style for Implementation item
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
9ce26dfb42753570ad7a2c89e51638aa5d49df2b | fedora/__init__.py | fedora/__init__.py | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ... | Use kitchen.i18n to setup gettext. Setup b_() for exceptions. | Use kitchen.i18n to setup gettext. Setup b_() for exceptions.
| Python | lgpl-2.1 | fedora-infra/python-fedora |
d7fc29fb6e0c449617cf6aae1025fd5b718d8b70 | modules/token.py | modules/token.py | class Token(object):
def __init__( self, line ):
entries = line.split('\t')
self.form = entries[0].lower()
self.gold_pos = entries[1]
self.predicted_pos = entries [3]
def createFeatureVector(self, featvec, currentToken, previousToken, nextToken):
self.sparseFeatvec = {}
#if previousToken: self.sparseF... | class Token(object):
def __init__( self, line ):
# Splits line tab-wise, writes the values in parameters
entries = line.split('\t')
if len(entries) == 4:
self.form = entries[0].lower()
self.gold_pos = entries[1]
self.predicted_pos = entries [3]
elif len(entries) > 4: print "\tInput file not in expe... | Handle wrong formatted input, added comments, some cosmetics | Handle wrong formatted input, added comments, some cosmetics
| Python | mit | YNedderhoff/perceptron-pos-tagger,YNedderhoff/named-entity-recognizer,YNedderhoff/perceptron-pos-tagger,YNedderhoff/aspect-classifier,YNedderhoff/aspect-classifier,YNedderhoff/named-entity-recognizer |
7d08a71874dd7b1ab7ba4bb1cd345161d9118266 | src/extract.py | src/extract.py | import os
import csv
from parser import Parser
class Extract:
"""
Extract data from .git repo and persist as a data set
"""
# repos name git: .git
# destination absolute path
def clone_repo(self, repo_name, destination):
Repo.clone_from(repo_name, destination)
# get parsed .diff file
def get_parsed_diff(sel... | import os
import csv
from parser import Parser
class Extract:
"""
Extract data from .git repo and persist as a data set
"""
# repos name git: .git
# destination absolute path
def clone_repo(self, repo_name, destination):
Repo.clone_from(repo_name, destination)
# get parsed .diff file
def get_parsed_diff(sel... | Move repo name to arg | Move repo name to arg
| Python | mit | rajikaimal/emma,rajikaimal/emma |
8d04bb798648980a2fe29ee408bdcff099bfd2c1 | tk/urls.py | tk/urls.py | from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^material/', include('tk.material.urls')),
url(r'^admin/', admin.site.urls),
]
| from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='base.html'), name='frontpage'),
url(r'^material/', include('tk.material.urls')),
url(r'^admin/', admin.s... | Add a frontpage rendering view | Add a frontpage rendering view
| Python | agpl-3.0 | GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa |
09498335615b7e770f5976b9749d68050966501d | models/timeandplace.py | models/timeandplace.py | #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from datetime import datetime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
... | #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from .realtime import RealtimeTime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
... | Revert "TimeAndPlace no longer refers to realtime data" | Revert "TimeAndPlace no longer refers to realtime data"
This reverts commit cf92e191e3748c67102f142b411937517c5051f4.
| Python | apache-2.0 | NoMoKeTo/choo,NoMoKeTo/transit |
cd471449edad56ef6c3a69d025130f4fb8ea1fea | plumbium/artefacts.py | plumbium/artefacts.py | import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self._filename = filename
self._ext_length = len(extension)
self._abspath = os.path.abspath(filename)
... | import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self._filename = filename
self._ext_length = len(extension)
self._abspath = os.path.abspath(filename)
... | Use correct method to get classname of self | Use correct method to get classname of self
| Python | mit | jstutters/Plumbium |
a5d61bee86c394cf6bc972020cbfe2f95463d1e2 | huxley/www/views.py | huxley/www/views.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).
import json
from huxley.api.serializers import UserSerializer
from huxley.utils.shortcuts import render_template
def index(request):
user_dict = {};
if request.... | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import json
from huxley.api.serializers import UserSerializer
from huxley.utils.shortcuts import render_template
def index(request):
user_dict = {};
if request.... | Fix XSS vulnerability in current user bootstrapping. | Fix XSS vulnerability in current user bootstrapping.
| Python | bsd-3-clause | bmun/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,bmun/huxley,bmun/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,bmun/huxley,nathanielparke/huxley |
049e8c746b5f40b3e708dcd749052405e2246160 | lc0084_largest_rectangle_in_histogram.py | lc0084_largest_rectangle_in_histogram.py | """Leetcode 84. Largest Rectangle in Histogram
Hard
URL: https://leetcode.com/problems/largest-rectangle-in-histogram/
Given n non-negative integers representing the histogram's bar height where the
width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each ... | """Leetcode 84. Largest Rectangle in Histogram
Hard
URL: https://leetcode.com/problems/largest-rectangle-in-histogram/
Given n non-negative integers representing the histogram's bar height where the
width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each ... | Complete increasing heights idx stack sol | Complete increasing heights idx stack sol
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
59bf9eca217ef8ef3011124d1ff9e1570e8ff76d | plugins/clue/clue.py | plugins/clue/clue.py | from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
def process_message(data):
outputs.append([data['channel'], "from repeat1 \"{}\" in channel {}".format(
data['text'], data['channel'])]
)
| from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
def process_message(data):
outputs.append([data['channel'], data['text']])
| Simplify stony's response to exactly what the user sent | Simplify stony's response to exactly what the user sent
Rather than providing the "from repeat1" and "in channel D???????" noise.
| Python | mit | cworth-gh/stony |
6d76842d9f9394aa78cda55fff9c62a4db5da5c6 | common.py | common.py | from __future__ import print_function
import os, pyrax, sys
import pyrax.exceptions as pexc
from termcolor import colored
import ConfigParser
from subprocess import check_output
path = os.path.dirname(os.path.realpath(__file__))
config_file = path + "/config.ini"
def log(level, message):
if level == 'OK':
print... | from __future__ import print_function
import os, pyrax, sys
import pyrax.exceptions as pexc
from termcolor import colored
import ConfigParser
import subprocess
path = os.path.dirname(os.path.realpath(__file__))
config_file = path + "/config.ini"
def log(level, message):
if level == 'OK':
print(colored('[ OK ]... | Fix for python 2.6 compatibility in subprocess | Fix for python 2.6 compatibility in subprocess
| Python | apache-2.0 | boxidau/rax-autoscaler,boxidau/rax-autoscaler,eljrax/rax-autoscaler,rackerlabs/rax-autoscaler |
9347f3bc4a9c37c7013e8666f86cceee1a7a17f9 | genome_designer/main/startup.py | genome_designer/main/startup.py | """Actions to run at server startup.
"""
from django.db import connection
def run():
"""Call this from manage.py or tests.
"""
_add_custom_mult_agg_function()
def _add_custom_mult_agg_function():
"""Make sure the Postgresql database has a custom function array_agg_mult.
NOTE: Figured out the r... | """Actions to run at server startup.
"""
from django.db import connection
from django.db import transaction
def run():
"""Call this from manage.py or tests.
"""
_add_custom_mult_agg_function()
def _add_custom_mult_agg_function():
"""Make sure the Postgresql database has a custom function array_agg_... | Fix bug with array_agg_mult() function not actually being created. | Fix bug with array_agg_mult() function not actually being created.
| Python | mit | churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,woodymit/millstone_accidental_source |
3e2b06aa73488323600a5942588b556f2d78c2af | persons/tests.py | persons/tests.py | """
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
... | from datetime import datetime
from django.test import TestCase
from unittest import skip
from .models import Person
from mks.models import Member
class PersonTests(TestCase):
@skip
def test_member_person_sync(self):
"""
Test member/person sync on member save()
"""
birth = d... | Test case for Member/Person sync | Test case for Member/Person sync
Skipped for now, to help with #4049
| Python | bsd-3-clause | navotsil/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,DanaOshri/Open-Knesset,jspan/Open-Knesset,navotsil/Open-Knesset,MeirKriheli/Open-Knesset,jspan/Open-Knesset,Shrulik/Open-Knesset,ofri/Open-Knesset,habeanf/Open-Knesset,jspan/Open-Knesset,noamelf/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Knesset,navotsi... |
8377f3e61441a7f465feefba905cd3c82586e1a5 | geomdl/visualization/__init__.py | geomdl/visualization/__init__.py | """ NURBS-Python Visualization Component
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
| """ NURBS-Python Visualization Component
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
__author__ = "Onur Rauf Bingol"
__version__ = "1.0.0"
__license__ = "MIT"
| Add metadata to visualization module | Add metadata to visualization module
| Python | mit | orbingol/NURBS-Python,orbingol/NURBS-Python |
2fc3ee4edc4b7a1842fca369620c790244000f11 | flask_apidoc/commands.py | flask_apidoc/commands.py | # Copyright 2015 Vinicius Chiele. 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 ... | # Copyright 2015 Vinicius Chiele. 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 ... | Set static/docs as the default folder to generate the apidoc's files | Set static/docs as the default folder to generate the apidoc's files
| Python | mit | viniciuschiele/flask-apidoc |
98771f6a7a96ccedf56e3619433e2451d5c3251f | exception/test1.py | exception/test1.py | #!/usr/local/bin/python
class MuffledCalculator:
muffled=False
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print "Can't divide zero"
else:
raise
a=MuffledCalculator()
print a.calc('2/1')
#print a.calc('1/0')
a.muffled=True
print a.... | #!/usr/local/bin/python
#class MuffledCalculator:
# muffled=False
# def calc(self,expr):
# try:
# return eval(expr)
# except (ZeroDivisionError,TypeError):
# if self.muffled:
# print "There are errors."
# else:
# raise
#a=MuffledCalculator()
#print a.calc('2/1')
##print a.calc('2/"d... | Use finally and so on. | Use finally and so on.
| Python | apache-2.0 | Vayne-Lover/Python |
661d42468359836c0ce9ee4e267241a4aaf7a021 | lot/views.py | lot/views.py | import json
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import get_object_or_404, resolve_url
from django.utils.http import is_safe_url
from django.views.generic import View
from django.contrib.auth import authenticate, login
from .models ... | import json
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.shortcuts import get_object_or_404, resolve_url
from django.utils.http import is_safe_url
from django.views.generic import View
from django.contrib.auth import authenticate, login
from .models ... | Check for an empty user | Check for an empty user | Python | bsd-3-clause | ABASystems/django-lot |
6fd0c91fd1bbc6ae1a8fae46503464ab63603d38 | pinry/api/api.py | pinry/api/api.py | from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
from django.contrib.auth.models import User
from pinry.pins.models import Pin
class PinResource(ModelResource): # pylint: disable-m... | from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
from django.contrib.auth.models import User
from pinry.pins.models import Pin
class PinResource(ModelResource): # pylint: disable-m... | Enable filtering over the published field | Enable filtering over the published field
Tastypie requires that we define a list of fields that can be used
for filtering; add the "published" to this list so we can query pinry
for the list of images created after some date.
| Python | bsd-2-clause | lapo-luchini/pinry,supervacuo/pinry,lapo-luchini/pinry,supervacuo/pinry,wangjun/pinry,QLGu/pinry,Stackato-Apps/pinry,dotcom900825/xishi,lapo-luchini/pinry,Stackato-Apps/pinry,MSylvia/pinry,pinry/pinry,MSylvia/pinry,pinry/pinry,pinry/pinry,Stackato-Apps/pinry,dotcom900825/xishi,QLGu/pinry,wangjun/pinry,QLGu/pinry,rafiro... |
e23b146f613ed6e0090b0ef1f895ee1785e56f31 | plugins/brian.py | plugins/brian.py | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | Use block quotes for Markov-chain plugin | Use block quotes for Markov-chain plugin
| Python | mit | kvchen/keffbot-py,kvchen/keffbot |
4cef3788a19b9ad7059184a39accd2b551407de4 | tests/test_benchmark.py | tests/test_benchmark.py | import os
from subprocess import check_call
import pytest
def run(command, problem, so, shape, nbpml, *extra):
args = ["python", "../benchmarks/user/benchmark.py", command]
args.extend(["-P", str(problem)])
args.extend(["-so", str(so)])
args.extend(["-d"] + [str(i) for i in shape])
args.extend(["... | from subprocess import check_call
def run_cmd(command, problem, so, shape, nbpml, *extra):
args = ["python", "../benchmarks/user/benchmark.py", command]
args.extend(["-P", str(problem)])
args.extend(["-so", str(so)])
args.extend(["-d"] + [str(i) for i in shape])
args.extend(["--nbpml", str(nbpml)]... | Check bench mode==run with fixed block shape | tests: Check bench mode==run with fixed block shape
| Python | mit | opesci/devito,opesci/devito |
9a14fec9a4bb931b41ab62988975e5688f16573d | cms/tests/test_permalinks.py | cms/tests/test_permalinks.py | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... | Fix permalinks test which was breaking other tests. | Fix permalinks test which was breaking other tests.
| Python | bsd-3-clause | lewiscollard/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,dan-gamble/cms,lewiscollard/cms,danielsamuels/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,jamesfoley/cms,jamesfoley/cms |
24341ee3dabcbad751c849ef8007b669bdce5141 | tests/test_bountyxml.py | tests/test_bountyxml.py | from hearthstone import bountyxml
def test_bountyxml_load():
bounty_db, _ = bountyxml.load()
assert bounty_db
assert bounty_db[47].boss_name == "Cap'n Hogger"
assert bounty_db[58].region_name == "The Barrens"
| from hearthstone import bountyxml
def test_bountyxml_load():
bounty_db, _ = bountyxml.load()
assert bounty_db
assert bounty_db[68].boss_name == "The Anointed Blades"
assert bounty_db[58].region_name == "The Barrens"
| Fix broken Mercenaries bountyxml test | Fix broken Mercenaries bountyxml test
| Python | mit | HearthSim/python-hearthstone |
32efe7a0365738f982030f7c5be3b702dbac87c8 | tests/test.py | tests/test.py | from devicehive import Handler
from devicehive import DeviceHive
class TestHandler(Handler):
"""Test handler class."""
def handle_connect(self):
if not self.options['handle_connect'](self):
self.api.disconnect()
def handle_event(self, event):
pass
class Test(object):
""... | from devicehive import Handler
from devicehive import DeviceHive
import pytest
class TestHandler(Handler):
"""Test handler class."""
def handle_connect(self):
if not self.options['handle_connect'](self):
self.api.disconnect()
def handle_event(self, event):
pass
class Test(o... | Add only_http_implementation and only_websocket_implementation methods | Add only_http_implementation and only_websocket_implementation methods
| Python | apache-2.0 | devicehive/devicehive-python |
0b15611eb0020bc2cdb4a4435756315b0bd97a21 | seria/cli.py | seria/cli.py | # -*- coding: utf-8 -*-
import click
from .compat import StringIO
import seria
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--xml', 'out_fmt', flag_value='xml')
@click.option('--yaml', 'out_fmt', flag_value='yaml')
@click.option('--jso... | # -*- coding: utf-8 -*-
import click
from .compat import StringIO, str, builtin_str
import seria
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--xml', 'out_fmt', flag_value='xml')
@click.option('--yaml', 'out_fmt', flag_value='yaml')
@c... | Fix errors with 2/3 FLO support | Fix errors with 2/3 FLO support
| Python | mit | rtluckie/seria |
b2d4bf11b293073c4410ca1be98f657a30c35762 | python/triple-sum.py | python/triple-sum.py |
# A special triplet is defined as: a <= b <= c for
# a in list_a, b in list_b, and c in list_c
def get_num_special_triplets(list_a, list_b, list_c):
# remove duplicates and sort lists
list_a = sorted(set(list_a))
list_b = sorted(set(list_b))
list_c = sorted(set(list_c))
num_special_triplets = 0
... | def get_num_special_triplets(list_a, list_b, list_c):
a_index = 0
c_index = 0
num_special_triplets = 0
for b in list_b:
while a_index < len(list_a) and list_a[a_index] <= b:
a_index += 1
while c_index < len(list_c) and list_c[c_index] <= b:
c_index += 1
... | Improve time complexity of solution | Improve time complexity of solution
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
4947ebf9460c2cf2ba8338de92601804dec2148a | src/svg_icons/templatetags/svg_icons.py | src/svg_icons/templatetags/svg_icons.py | import json
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
register = Library()
@register.inclusion_tag('svg_icons/icon.html')
def icon(name, **kwargs):
"""Render a SVG icon defined in a json file to our template.
..:json exampl... | import json
from importlib import import_module
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader')
try:
module, cls = reader_class.rspli... | Use the new reader classes in the template tag | Use the new reader classes in the template tag
| Python | apache-2.0 | mikedingjan/django-svg-icons,mikedingjan/django-svg-icons |
bcc40b08c59ba8fcb8efc9044c2ea6e11ed9df12 | tests/api/views/users/list_test.py | tests/api/views/users/list_test.py | from tests.data import add_fixtures, users
def test_list_users(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/')
assert res.status_code == 200
assert res.json == {
u'users': [{
u'id': john.id,
u'name': u'John Doe',
... | from tests.data import add_fixtures, users, clubs
def test_list_users(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/')
assert res.status_code == 200
assert res.json == {
u'users': [{
u'id': john.id,
u'name': u'John... | Add more "GET /users" tests | tests/api: Add more "GET /users" tests
| Python | agpl-3.0 | RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Harry-R/skylines,shadowoneau/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Turbo87/skylines,skylines-project/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,shadowoneau/skylines,skyline... |
e593306092292f72009e13bafe1cbb83f85d7937 | indra/bel/ndex_client.py | indra/bel/ndex_client.py | import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
status = res.status_code
if ... | import requests
import json
import time
ndex_base_url = 'http://services.bigmech.ndexbio.org'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res):
status = res.status_code
if ... | Fix messages in NDEx client | Fix messages in NDEx client
| Python | bsd-2-clause | jmuhlich/indra,pvtodorov/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,... |
e57c2cefa9e8403aa9a2f27d791604a179c8b998 | quickfileopen.py | quickfileopen.py | import sublime
import sublime_plugin
class QuickFileOpenCommand(sublime_plugin.WindowCommand):
def run(self):
settings = sublime.load_settings('QuickFileOpen.sublime-settings')
files = settings.get('files')
if type(files) == list:
self.window.show_quick_panel(files, self.on_don... | import sublime
import sublime_plugin
class QuickFileOpenCommand(sublime_plugin.WindowCommand):
def run(self):
settings = sublime.load_settings('QuickFileOpen.sublime-settings')
files = settings.get('files')
if type(files) == list:
self.window.show_quick_panel(files, self.on_don... | Handle the case where the user exits the panel | Handle the case where the user exits the panel
| Python | mit | gsingh93/sublime-quick-file-open |
d5ad324355e0abdf0a6bdcb41e1f07224742b537 | src/main.py | src/main.py | #!/usr/bin/env python3
# card-fight-thingy - Simplistic battle card game... thingy
#
# The MIT License (MIT)
#
# Copyright (c) 2015 The Underscores
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the S... | #!/usr/bin/env python3
# card-fight-thingy - Simplistic battle card game... thingy
#
# The MIT License (MIT)
#
# Copyright (c) 2015 The Underscores
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the S... | Remove needless import of sys module | Remove needless import of sys module
| Python | mit | TheUnderscores/card-fight-thingy |
d3b8b948dac6ccce68ccf21311397ce6792fddc6 | tests/test_modules/os_test.py | tests/test_modules/os_test.py | from subprocess import call, check_output
class TestOs:
""" Contains test methods to test
if the vagrant OS got installed properly """
| from subprocess import call, check_output
class TestOs:
""" Contains test methods to test
if the vagrant OS got installed properly """
def uname_kernel(self):
""" returns output of uname -s """
output = check_output(["uname", "-s"]).decode("utf-8").lstrip().rstrip()
return out... | Add tests for vagrant guest OS | Add tests for vagrant guest OS
| Python | bsd-3-clause | DevBlend/DevBlend,DevBlend/zenias,byteknacker/fcc-python-vagrant,DevBlend/DevBlend,DevBlend/zenias,DevBlend/zenias,byteknacker/fcc-python-vagrant,DevBlend/DevBlend,DevBlend/zenias,DevBlend/zenias,DevBlend/DevBlend,DevBlend/DevBlend,DevBlend/zenias,DevBlend/DevBlend |
1126c0e795d94e004fae03edda3e299b2d3b764c | todo/models.py | todo/models.py | from django.db import models
from django.utils.text import slugify
from common.models import TimeStampedModel
class List(TimeStampedModel):
name = models.CharField(max_length=50)
slug = models.CharField(max_length=50, editable=False)
def __unicode__(self):
return self.name
def save(self, *a... | from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify
from common.models import DeleteSafeTimeStampedMixin
class List(DeleteSafeTimeStampedMixin):
name = models.CharField(max_length=50)
slug = models.CharField(max_length=50, editable=False)
author ... | Attach user with List and Item | Attach user with List and Item
| Python | mit | ajoyoommen/zerrenda,ajoyoommen/zerrenda |
e84d6dc5be2e2ac2d95b81e4df18bc0ad939916a | __init__.py | __init__.py | import os
from flask import Flask, redirect, request, render_template
from flask_mail import Mail, Message
app = Flask (__name__)
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg'])
mail = Mail(app)
@app.route("/")
def index():
return render_template('in-development.html.j2')
if __name__ == "__main__":
a... | import os
from flask import Flask, redirect, request, render_template
from flask_mail import Mail, Message
app = Flask (__name__)
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg'])
mail = Mail(app)
@app.route("/")
def index():
return render_template('index.html.j2')
if __name__ == "__main__":
app.run()
| Split into new branch for development of the main site | Split into new branch for development of the main site
| Python | mit | JonathanPeterCole/Tech-Support-Site,JonathanPeterCole/Tech-Support-Site |
30609236e703123c464c2e3927417ae677f37c4e | nimp/base_commands/__init__.py | nimp/base_commands/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2014-2019 Dontnod Entertainment
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use,... | # -*- coding: utf-8 -*-
# Copyright (c) 2014-2019 Dontnod Entertainment
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use,... | Remove run_hook from list of imported commands. | Remove run_hook from list of imported commands.
| Python | mit | dontnod/nimp |
1cff28b9612c156363ed87cdde1718ee83b65776 | real_estate_agency/resale/serializers.py | real_estate_agency/resale/serializers.py | from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# ima... | from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# ima... | Make ResaleApartmentSerializer return Decoration.name on decoration field. | Make ResaleApartmentSerializer return Decoration.name on decoration field.
It allows to show readable value at resale detailed page.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency |
1e513d901dfef9135a62c8f99633b10d3900ecb8 | orator/schema/mysql_builder.py | orator/schema/mysql_builder.py | # -*- coding: utf-8 -*-
from .builder import SchemaBuilder
class MySQLSchemaBuilder(SchemaBuilder):
def has_table(self, table):
"""
Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool
"""
sql = self._grammar.compile... | # -*- coding: utf-8 -*-
from .builder import SchemaBuilder
class MySQLSchemaBuilder(SchemaBuilder):
def has_table(self, table):
"""
Determine if the given table exists.
:param table: The table
:type table: str
:rtype: bool
"""
sql = self._grammar.compile_... | Fix case when processing column names for MySQL | Fix case when processing column names for MySQL
| Python | mit | sdispater/orator |
0a6078f5d0537cea9f36894b736fa274c3fa3e47 | molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py | molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py | from django import forms
class MediaForm(forms.Form):
zip_file = forms.FileField(label="Zipped Media File")
def clean_data_file(self):
file = self.cleaned_data['data_file']
if file:
extension = file.name.split('.')[-1]
if extension != 'zip':
raise form... | from django import forms
class MediaForm(forms.Form):
zip_file = forms.FileField(label="Zipped Media File")
def clean_zip_file(self):
file = self.cleaned_data['zip_file']
if file:
extension = file.name.split('.')[-1]
if extension != 'zip':
raise forms.... | Fix upload form to only accept .zip files | Fix upload form to only accept .zip files
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo |
8a55e9fac0885c5b6eb21cd8f3da54a105de8010 | sktracker/__init__.py | sktracker/__init__.py | """Object detection and tracking for cell biology
`scikit-learn` is bla bla bla.
Subpackages
-----------
color
Color space conversion.
Utility Functions
-----------------
img_as_float
Convert an image to floating point format, with values in [0, 1].
"""
try:
from .version import __version__
except Imp... | """Object detection and tracking for cell biology
`scikit-learn` is bla bla bla.
Subpackages
-----------
color
Color space conversion.
"""
try:
from .version import __version__
except ImportError:
__version__ = "dev"
import utils
| Fix utils module import mechanism | Fix utils module import mechanism
| Python | bsd-3-clause | bnoi/scikit-tracker,bnoi/scikit-tracker,bnoi/scikit-tracker |
e92fa763729ce68e86da3664ae1a1ed37e3200a5 | ynr/apps/uk_results/serializers.py | ynr/apps/uk_results/serializers.py | from __future__ import unicode_literals
from rest_framework import serializers
from candidates.serializers import MembershipSerializer
from .models import CandidateResult, ResultSet
class CandidateResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CandidateResult
fiel... | from __future__ import unicode_literals
from rest_framework import serializers
from candidates.serializers import MembershipSerializer
from .models import CandidateResult, ResultSet
class CandidateResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CandidateResult
fiel... | Add ballot paper ID to API | Add ballot paper ID to API
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
3c8b3a24978cf757fb3a8cc8660eb4554f183e0f | social_auth/fields.py | social_auth/fields.py | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... | Use get_db_prep_value instead of get_db_prep_save. Closes gh-42 | Use get_db_prep_value instead of get_db_prep_save. Closes gh-42
| Python | bsd-3-clause | WW-Digital/django-social-auth,1st/django-social-auth,vxvinh1511/django-social-auth,limdauto/django-social-auth,michael-borisov/django-social-auth,caktus/django-social-auth,thesealion/django-social-auth,lovehhf/django-social-auth,dongguangming/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,du... |
49b3fe4e334e25c6afaa9ccace72f5c985e761cb | wcontrol/src/models.py | wcontrol/src/models.py | from app import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
name = db.Column(db.String(64), index=True)
email = db.Column(db.String(64), index=... | from app import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
name = db.Column(db.String(64), index=True)
email = db.Column(db.String(64), index... | Modify to fit with PEP8 standard | Modify to fit with PEP8 standard
| Python | mit | pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control |
b54a6353a746d54869a7cadca1bdcfb1e1cd3d51 | moviemanager/models.py | moviemanager/models.py | from django.db import models
class Movie(models.Model):
tmdb_id = models.IntegerField() | from django.contrib.auth.models import User
from django.db import models
class Movie(models.Model):
tmdb_id = models.IntegerField()
score = models.IntegerField()
submitter = models.ForeignKey(User) | Add some extra fields to movie model | Add some extra fields to movie model
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 |
43b077050cd0e914fbe7398f9077e787c496afe4 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django_pandas',
'django_pandas.tests',
),
DATABASES={
... | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django_pandas',
'django_pandas.tests',
),
DATABASES={
... | Add support for django 1.8 by using test runner | Add support for django 1.8 by using test runner
| Python | bsd-3-clause | sternb0t/django-pandas,perpetua1/django-pandas,arcticshores/django-pandas,chrisdev/django-pandas |
894086bda2545fc7d094def6f925b96905920992 | isso/utils/http.py | isso/utils/http.py | # -*- encoding: utf-8 -*-
import socket
try:
import httplib
except ImportError:
import http.client as httplib
from isso.wsgi import urlsplit
class curl(object):
"""Easy to use wrapper around :module:`httplib`. Use as context-manager
so we can close the response properly.
.. code-block:: pytho... | # -*- encoding: utf-8 -*-
import socket
try:
import httplib
except ImportError:
import http.client as httplib
from isso.wsgi import urlsplit
class curl(object):
"""Easy to use wrapper around :module:`httplib`. Use as context-manager
so we can close the response properly.
.. code-block:: pytho... | Fix catch socket timeout and error exceptions | Fix catch socket timeout and error exceptions | Python | mit | jiumx60rus/isso,janusnic/isso,WQuanfeng/isso,mathstuf/isso,janusnic/isso,Mushiyo/isso,posativ/isso,xuhdev/isso,jelmer/isso,princesuke/isso,mathstuf/isso,princesuke/isso,WQuanfeng/isso,jelmer/isso,jelmer/isso,xuhdev/isso,posativ/isso,Mushiyo/isso,jelmer/isso,xuhdev/isso,princesuke/isso,posativ/isso,jiumx60rus/isso,maths... |
0eb20c8025a838d93a5854442640550d5bf05b0b | settings.py | settings.py | #!/usr/bin/env python
"""settings.py
Udacity conference server-side Python App Engine app user settings
$Id$
created/forked from conference.py by wesc on 2014 may 24
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8m... | #!/usr/bin/env python
"""settings.py
Udacity conference server-side Python App Engine app user settings
$Id$
created/forked from conference.py by wesc on 2014 may 24
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8m... | Add android and ios client IDs | Add android and ios client IDs
| Python | apache-2.0 | elbernante/conference-central,elbernante/conference-central,elbernante/conference-central |
0b56e5d8b1da9c5b76a39cead7f4642384750c0a | utils/http.py | utils/http.py | # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2012 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, ... | # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2012 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, ... | Remove the unnecessary and never-used basic auth hack. | Remove the unnecessary and never-used basic auth hack.
| Python | agpl-3.0 | ReachingOut/unisubs,ofer43211/unisubs,ReachingOut/unisubs,ujdhesa/unisubs,eloquence/unisubs,pculture/unisubs,ujdhesa/unisubs,wevoice/wesub,ReachingOut/unisubs,wevoice/wesub,pculture/unisubs,eloquence/unisubs,norayr/unisubs,norayr/unisubs,eloquence/unisubs,pculture/unisubs,wevoice/wesub,ReachingOut/unisubs,pculture/unis... |
5dc69c3e88ab4df897c9a1d632a47de42e5bc9c0 | app.py | app.py | """Module containing factory function for the application"""
from flask import Flask, redirect
from flask_restplus import Api
from config import app_config
from api_v1 import Blueprint_apiV1
from api_v1.models import db
Api_V1 = Api(
app=Blueprint_apiV1,
title="Shopping List Api",
description="An API for... | """Module containing factory function for the application"""
from flask import Flask, redirect
from flask_restplus import Api
from flask_cors import CORS
from config import app_config
from api_v1 import Blueprint_apiV1
from api_v1.models import db
Api_V1 = Api(
app=Blueprint_apiV1,
title="Shopping List Api",... | Enable Cross Origin Resource Sharing | [Update] Enable Cross Origin Resource Sharing
| Python | mit | machariamarigi/shopping_list_api |
2adc021a520baa356c46ad1316893c1cd96f3147 | knights/lexer.py | knights/lexer.py | from enum import Enum
import re
Token = Enum('Token', 'load comment text var block',)
tag_re = re.compile(
'|'.join([
r'{\!\s*(?P<load>.+?)\s*\!}',
r'{%\s*(?P<tag>.+?)\s*%}',
r'{{\s*(?P<var>.+?)\s*}}',
r'{#\s*(?P<comment>.+?)\s*#}'
]),
re.DOTALL
)
def tokenise(template):
... | from enum import Enum
import re
TokenType = Enum('Token', 'load comment text var block',)
tag_re = re.compile(
'|'.join([
r'{\!\s*(?P<load>.+?)\s*\!}',
r'{%\s*(?P<tag>.+?)\s*%}',
r'{{\s*(?P<var>.+?)\s*}}',
r'{#\s*(?P<comment>.+?)\s*#}'
]),
re.DOTALL
)
class Token:
de... | Rework Lexer to use Token object | Rework Lexer to use Token object
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
890860f89e353e6afb45dec06e3617f0f70e1ad7 | examples/basic_datalogger.py | examples/basic_datalogger.py | from pymoku import Moku
from pymoku.instruments import *
import time, logging
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscil... | from pymoku import Moku
from pymoku.instruments import *
import time, logging
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscil... | Remove time.sleep from example, no longer required | Datalogger: Remove time.sleep from example, no longer required
| Python | mit | liquidinstruments/pymoku,benizl/pymoku |
5bb6e416cf7c59b7a5f85b1b0b037df7667d5d88 | staticbuilder/conf.py | staticbuilder/conf.py | from appconf import AppConf
class StaticBuilderConf(AppConf):
BUILD_COMMANDS = []
COLLECT_BUILT = True
INCLUDE_FILES = ['*.css', '*.js']
class Meta:
required = [
'BUILT_ROOT',
]
| from appconf import AppConf
class StaticBuilderConf(AppConf):
BUILD_COMMANDS = []
COLLECT_BUILT = True
INCLUDE_FILES = ['*']
class Meta:
required = [
'BUILT_ROOT',
]
| Include all static files in build by default | Include all static files in build by default
| Python | mit | hzdg/django-ecstatic,hzdg/django-staticbuilder |
a97b557146edfb340ad83fd95838dc2a627ce32f | src/urls.py | src/urls.py |
__author__ = "Individual contributors (see AUTHORS file)"
__date__ = "$DATE$"
__rev__ = "$REV$"
__license__ = "AGPL v.3"
__copyright__ = """
This file is part of ArgCache.
Copyright (c) 2015 by the individual contributors
(see AUTHORS file)
This program is free software: you can redistribute it and/... |
__author__ = "Individual contributors (see AUTHORS file)"
__date__ = "$DATE$"
__rev__ = "$REV$"
__license__ = "AGPL v.3"
__copyright__ = """
This file is part of ArgCache.
Copyright (c) 2015 by the individual contributors
(see AUTHORS file)
This program is free software: you can redistribute it and/... | Fix urlconf to avoid string view arguments to url() | Fix urlconf to avoid string view arguments to url()
| Python | agpl-3.0 | luac/django-argcache,luac/django-argcache |
1ea6a0b43e4b05bdb743b0e2be86174062581d03 | errors.py | errors.py | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = 9
REPOSITORY_NOT_I... | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = 9
REPOSITORY_NOT_I... | Add a new error code | Add a new error code
| Python | lgpl-2.1 | mhl/gib,mhl/gib |
c29f55196f97ef3fa70124628fd94c78b90162ea | python/getmonotime.py | python/getmonotime.py | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
except getopt.GetoptError:
usage()
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if sippy_path != None:
... | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
out_realtime = False
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if o... | Add an option to output both realtime and monotime. | Add an option to output both realtime and monotime.
| Python | bsd-2-clause | synety-jdebp/rtpproxy,dsanders11/rtpproxy,synety-jdebp/rtpproxy,jevonearth/rtpproxy,jevonearth/rtpproxy,synety-jdebp/rtpproxy,sippy/rtpproxy,dsanders11/rtpproxy,jevonearth/rtpproxy,jevonearth/rtpproxy,dsanders11/rtpproxy,sippy/rtpproxy,synety-jdebp/rtpproxy,sippy/rtpproxy |
3f2ab5710fb07a78c5b7f67afb785e9aab5e7695 | evergreen/core/threadpool.py | evergreen/core/threadpool.py | #
# This file is part of Evergreen. See the NOTICE for more information.
#
import pyuv
import sys
from evergreen.event import Event
from evergreen.futures import Future
__all__ = ('ThreadPool')
"""Internal thread pool which uses the pyuv work queuing capability. This module
is for internal use of Evergreen.
"""
c... | #
# This file is part of Evergreen. See the NOTICE for more information.
#
import pyuv
import sys
from evergreen.event import Event
from evergreen.futures import Future
__all__ = ('ThreadPool')
"""Internal thread pool which uses the pyuv work queuing capability. This module
is for internal use of Evergreen.
"""
c... | Break potential cycle because we are storing the traceback | Break potential cycle because we are storing the traceback
| Python | mit | saghul/evergreen,saghul/evergreen |
7ebda7fca01372ae49a8c66812c958fc8200f4b0 | apps/events/filters.py | apps/events/filters.py | import django_filters
from django_filters.filters import Lookup
from apps.events.models import Event
class ListFilter(django_filters.Filter):
# https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702
def filter(self, qs, value):
value_list = value.split(u',')
return su... | import django_filters
from django_filters.filters import Lookup
from apps.events.models import Event
class ListFilter(django_filters.Filter):
# https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702
def filter(self, qs, value):
value_list = value.split(u',')
return su... | Change Django field filter kwarg from name to field_name for Django 2 support | Change Django field filter kwarg from name to field_name for Django 2 support
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
d6a1e13ed6fc1db1d2087ba56fc9130f9ab641f9 | tests/__init__.py | tests/__init__.py | from __future__ import unicode_literals
import os
import sys
def path_to_data_dir(name):
if not isinstance(name, bytes):
name = name.encode(sys.getfilesystemencoding())
path = os.path.dirname(__file__)
path = os.path.join(path, b'data')
path = os.path.abspath(path)
return os.path.join(pat... | from __future__ import unicode_literals
import os
def path_to_data_dir(name):
if not isinstance(name, bytes):
name = name.encode('utf-8')
path = os.path.dirname(__file__)
path = os.path.join(path, b'data')
path = os.path.abspath(path)
return os.path.join(path, name)
class IsA(object):
... | Use utf-8 when encoding our test data paths to bytes | tests: Use utf-8 when encoding our test data paths to bytes
| Python | apache-2.0 | rawdlite/mopidy,jcass77/mopidy,SuperStarPL/mopidy,jcass77/mopidy,bencevans/mopidy,jmarsik/mopidy,vrs01/mopidy,jcass77/mopidy,ali/mopidy,pacificIT/mopidy,tkem/mopidy,jodal/mopidy,diandiankan/mopidy,tkem/mopidy,adamcik/mopidy,vrs01/mopidy,mokieyue/mopidy,adamcik/mopidy,bencevans/mopidy,swak/mopidy,swak/mopidy,ali/mopidy,... |
fbd99212c7af806137f996ac3c1d6c018f9402a7 | puffin/core/compose.py | puffin/core/compose.py | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... | from .applications import get_application_domain, get_application_name
from .machine import get_env_vars
from .. import app
from subprocess import Popen, STDOUT, PIPE
from os import environ
from os.path import join
def init():
pass
def compose_start(machine, user, application, **environment):
compose_run(ma... | Add Let's Encrypt env var | Add Let's Encrypt env var
| Python | agpl-3.0 | puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin,loomchild/puffin,loomchild/jenca-puffin |
abfc91a687b33dda2659025af254bc9f50c077b5 | publishers/migrations/0008_fix_name_indices.py | publishers/migrations/0008_fix_name_indices.py | # Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='... | # Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',... | Mark index migration as non atomic | Mark index migration as non atomic
| Python | agpl-3.0 | dissemin/dissemin,wetneb/dissemin,wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin |
95c7037a4a1e9c3921c3b4584046824ed469ae7f | osfclient/tests/test_session.py | osfclient/tests/test_session.py | from osfclient.models import OSFSession
def test_basic_auth():
session = OSFSession()
session.basic_auth('joe@example.com', 'secret_password')
assert session.auth == ('joe@example.com', 'secret_password')
assert 'Authorization' not in session.headers
def test_basic_build_url():
session = OSFSess... | from unittest.mock import patch
from unittest.mock import MagicMock
import pytest
from osfclient.models import OSFSession
from osfclient.exceptions import UnauthorizedException
def test_basic_auth():
session = OSFSession()
session.basic_auth('joe@example.com', 'secret_password')
assert session.auth == (... | Add test for osfclient's session object | Add test for osfclient's session object
Check that exceptions are raised on unauthed HTTP put/get
| Python | bsd-3-clause | betatim/osf-cli,betatim/osf-cli |
8febff1065c67db1599f6b9bccd27f843981dd95 | main/management/commands/poll_rss.py | main/management/commands/poll_rss.py |
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url i... |
from datetime import datetime
from time import mktime
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from mezzanine.generic.models import Rating
from ...models import Link... | Add an initial rating to new links in the rss seeder. | Add an initial rating to new links in the rss seeder.
| Python | bsd-2-clause | tsybulevskij/drum,j00bar/drum,j00bar/drum,yodermk/drum,skybluejamie/wikipeace,yodermk/drum,renyi/drum,sing1ee/drum,yodermk/drum,renyi/drum,tsybulevskij/drum,stephenmcd/drum,sing1ee/drum,j00bar/drum,stephenmcd/drum,abendig/drum,tsybulevskij/drum,renyi/drum,skybluejamie/wikipeace,abendig/drum,sing1ee/drum,abendig/drum |
a3d404a7f7352fd85a821b445ebeb8d7ca9b21c9 | sigma_core/serializers/group.py | sigma_core/serializers/group.py | from rest_framework import serializers
from sigma_core.models.group import Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
| from rest_framework import serializers
from sigma_core.models.group import Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
visibility = serializers.SerializerMethodField()
membership_policy = serializers.SerializerMethodField()
validation_policy = seri... | Change GroupSerializer to display attributes as strings | Change GroupSerializer to display attributes as strings
| Python | agpl-3.0 | ProjetSigma/backend,ProjetSigma/backend |
ab25537b67b14a8574028280c1e16637faa8037c | gunicorn/workers/gtornado.py | gunicorn/workers/gtornado.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn import __version__... | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
import tornado.web
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop, PeriodicCallback
from gunicorn.workers.base import Worker
from gunicorn... | Fix assumption that tornado.web was imported. | Fix assumption that tornado.web was imported.
| Python | mit | mvaled/gunicorn,wong2/gunicorn,prezi/gunicorn,elelianghh/gunicorn,wong2/gunicorn,WSDC-NITWarangal/gunicorn,MrKiven/gunicorn,mvaled/gunicorn,alex/gunicorn,1stvamp/gunicorn,z-fork/gunicorn,1stvamp/gunicorn,ephes/gunicorn,prezi/gunicorn,gtrdotmcs/gunicorn,tejasmanohar/gunicorn,urbaniak/gunicorn,gtrdotmcs/gunicorn,prezi/gu... |
dd5774c30f950c8a52b977a5529300e8edce4bc7 | migrations/versions/2c240cb3edd1_.py | migrations/versions/2c240cb3edd1_.py | """Add movie metadata (imdb rating, number of votes, metascore) and relevancy
Revision ID: 2c240cb3edd1
Revises: 588336e02ca
Create Date: 2014-02-09 13:46:18.630000
"""
# revision identifiers, used by Alembic.
revision = '2c240cb3edd1'
down_revision = '588336e02ca'
from alembic import op
import sqlalchemy as sa
d... | """Add movie metadata (imdb rating, number of votes, metascore) and relevancy
Revision ID: 2c240cb3edd1
Revises: 588336e02ca
Create Date: 2014-02-09 13:46:18.630000
"""
# revision identifiers, used by Alembic.
revision = '2c240cb3edd1'
down_revision = '588336e02ca'
from alembic import op
import sqlalchemy as sa
d... | Fix proper default values for metadata migration | Fix proper default values for metadata migration
| Python | mit | streamr/marvin,streamr/marvin,streamr/marvin |
1e148822b4611403add32154fbe47bc8775f8001 | py/garage/garage/sql/sqlite.py | py/garage/garage/sql/sqlite.py | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(db_uri, check_same_thread=False, echo=False):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for... | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(db_uri, check_same_thread=False, echo=False):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for... | Enable foreign key constraint for SQLite | Enable foreign key constraint for SQLite
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage |
7e2835f76474f6153d8972a983c5d45f9c4f11ee | tests/Physics/TestLight.py | tests/Physics/TestLight.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal
from UliEngineering.Physics.Light import *
from UliEngineering.EngineerIO import auto_format
import unittest
class TestJohnsonNyquistNoise(unittest.TestCase):
def test_lumen_to_candela_by_apex_angle(self):
v = lume... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal
from UliEngineering.Physics.Light import *
from UliEngineering.EngineerIO import auto_format
import unittest
class TestLight(unittest.TestCase):
def test_lumen_to_candela_by_apex_angle(self):
v = lumen_to_candela_b... | Fix badly named test class | Fix badly named test class
| Python | apache-2.0 | ulikoehler/UliEngineering |
e2c9d39dd30a60c5c54521d7d11773430cae1bd1 | tests/test_image_access.py | tests/test_image_access.py | import pytest
import imghdr
from io import BytesIO
from PIL import Image
from pikepdf import _qpdf as qpdf
def test_jpeg(resources, outdir):
pdf = qpdf.Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pdf.pag... | import pytest
import imghdr
from io import BytesIO
from PIL import Image
import zlib
from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
pdf = Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pd... | Add manual experiment that replaces a RGB image with grayscale | Add manual experiment that replaces a RGB image with grayscale
| Python | mpl-2.0 | pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf |
cebd4d613cc95ef6e775581a6f77f4850e39020a | src/mdformat/_conf.py | src/mdformat/_conf.py | from __future__ import annotations
import functools
from pathlib import Path
from typing import Mapping
import tomli
DEFAULT_OPTS = {
"wrap": "keep",
"number": False,
"end_of_line": "lf",
}
class InvalidConfError(Exception):
"""Error raised given invalid TOML or a key that is not valid for
mdfo... | from __future__ import annotations
import functools
from pathlib import Path
from typing import Mapping
import tomli
DEFAULT_OPTS = {
"wrap": "keep",
"number": False,
"end_of_line": "lf",
}
class InvalidConfError(Exception):
"""Error raised given invalid TOML or a key that is not valid for
mdfo... | Improve error message on invalid conf key | Improve error message on invalid conf key
| Python | mit | executablebooks/mdformat |
20151a50424bbb6c4edcab5f19b97e3d7fb838b9 | plugins/GCodeReader/__init__.py | plugins/GCodeReader/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... | Change plugin type to profile_reader | Change plugin type to profile_reader
This repairs the profile reading at startup. It should not be a mesh reader.
Contributes to issue CURA-34.
| Python | agpl-3.0 | Curahelper/Cura,fieldOfView/Cura,hmflash/Cura,ynotstartups/Wanhao,hmflash/Cura,senttech/Cura,Curahelper/Cura,ynotstartups/Wanhao,fieldOfView/Cura,totalretribution/Cura,totalretribution/Cura,senttech/Cura |
715098531f823c3b2932e6a03d2e4b113bd53ed9 | tests/test_grammar.py | tests/test_grammar.py | import viper.grammar as vg
import viper.grammar.languages as vgl
import viper.lexer as vl
import pytest
@pytest.mark.parametrize('line,sppf', [
('foo',
vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))),
('2',
vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))),
('...',
vgl.SPPF(vgl.ParseTreeChar(vl.Op... | import viper.grammar as vg
import viper.lexer as vl
from viper.grammar.languages import (
SPPF,
ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR
)
import pytest
@pytest.mark.parametrize('line,sppf', [
('foo',
SPPF(PTC(vl.Name('foo')))),
('42',
SPPF(PTC... | Revise grammar tests for atom | Revise grammar tests for atom
| Python | apache-2.0 | pdarragh/Viper |
94529f62757886d2291cf90596a179dc2d0b6642 | yutu.py | yutu.py | import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.... | import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.... | Make cute respect guild nicknames | Make cute respect guild nicknames
| Python | mit | HarkonenBade/yutu |
694a3e1aa5eec02e81cfde517ca126f00b21bd2f | rest_framework_docs/api_docs.py | rest_framework_docs/api_docs.py | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import... | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
... | Use Django's module loading rather than __import__ | Use Django's module loading rather than __import__
__import__ doesn't deal well with dotted paths, in my instance my root url conf is in a few levels "appname.config.urls". unfortunately, for __import__ this means that just `appname` is imported, but `config.urls` is loaded and no other modules in between are usable. ... | Python | bsd-2-clause | manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,manosim/django-rest-framework-docs |
6ece85c530d9856a7db650729e57a9f2a92dfa4b | oscar/apps/offer/managers.py | oscar/apps/offer/managers.py | import datetime
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating ACTIVE offers only.
"""
def get_query_set(self):
today = datetime.date.today()
return super(ActiveOfferManager, self).get_query_set().filter(
start_date__lte=t... | import datetime
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating offers within their date range
"""
def get_query_set(self):
today = datetime.date.today()
return super(ActiveOfferManager, self).get_query_set().filter(
start_... | Fix queryset filtering for active offers | Fix queryset filtering for active offers
| Python | bsd-3-clause | sasha0/django-oscar,thechampanurag/django-oscar,ka7eh/django-oscar,elliotthill/django-oscar,eddiep1101/django-oscar,john-parton/django-oscar,adamend/django-oscar,nfletton/django-oscar,jmt4/django-oscar,pdonadeo/django-oscar,bschuon/django-oscar,sonofatailor/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,Willis... |
6e1337f7079ba48aafcde59e4d5806caabb0bc29 | navigation_extensions.py | navigation_extensions.py | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, *... | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, *... | Stop hard-coding the navigation level in the extension | Stop hard-coding the navigation level in the extension
| Python | mit | matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz |
8608283592338960c80113ff4d68f42936ddb969 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Gregory Oschwald
# Copyright (c) 2013 Gregory Oschwald
#
# License: MIT
#
"""This module exports the Perl plugin class."""
import shlex
from SublimeLinter.lint import Linter, util
class Perl(Linter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Gregory Oschwald
# Copyright (c) 2013 Gregory Oschwald
#
# License: MIT
#
"""This module exports the Perl plugin class."""
import shlex
from SublimeLinter.lint import Linter, util
class Perl(Linter):
"""Provi... | Clean up include dir code | Clean up include dir code
| Python | mit | oschwald/SublimeLinter-perl |
6d91ed53a15672b1e70d74691158e9afb7162e74 | src/etcd/__init__.py | src/etcd/__init__.py | import collections
from client import Client
class EtcdResult(collections.namedtuple(
'EtcdResult',
[
'action',
'index',
'key',
'prevValue',
'value',
'expiration',
'ttl',
'newKey'])):
def __new__(
cls,
action=None,
... | import collections
from client import Client
class EtcdResult(collections.namedtuple(
'EtcdResult',
[
'action',
'index',
'key',
'prevValue',
'value',
'expiration',
'ttl',
'newKey'])):
def __new__(
cls,
action=None,
... | Add optional support for SSL SNI | Add optional support for SSL SNI
| Python | mit | dmonroy/python-etcd,ocadotechnology/python-etcd,thepwagner/python-etcd,dmonroy/python-etcd,jlamillan/python-etcd,ocadotechnology/python-etcd,aziontech/python-etcd,jplana/python-etcd,sentinelleader/python-etcd,vodik/python-etcd,projectcalico/python-etcd,j-mcnally/python-etcd,j-mcnally/python-etcd,mbrukman/python-etcd,az... |
84deb31cc2bdbf30d8b6f30725a3eaaccd1dd903 | ade25/assetmanager/browser/repository.py | ade25/assetmanager/browser/repository.py | # -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.blob.interfaces import IATBlobImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, ui... | # -*- coding: utf-8 -*-
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
from plone.app.contenttypes.interfaces import IImage
class AssetRepositoryView(BrowserView):
""" Folderish content page default view """
def contained_items(self, u... | Use newer interface for filtering | Use newer interface for filtering
The image provided by `plone.app.contenttypes` does reintroduce the global
IImage identifier lost during the transition to dexterity based types
| Python | mit | ade25/ade25.assetmanager |
1dd257b157cfcb13a13a9c97ff6580045026118c | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description... | # -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description... | Change the order when loading xml data | Change the order when loading xml data
| Python | agpl-3.0 | xcgd/account_streamline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.