commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
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 | ---
+++
@@ -18,6 +18,10 @@
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
+ # Enable foreign key.
+ cursor = dbapi_connection.cursor()
+ cursor.execute("PRAGMA foreign_keys = ON")
+ cursor.clos... |
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 | ---
+++
@@ -5,7 +5,7 @@
from UliEngineering.EngineerIO import auto_format
import unittest
-class TestJohnsonNyquistNoise(unittest.TestCase):
+class TestLight(unittest.TestCase):
def test_lumen_to_candela_by_apex_angle(self):
v = lumen_to_candela_by_apex_angle("25 lm", "120°")
assert_approx_... |
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 | ---
+++
@@ -2,21 +2,39 @@
import imghdr
from io import BytesIO
from PIL import Image
+import zlib
-from pikepdf import _qpdf as qpdf
+from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
- pdf = qpdf.Pdf.open(resources / 'congress.pdf')
+ pdf = Pdf.open(resources / 'congress.pdf')
# ... |
6874ff82ddf5e9d803a45676c45d83be65ad3b33 | core/app.py | core/app.py | import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'frontend/templates'
)
static_directory = 'frontend/static'
app = Flask(__name__, template_folder=template_directory, s... | import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'../frontend/templates'
)
static_directory = '../frontend/static'
app = Flask(__name__, template_folder=template_direct... | Fix template and static paths | Fix template and static paths
| Python | mit | LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr | ---
+++
@@ -6,9 +6,9 @@
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
- 'frontend/templates'
+ '../frontend/templates'
)
-static_directory = 'frontend/static'
+static_directory = '../frontend/static'
app = Flask(__name__, template_folder=template_directory, static_fo... |
f5fe10907d1ecffb89f62a56e8b7f8e34f4fcf2a | urls.py | urls.py | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... | Make catch-all actually catch all | Make catch-all actually catch all
| Python | bsd-3-clause | willmurnane/store | ---
+++
@@ -14,5 +14,5 @@
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
- (r'^/', 'store.views.frontpage'),
+ (r'', 'store.views.frontpage'),
) |
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 | ---
+++
@@ -35,6 +35,9 @@
for key in toml_opts:
if key not in DEFAULT_OPTS:
- raise InvalidConfError(f"Invalid key {key!r} in {conf_path}")
+ raise InvalidConfError(
+ f"Invalid key {key!r} in {conf_path}."
+ f" Keys must be one of {set(DEFAULT_OPTS)... |
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 | ---
+++
@@ -15,13 +15,11 @@
"description": catalog.i18nc("@info:whatsthis", "Provides support for reading GCode files."),
"api": 2
},
- "mesh_reader": [
- {
- "extension": "gcode",
- "description": catalog.i18nc("@item:inlistbox", "Gco... |
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 | ---
+++
@@ -1,25 +1,37 @@
import viper.grammar as vg
-import viper.grammar.languages as vgl
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... |
eca9ee90bf64b14c6a8eacdb4197825790ab7825 | tests/test_helpers.py | tests/test_helpers.py | """
Tests for the NURBS-Python package
Released under The MIT License. See LICENSE file for details.
Copyright (c) 2018 Onur Rauf Bingol
Tests geomdl.helpers module.
"""
from geomdl import helpers
GEOMDL_DELTA = 10e-8
def test_basis_function_one():
degree = 2
knot_vector = [0, 0, 0, 1, 2, 3, 4, 4,... | Add tests for A2.4 and A2.5 | Add tests for A2.4 and A2.5
| Python | mit | orbingol/NURBS-Python,orbingol/NURBS-Python | ---
+++
@@ -0,0 +1,33 @@
+"""
+ Tests for the NURBS-Python package
+ Released under The MIT License. See LICENSE file for details.
+ Copyright (c) 2018 Onur Rauf Bingol
+
+ Tests geomdl.helpers module.
+"""
+
+from geomdl import helpers
+
+GEOMDL_DELTA = 10e-8
+
+def test_basis_function_one():
+ degree = ... | |
99683d16551450686397f953668b7d6bf4167a5e | tests/test_methods.py | tests/test_methods.py | import interleaving as il
import numpy as np
np.random.seed(0)
class TestMethods(object):
def assert_almost_equal(self, a, b, error_rate=0.1):
half_error_rate = error_rate / 2.0
lower_bound = (1.0 - half_error_rate) * a
upper_bound = (1.0 + half_error_rate) * a
assert lower_bound <... | import interleaving as il
import numpy as np
np.random.seed(0)
class TestMethods(object):
def assert_almost_equal(self, a, b, error_rate=0.1):
half_error_rate = error_rate / 2.0
lower_bound = (1.0 - half_error_rate) * a
upper_bound = (1.0 + half_error_rate) * a
assert lower_bound <... | Add a length argument in TestMethods.interleave | Add a length argument in TestMethods.interleave
| Python | mit | mpkato/interleaving | ---
+++
@@ -10,10 +10,10 @@
upper_bound = (1.0 + half_error_rate) * a
assert lower_bound <= b and b <= upper_bound
- def interleave(self, method, a, b, ideals, num=100):
+ def interleave(self, method, k, a, b, ideals, num=100):
results = []
for i in range(num):
- ... |
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 | ---
+++
@@ -23,7 +23,7 @@
else:
first = ctx.author
second = member
- post = discord.Embed(description='**{0.name}** thinks that **{1.name}** is cute!'.format(first, second))
+ post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, s... |
f8a42dc715c55d1f3faf3dd87d168e0687f87e5b | l10n_ch_payment_slip/report/__init__.py | l10n_ch_payment_slip/report/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | Add common in import statement | Add common in import statement
| Python | agpl-3.0 | BT-ojossen/l10n-switzerland,cgaspoz/l10n-switzerland,CompassionCH/l10n-switzerland,BT-csanchez/l10n-switzerland,CompassionCH/l10n-switzerland,BT-fgarbely/l10n-switzerland,BT-ojossen/l10n-switzerland,BT-fgarbely/l10n-switzerland,cyp-opennet/ons_cyp_github,open-net-sarl/l10n-switzerland,open-net-sarl/l10n-switzerland,cyp... | ---
+++
@@ -29,3 +29,4 @@
#
##############################################################################
from . import payment_slip_from_invoice
+from . import reports_common |
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 | ---
+++
@@ -1,5 +1,6 @@
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
@@ -8,7 +9,7 @@
def __in... |
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... | ---
+++
@@ -5,9 +5,9 @@
class ActiveOfferManager(models.Manager):
"""
- For searching/creating ACTIVE offers only.
+ For searching/creating offers within their date range
"""
def get_query_set(self):
today = datetime.date.today()
return super(ActiveOfferManager, self).get_que... |
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 | ---
+++
@@ -14,31 +14,31 @@
PagePretender(
title=capfirst(_('drudges')),
url='%sdrudges/' % url,
- level=3,
+ level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=c... |
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 | ---
+++
@@ -20,7 +20,7 @@
syntax = ('modernperl', 'perl')
executable = 'perl'
- base_cmd = ('perl -c')
+
regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?'
error_stream = util.STREAM_STDERR
@@ -33,14 +33,12 @@
"""
- full_cmd = self.base_cmd
+ ... |
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... | ---
+++
@@ -42,3 +42,11 @@
"""
pass
+
+# Attempt to enable urllib3's SNI support, if possible
+# Blatantly copied from requests.
+try:
+ from urllib3.contrib import pyopenssl
+ pyopenssl.inject_into_urllib3()
+except ImportError:
+ pass |
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 | ---
+++
@@ -2,8 +2,7 @@
"""Module providing views for asset storage folder"""
from Products.Five.browser import BrowserView
from plone import api
-from plone.app.blob.interfaces import IATBlobImage
-
+from plone.app.contenttypes.interfaces import IImage
class AssetRepositoryView(BrowserView):
""" Folderish... |
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 | ---
+++
@@ -30,8 +30,8 @@
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
+ 'account_move_line_journal_view.xml',
'account_menu_entries.xml',
- 'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/... |
ed491860864c363be36d99c09ff0131a5fe00aaf | test/Driver/Dependencies/Inputs/touch.py | test/Driver/Dependencies/Inputs/touch.py | #!/usr/bin/env python
# touch.py - /bin/touch that writes the LLVM epoch -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LI... | #!/usr/bin/env python
# touch.py - /bin/touch that writes the LLVM epoch -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LI... | Fix tests for file timestamps to drop the LLVM epoch offset. | Fix tests for file timestamps to drop the LLVM epoch offset.
Now that Swift is not using LLVM's TimeValue (564fc6f2 and previous commit)
there is no offset from the system_clock epoch. The offset could be added
into the tests that use touch.py (so the times would not be back in 1984)
but I decided not to do that to av... | Python | apache-2.0 | aschwaighofer/swift,tinysun212/swift-windows,arvedviehweger/swift,xwu/swift,airspeedswift/swift,parkera/swift,tinysun212/swift-windows,JGiola/swift,JaSpa/swift,JGiola/swift,parkera/swift,zisko/swift,hughbe/swift,codestergit/swift,CodaFi/swift,rudkx/swift,huonw/swift,tkremenek/swift,jtbandes/swift,codestergit/swift,prac... | ---
+++
@@ -11,7 +11,7 @@
#
# ----------------------------------------------------------------------------
#
-# Like /bin/touch, but takes a time using the LLVM epoch.
+# Like /bin/touch, but takes a time using the system_clock epoch.
#
# --------------------------------------------------------------------------... |
2da44025051e6a0c0bffe4dba25ed7084e7ae277 | test/connect_remote/TestConnectRemote.py | test/connect_remote/TestConnectRemote.py | """
Test lldb 'process connect' command.
"""
import os
import unittest2
import lldb
import pexpect
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
@unittest2.expectedFailure
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"... | """
Test lldb 'process connect' command.
"""
import os
import unittest2
import lldb
import pexpect
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
# First, we'll st... | Test case test_connect_remote() has been passing consistently for some times. Let's remove the @expectedFailure marker from it. | Test case test_connect_remote() has been passing consistently for some times.
Let's remove the @expectedFailure marker from it.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@133294 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb | ---
+++
@@ -12,7 +12,6 @@
mydir = "connect_remote"
- @unittest2.expectedFailure
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
|
642908032012baf200ab227803982730c6d4b083 | stdnum/ca/__init__.py | stdnum/ca/__init__.py | # __init__.py - collection of Canadian numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library 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,... | # __init__.py - collection of Canadian numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library 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,... | Add missing vat alias for Canada | Add missing vat alias for Canada
| Python | lgpl-2.1 | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum | ---
+++
@@ -19,3 +19,4 @@
# 02110-1301 USA
"""Collection of Canadian numbers."""
+from stdnum.ca import bn as vat # noqa: F401 |
c2859bd8da741862ee01a276a1350fb4a5931dbc | data_access.py | data_access.py | #!/usr/bin/env python
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...... | #!/usr/bin/env python
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
... | Change data access script to issue SELECTs that actually return a value | Change data access script to issue SELECTs that actually return a value
This makes the part about tracing the SQL statements and tracing the
number of rows returned a little more interesting.
| Python | mit | goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop | ---
+++
@@ -1,7 +1,10 @@
#!/usr/bin/env python
+from random import randint
import sys
import mysql.connector
+
+NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
@@ -13,7 +16,7 @@
cursor.close()
print("Inserting employees...")
- for n in xrange(0, 10000):
+ for n in xrang... |
b0d8280927bdd33cfb16da2782ca54100a5ece09 | py/dynesty/__init__.py | py/dynesty/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
dynesty is nested sampling package.
The main functionality of dynesty is performed by the
dynesty.NestedSampler and dynesty.DynamicNestedSampler
classes
"""
from .dynesty import NestedSampler, DynamicNestedSampler
from . import bounding
from . import utils
__version__ ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
dynesty is nested sampling package.
The main functionality of dynesty is performed by the
dynesty.NestedSampler and dynesty.DynamicNestedSampler
classes
"""
from .dynesty import NestedSampler, DynamicNestedSampler
from . import bounding
from . import utils
__version__ ... | Change the version to 1.2.0 | Change the version to 1.2.0
| Python | mit | joshspeagle/dynesty | ---
+++
@@ -10,4 +10,4 @@
from . import bounding
from . import utils
-__version__ = "1.2"
+__version__ = "1.2.0" |
807d7efe7de00950df675e78249dcada298b6cd1 | systemrdl/__init__.py | systemrdl/__init__.py | from .__about__ import __version__
from .compiler import RDLCompiler
from .walker import RDLListener, RDLWalker
from .messages import RDLCompileError
| from .__about__ import __version__
from .compiler import RDLCompiler
from .walker import RDLListener, RDLWalker
from .messages import RDLCompileError
from .node import AddressableNode, VectorNode, SignalNode
from .node import FieldNode, RegNode, RegfileNode, AddrmapNode, MemNode
from .component import AddressableCom... | Bring forward more contents into top namespace | Bring forward more contents into top namespace
| Python | mit | SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler | ---
+++
@@ -1,4 +1,11 @@
from .__about__ import __version__
+
from .compiler import RDLCompiler
from .walker import RDLListener, RDLWalker
from .messages import RDLCompileError
+
+from .node import AddressableNode, VectorNode, SignalNode
+from .node import FieldNode, RegNode, RegfileNode, AddrmapNode, MemNode
+
+... |
ccb90932cf967190029b3ce9494a1fd9e6cb889a | gaphor/UML/classes/tests/test_propertypages.py | gaphor/UML/classes/tests/test_propertypages.py | from gi.repository import Gtk
from gaphor import UML
from gaphor.UML.classes import ClassItem
from gaphor.UML.classes.classespropertypages import ClassAttributes
class TestClassPropertyPages:
def test_attribute_editing(self, case):
class_item = case.create(ClassItem, UML.Class)
model = ClassAttri... | from gi.repository import Gtk
from gaphor import UML
from gaphor.UML.classes import ClassItem, EnumerationItem
from gaphor.UML.classes.classespropertypages import (
ClassAttributes,
ClassEnumerationLiterals,
)
def test_attribute_editing(case):
class_item = case.create(ClassItem, UML.Class)
model = Cl... | Add test for enumeration editing | Add test for enumeration editing
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -1,17 +1,30 @@
from gi.repository import Gtk
from gaphor import UML
-from gaphor.UML.classes import ClassItem
-from gaphor.UML.classes.classespropertypages import ClassAttributes
+from gaphor.UML.classes import ClassItem, EnumerationItem
+from gaphor.UML.classes.classespropertypages import (
+ Class... |
5747284df86016958ab1ae9dcf437b375e79beba | xbob/core/__init__.py | xbob/core/__init__.py | from ._convert import convert
from . import log
from . import random
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return __import__('pkg_resources').resource_f... | from ._convert import convert
from . import log
from . import random
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return __import__('pkg_resources').resource_f... | Add function to print comprehensive dependence list | Add function to print comprehensive dependence list
| Python | bsd-3-clause | tiagofrepereira2012/bob.core,tiagofrepereira2012/bob.core,tiagofrepereira2012/bob.core | ---
+++
@@ -10,5 +10,24 @@
return __import__('pkg_resources').resource_filename(__name__, 'include')
+def get_config():
+ """Returns a string containing the configuration information.
+ """
+
+ import pkg_resources
+ from .version import externals
+
+ packages = pkg_resources.require(__name__)
+ this = p... |
f68e8cb9751a32cc4d8bdc97c6f753395381e1e1 | python/dnest4/utils.py | python/dnest4/utils.py | # -*- coding: utf-8 -*-
__all__ = ["randh", "wrap"]
import numpy as np
import numpy.random as rng
def randh():
"""
Generate from the heavy-tailed distribution.
"""
return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn()
def wrap(x, a, b):
assert b > a
return (x - a... | # -*- coding: utf-8 -*-
__all__ = ["randh", "wrap"]
import numpy as np
import numpy.random as rng
def randh(N=1):
"""
Generate from the heavy-tailed distribution.
"""
if N==1:
return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn()
return 10.0**(1.5 - 3*np.abs(rng.... | Allow N > 1 randhs to be generated | Allow N > 1 randhs to be generated
| Python | mit | eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4,eggplantbren/DNest4 | ---
+++
@@ -4,11 +4,14 @@
import numpy as np
import numpy.random as rng
-def randh():
+def randh(N=1):
"""
Generate from the heavy-tailed distribution.
"""
- return 10.0**(1.5 - 3*np.abs(rng.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn()
+ if N==1:
+ return 10.0**(1.5 - 3*np.abs(rng.r... |
6d7d04b095eacb413b07ebcb3fed9684dc40fc80 | utils/gyb_syntax_support/protocolsMap.py | utils/gyb_syntax_support/protocolsMap.py | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList'... | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList'... | Add convenience initializer for `BinaryOperatorExpr` | [SwiftSyntax] Add convenience initializer for `BinaryOperatorExpr`
| Python | apache-2.0 | atrick/swift,atrick/swift,apple/swift,rudkx/swift,benlangmuir/swift,roambotics/swift,rudkx/swift,glessard/swift,atrick/swift,ahoppen/swift,glessard/swift,JGiola/swift,atrick/swift,ahoppen/swift,ahoppen/swift,apple/swift,glessard/swift,JGiola/swift,rudkx/swift,rudkx/swift,atrick/swift,roambotics/swift,apple/swift,roambo... | ---
+++
@@ -22,5 +22,8 @@
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
+ ],
+ 'TokenSyntax': [
+ 'BinaryOperatorExpr'
]
} |
93b4fd9c6d2c7b113551d1f6f565c7fffc66b5e2 | astral/conf/global_settings.py | astral/conf/global_settings.py | import logging
import logging.handlers
DEBUG = True
LOG_FORMAT = '[%(asctime)s: %(levelname)s] %(message)s'
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.WARN
LOG_COLOR = True
PORT = 8000
TORNADO_SETTINGS = {}
TORNADO_SETTINGS['debug'] = DEBUG
TORNADO_SETTINGS['xsrf_cookies'] = False
TORNADO... | import logging
import logging.handlers
DEBUG = True
LOG_FORMAT = '[%(asctime)s: %(levelname)s] %(message)s'
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.WARN
LOG_COLOR = True
PORT = 8000
TORNADO_SETTINGS = {}
TORNADO_SETTINGS['debug'] = DEBUG
TORNADO_SETTINGS['xsrf_cookies'] = False
TORNADO... | Use Heroku instance of webapp if not in DEBUG mode. | Use Heroku instance of webapp if not in DEBUG mode.
| Python | mit | peplin/astral | ---
+++
@@ -34,7 +34,11 @@
'use_syslog': USE_SYSLOG,
}
-ASTRAL_WEBSERVER = "http://localhost:4567"
+if DEBUG:
+ ASTRAL_WEBSERVER = "http://localhost:4567"
+else:
+ ASTRAL_WEBSERVER = "http://astral-video.heroku.com"
+
BOOTSTRAP_NODES = [
]
|
4fa21d91ada4df904fc8fdddff608fc40c49aaee | reviewboard/accounts/urls.py | reviewboard/accounts/urls.py | from __future__ import unicode_literals
from django.conf.urls import patterns, url
from reviewboard.accounts.views import MyAccountView
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$... | from __future__ import unicode_literals
from django.conf.urls import patterns, url
from reviewboard.accounts.views import MyAccountView
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$... | Change 'password_reset_done' URL name to 'password_reset_complete' | Change 'password_reset_done' URL name to 'password_reset_complete'
The built-in password reset views use a different name for the last page in the
flow than we did before, and somehow we never noticed this until recently.
Trivial fix.
Fixes bug 3345.
| Python | mit | reviewboard/reviewboard,custode/reviewboard,1tush/reviewboard,brennie/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,1tush/reviewboard,custode/reviewboard,chipx86/reviewboard,beol/reviewboard,reviewboard/reviewboard,1tush/reviewboard,custode/reviewboard,1tush/reviewboard,davidt/reviewbo... | ---
+++
@@ -31,7 +31,7 @@
},
name='recover'),
url(r'^recover/done/$',
- 'password_reset_done',
+ 'password_reset_complete',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<toke... |
62bdb6f2a6df565119661cf2ba1517d19126e26a | member.py | member.py | #!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
__tablename__ = 'member'
id = ... | #!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Member(Base):
__tablename__ = 'member'
id = ... | Make globalName nullable for now. | Make globalName nullable for now.
| Python | agpl-3.0 | dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph | ---
+++
@@ -12,7 +12,7 @@
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
- globalName = Column(String(250), nullable=False)
+ globalName = Column(String(250), nullable=True)
nickname = Column(String(250), nullable=True)
role = Column(String(250), nullable=True)
points... |
9fb89c7e76bd3c6db5f7283b91a2852225056b40 | tests/test_analyse.py | tests/test_analyse.py | """Test analysis page."""
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
| """Test analysis page."""
import pytest
import webtest.app
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body... | Test analyse page checks domain validity | Test analyse page checks domain validity
| Python | unlicense | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | ---
+++
@@ -1,4 +1,6 @@
"""Test analysis page."""
+import pytest
+import webtest.app
def test_analysis(webapp):
@@ -7,3 +9,10 @@
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
+
+
+def test_bad_domain_fails(webapp):
+ """Test the a... |
323b201b8a498402d9f45cbc5cbac049299feea8 | api/bots/incrementor/incrementor.py | api/bots/incrementor/incrementor.py | # See readme.md for instructions on running this code.
class IncrementorHandler(object):
def __init__(self):
self.number = 0
self.message_id = None
def usage(self):
return '''
This is a boilerplate bot that makes use of the
update_message function. For the first @-men... | # See readme.md for instructions on running this code.
class IncrementorHandler(object):
def usage(self):
return '''
This is a boilerplate bot that makes use of the
update_message function. For the first @-mention, it initially
replies with one message containing a `1`. Every time... | Adjust Incrementor bot to use StateHandler | Bots: Adjust Incrementor bot to use StateHandler
| Python | apache-2.0 | jackrzhang/zulip,zulip/zulip,Galexrt/zulip,eeshangarg/zulip,kou/zulip,brainwane/zulip,timabbott/zulip,verma-varsha/zulip,vabs22/zulip,mahim97/zulip,verma-varsha/zulip,hackerkid/zulip,rishig/zulip,zulip/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,jackrzhang/zulip,punchagan/zulip,timabbott/zulip,hackerkid/zulip,punch... | ---
+++
@@ -2,10 +2,6 @@
class IncrementorHandler(object):
-
- def __init__(self):
- self.number = 0
- self.message_id = None
def usage(self):
return '''
@@ -16,14 +12,17 @@
'''
def handle_message(self, message, bot_handler, state_handler):
- self.number +=... |
ffc7f4e87da72866ce391f78084385eac3485049 | src/dicomweb_client/__init__.py | src/dicomweb_client/__init__.py | __version__ = '0.9.2'
from dicomweb_client.api import DICOMwebClient
| __version__ = '0.9.3'
from dicomweb_client.api import DICOMwebClient
| Increase version to 0.9.3 for release | Increase version to 0.9.3 for release
| Python | mit | MGHComputationalPathology/dicomweb-client | ---
+++
@@ -1,3 +1,3 @@
-__version__ = '0.9.2'
+__version__ = '0.9.3'
from dicomweb_client.api import DICOMwebClient |
58120c937e04357f6fbdcf1431f69fe7a38aacb2 | app/mod_budget/model.py | app/mod_budget/model.py | from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Entry(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry.... | from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Income(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry... | Split Entry into Income and Expense schemes | Split Entry into Income and Expense schemes
Splitting the Entry schema into two seperate schemes allows
us to use different collections to store them, which in turn makes
our work easier later on.
| Python | mit | Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault | ---
+++
@@ -5,7 +5,7 @@
# The name of the category.
name = db.StringField(required = True)
-class Entry(db.Document):
+class Income(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
@@ -13,6 +13,20 @@
description = db.StringField(required = ... |
d4b1c89a8d365457e1162d5a39815e7fc47781a1 | src/epiweb/apps/profile/urls.py | src/epiweb/apps/profile/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^edit/$', 'epiweb.apps.profile.views.edit'),
(r'^$', 'epiweb.apps.profile.views.index'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^$', 'epiweb.apps.profile.views.index'),
)
| Remove profile 'show' page, only 'edit' page is provided. | Remove profile 'show' page, only 'edit' page is provided.
| Python | agpl-3.0 | ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website | ---
+++
@@ -1,7 +1,6 @@
from django.conf.urls.defaults import *
urlpatterns = patterns('',
- (r'^edit/$', 'epiweb.apps.profile.views.edit'),
(r'^$', 'epiweb.apps.profile.views.index'),
)
|
5a0116378b6906fbfb3146bbf635d6d9c39ec714 | saleor/dashboard/collection/forms.py | saleor/dashboard/collection/forms.py | from django import forms
from ...product.models import Collection
class CollectionForm(forms.ModelForm):
class Meta:
model = Collection
exclude = []
| from unidecode import unidecode
from django import forms
from django.utils.text import slugify
from ...product.models import Collection
class CollectionForm(forms.ModelForm):
class Meta:
model = Collection
exclude = ['slug']
def save(self, commit=True):
self.instance.slug = slugify(... | Update CollectionForm to handle slug field | Update CollectionForm to handle slug field
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor | ---
+++
@@ -1,8 +1,17 @@
+from unidecode import unidecode
+
from django import forms
+from django.utils.text import slugify
+
from ...product.models import Collection
class CollectionForm(forms.ModelForm):
class Meta:
model = Collection
- exclude = []
+ exclude = ['slug']
+
+ def... |
5329c48a6f0a36809d3088560f91b427f7a2bf0b | models.py | models.py | from datetime import datetime
from app import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String())
pw_hash = db.Co... | from datetime import datetime
from app import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String())
pw_hash = db.Co... | Add title to Graph object constructor | Add title to Graph object constructor
| Python | mit | ChristopherChudzicki/math3d,stardust66/math3d,stardust66/math3d,stardust66/math3d,stardust66/math3d,ChristopherChudzicki/math3d,ChristopherChudzicki/math3d,ChristopherChudzicki/math3d | ---
+++
@@ -33,8 +33,9 @@
serialized_string = db.Column(db.String())
user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
- def __init__(self, serialized_string):
+ def __init__(self, title, serialized_string):
self.created_at = datetime.utcnow()
+ self.title = title
... |
44e3f48b8832dd14f8f9269c02929fa5d4a5c9af | src/librement/profile/models.py | src/librement/profile/models.py | from django.db import models
from django_enumfield import EnumField
from librement.utils.user_data import PerUserData
from .enums import AccountEnum, CountryEnum
class Profile(PerUserData('profile')):
account_type = EnumField(AccountEnum)
organisation = models.CharField(max_length=100, blank=True)
add... | from django.db import models
from django_enumfield import EnumField
from librement.utils.user_data import PerUserData
from .enums import AccountEnum, CountryEnum
class Profile(PerUserData('profile')):
account_type = EnumField(AccountEnum, default=AccountEnum.INDIVIDUAL)
organisation = models.CharField(max_... | Make this the default so we can create User objects. | Make this the default so we can create User objects.
Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
| Python | agpl-3.0 | rhertzog/librement,rhertzog/librement,rhertzog/librement | ---
+++
@@ -7,7 +7,7 @@
from .enums import AccountEnum, CountryEnum
class Profile(PerUserData('profile')):
- account_type = EnumField(AccountEnum)
+ account_type = EnumField(AccountEnum, default=AccountEnum.INDIVIDUAL)
organisation = models.CharField(max_length=100, blank=True)
|
e43345616e5240274e852a722c0c72c07f988b2a | registration/__init__.py | registration/__init__.py | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases... | Fix version number reporting so we can be installed before Django. | Fix version number reporting so we can be installed before Django.
| Python | bsd-3-clause | myimages/django-registration,Troyhy/django-registration,mypebble/djregs,akvo/django-registration,Troyhy/django-registration,hacklabr/django-registration,gone/django-registration,akvo/django-registration,tdruez/django-registration,dirtycoder/django-registration,sandipagr/django-registration,kennydude/djregs,danielsamuel... | ---
+++
@@ -1,6 +1,22 @@
-VERSION = (0, 9, 0, 'beta', 1)
+VERSION = (1, 0, 0, 'final', 0)
def get_version():
- from django.utils.version import get_version as django_get_version
- return django_get_version(VERSION) # pragma: no cover
+ "Returns a PEP 386-compliant version number from VERSION."
+ asse... |
dc45f973faa5655e821364cfbdb96a3e17ff9893 | app/__init__.py | app/__init__.py | import os
from flask import Flask, Blueprint, request, jsonify
app = Flask(__name__)
# Read configuration to apply from environment
config_name = os.environ.get('FLASK_CONFIG', 'development')
# apply configuration
cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
app.config.from_pyfile(cfg)
# Create a bl... | import os
from flask import Flask, Blueprint, request, jsonify
app = Flask(__name__)
# Read configuration to apply from environment
config_name = os.environ.get('FLASK_CONFIG', 'development')
# apply configuration
cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
app.config.from_pyfile(cfg)
# Create a bl... | Fix bug in token authentication | Fix bug in token authentication
| Python | apache-2.0 | javicacheiro/salt-git-synchronizer-proxy | ---
+++
@@ -19,8 +19,9 @@
def before_request():
"""All routes in this blueprint require authentication."""
if app.config['AUTH_REQUIRED']:
- if request.args.get('secret_token'):
- token = request.headers.get(app.config['TOKEN_HEADER'])
+ token_header = app.config['TOKEN_HEADER']
+ ... |
12df471eff4d5ece3da100c3691e9a3d577fa114 | EC2/create_instance.py | EC2/create_instance.py | import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='ju... | import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='ju... | Update the script to create EC2 instance. | Update the script to create EC2 instance.
This creates an EC2 i3.8xlarge.
| Python | apache-2.0 | icoming/FlashX,flashxio/FlashX,icoming/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashX,flashxio/FlashX,flashxio/FlashX,flashxio/FlashX | ---
+++
@@ -14,7 +14,7 @@
sg = client.describe_security_groups(GroupNames=['jupyter'])
print("the security group exist")
-o = ec2.create_instances(ImageId='ami-e36637f5', MinCount=1, MaxCount=1, InstanceType='i3.xlarge', SecurityGroups=['jupyter'])
+o = ec2.create_instances(ImageId='ami-622a0119', MinCoun... |
015ecbbe112edaa3ada4cb1af70f62f03654dfe4 | py/app.py | py/app.py | import json
import functools
from flask import Flask, Response
from foxgami.red import Story
app = Flask(__name__)
def return_as_json(inner_f):
@functools.wraps(inner_f)
def new_f(*args, **kwargs):
result = inner_f(*args, **kwargs)
return Response(json.dumps(
result,
i... | import json
import functools
from flask import Flask, Response
from foxgami.red import Story
app = Flask(__name__)
@app.after_response
def add_content_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
return response
def return_as_json(inner_f):
@functools.wraps(inner_f)
def n... | Add Access-Control headers to python | Add Access-Control headers to python
| Python | mit | flubstep/foxgami.com,flubstep/foxgami.com | ---
+++
@@ -4,6 +4,11 @@
from foxgami.red import Story
app = Flask(__name__)
+
+@app.after_response
+def add_content_headers(response):
+ response.headers['Access-Control-Allow-Origin'] = '*'
+ return response
def return_as_json(inner_f): |
f323676f1d3717ed2c84d06374cffbe2f1882cb4 | blimp_boards/notifications/serializers.py | blimp_boards/notifications/serializers.py | from rest_framework import serializers
from .models import Notification
class NotificationSerializer(serializers.ModelSerializer):
target = serializers.Field(source='data.target')
action_object = serializers.Field(source='data.action_object')
actor = serializers.Field(source='data.sender')
timesince ... | from django.utils.six.moves.urllib import parse
from rest_framework import serializers
from ..files.utils import sign_s3_url
from .models import Notification
class NotificationSerializer(serializers.ModelSerializer):
target = serializers.SerializerMethodField('get_target_data')
action_object = serializers.S... | Fix action object and target thumbnail urls | Fix action object and target thumbnail urls | Python | agpl-3.0 | jessamynsmith/boards-backend,jessamynsmith/boards-backend,GetBlimp/boards-backend | ---
+++
@@ -1,11 +1,14 @@
+from django.utils.six.moves.urllib import parse
+
from rest_framework import serializers
+from ..files.utils import sign_s3_url
from .models import Notification
class NotificationSerializer(serializers.ModelSerializer):
- target = serializers.Field(source='data.target')
- act... |
7bfefe50c00d86b55c0620207e9848c97aa28227 | rml/units.py | rml/units.py | import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly():
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - physics_v... | import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly(object):
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - phy... | Correct the definitions of old-style classes | Correct the definitions of old-style classes
| Python | apache-2.0 | razvanvasile/RML,willrogers/pml,willrogers/pml | ---
+++
@@ -2,7 +2,7 @@
from scipy.interpolate import PchipInterpolator
-class UcPoly():
+class UcPoly(object):
def __init__(self, coef):
self.p = np.poly1d(coef)
@@ -18,7 +18,7 @@
raise ValueError("No corresponding positive machine value:", roots)
-class UcPchip():
+class UcPchi... |
d487e8d74d8bbbadf003cd128f80868cc5651d21 | shenfun/optimization/__init__.py | shenfun/optimization/__init__.py | """Module for optimized functions
Some methods performed in Python may be slowing down solvers. In this optimization
module we place optimized functions that are to be used instead of default
Python methods. Some methods are implemented solely in Cython and only called
from within the regular Python modules.
"""
impo... | """Module for optimized functions
Some methods performed in Python may be slowing down solvers. In this optimization
module we place optimized functions that are to be used instead of default
Python methods. Some methods are implemented solely in Cython and only called
from within the regular Python modules.
"""
impo... | Use try clause for config in optimizer | Use try clause for config in optimizer
| Python | bsd-2-clause | spectralDNS/shenfun,spectralDNS/shenfun,spectralDNS/shenfun | ---
+++
@@ -18,8 +18,14 @@
def optimizer(func):
"""Decorator used to wrap calls to optimized versions of functions."""
from shenfun.config import config
- mod = config['optimization']['mode']
- verbose = config['optimization']['verbose']
+ mod = 'cython'
+ verbose = False
+ try:
+ mod... |
7c3c0fac58822bcfa7bbd69de5ce46b36f84740c | regulations/generator/link_flattener.py | regulations/generator/link_flattener.py | import re
# <a> followed by another <a> without any intervening </a>s
link_inside_link_regex = re.compile(
ur"(?P<outer_link><a ((?!</a>).)*)(<a ((?!</a>).)*>"
ur"(?P<internal_content>((?!</a>).)*)</a>)",
re.IGNORECASE | re.DOTALL)
def flatten_links(text):
"""
Fix <a> elements that have embedded ... | import re
# <a> followed by another <a> without any intervening </a>s
# outer_link - partial outer element up to the inner link
# inner_content - content of the inner_link
link_inside_link_regex = re.compile(
ur"(?P<outer_link><a ((?!</a>).)*)<a .*?>(?P<inner_content>.*?)</a>",
re.IGNORECASE | re.DOTALL)
def... | Simplify regex using non-greedy qualifier | Simplify regex using non-greedy qualifier
| Python | cc0-1.0 | 18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site | ---
+++
@@ -1,9 +1,10 @@
import re
# <a> followed by another <a> without any intervening </a>s
+# outer_link - partial outer element up to the inner link
+# inner_content - content of the inner_link
link_inside_link_regex = re.compile(
- ur"(?P<outer_link><a ((?!</a>).)*)(<a ((?!</a>).)*>"
- ur"(?P<interna... |
accaf0bc0ab81d12927b55fdfd24ad75907b772f | runserver.py | runserver.py | from anser import Anser
server = Anser(__name__, debug=True)
@server.action('default')
def action_a(message, address):
print message['type']
print message['body']
server.run() | from anser import Anser
server = Anser(__name__, debug=True)
@server.action('default')
def action_a(message, address):
print "{0} - {1}".format(address, message)
server.run()
| Clean the output of the demo server | Clean the output of the demo server
| Python | mit | iconpin/anser | ---
+++
@@ -6,8 +6,7 @@
@server.action('default')
def action_a(message, address):
- print message['type']
- print message['body']
+ print "{0} - {1}".format(address, message)
server.run() |
37b8cf1af7818fe78b31ed25622f3f91805ade01 | test_bert_trainer.py | test_bert_trainer.py | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(str(int(time.time())))
... | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(str(int(time.time())))
... | Fix merge conflict in bert_trainer_example.py | Fix merge conflict in bert_trainer_example.py
| Python | apache-2.0 | googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings | ---
+++
@@ -23,16 +23,6 @@
self.train_model()
shutil.rmtree(self.output_dir)
- def test_train_and_test(self):
- self.train_model()
- results = self.trainer.evaluate(self.data['abstract'], self.data['section'])
- results2 = self.trainer.evaluate(self.data['abstract'], self.d... |
ceb123e78b4d15c0cfe30198aa3fbbe71603472d | project/forms.py | project/forms.py | #! coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField(label=_('Naudotojo vardas'), max_length=100,
help_text=_('VU MIF uosis.mif.vu.lt ser... | #! coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField(label=_('Naudotojo vardas'), max_length=100,
help_text=_('VU MIF uosis.mif.vu.lt ser... | Update login form clean method to return full cleaned data. | Update login form clean method to return full cleaned data.
| Python | agpl-3.0 | InScience/DAMIS-old,InScience/DAMIS-old | ---
+++
@@ -19,4 +19,5 @@
if not user:
raise forms.ValidationError(_(u'Naudotojo vardas arba slaptažodis '
'yra neteisingi'))
- return {'user': user}
+ cleaned_data['user'] = user
+ return cleaned_data |
d38180f627cf421268f64d94e0eec36a19573754 | test_runner/utils.py | test_runner/utils.py | import logging
import os
import uuid
from contextlib import contextmanager
from subprocess import check_call, CalledProcessError
LOG = logging.getLogger(__name__)
def touch(directory, filename=None):
file_path = os.path.join(directory, filename)
if os.path.exists(file_path):
os.utime(file_path, Non... | import logging
import os
import uuid
from contextlib import contextmanager
from subprocess import check_call, CalledProcessError
LOG = logging.getLogger(__name__)
def touch(directory, filename=None):
file_path = os.path.join(directory, filename)
if os.path.exists(file_path):
os.utime(file_path, Non... | Add fallback to 'cwd' if not defined | Add fallback to 'cwd' if not defined
| Python | mit | rcbops-qa/test_runner | ---
+++
@@ -28,8 +28,7 @@
:param command: String of a command to run within a shell
:returns: Dictionary with keys relating to the execution's success
"""
- if kwargs['cwd']:
- cwd = kwargs['cwd']
+ cwd = kwargs.get('cwd', None)
try:
ret = check_call(command, shell=True, cw... |
a4d5a74c675b0c1d90dd9f254367975af9ea2735 | opps/core/models/__init__.py | opps/core/models/__init__.py | # -*- coding: utf-8 -*-
from opps.core.models.channel import *
from opps.core.models.profile import *
from opps.core.models.source import *
from opps.core.models.publisher import *
| # -*- coding: utf-8 -*-
from opps.core.models.channel import *
from opps.core.models.profile import *
from opps.core.models.source import *
from opps.core.models.published import *
| Change package core mdoels init | Change package core mdoels init
| Python | mit | jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps | ---
+++
@@ -2,4 +2,4 @@
from opps.core.models.channel import *
from opps.core.models.profile import *
from opps.core.models.source import *
-from opps.core.models.publisher import *
+from opps.core.models.published import * |
096bd7e3357e85c57ec56695bfc16f0b4eab9c4d | pystil.py | pystil.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""
pystil - An elegant site web traffic analyzer
"""
from pystil import app, config
import werkzeug.contrib
import sys
config.freeze()
if 'soup' in sys.ar... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 by Florian Mounier, Kozea
# This file is part of pystil, licensed under a 3-clause BSD license.
"""
pystil - An elegant site web traffic analyzer
"""
from pystil import app, config
import werkzeug.contrib.fixers
import sys
config.freeze()
if 'soup' in... | Add the good old middleware | Add the good old middleware
| Python | bsd-3-clause | Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil | ---
+++
@@ -6,7 +6,7 @@
pystil - An elegant site web traffic analyzer
"""
from pystil import app, config
-import werkzeug.contrib
+import werkzeug.contrib.fixers
import sys
config.freeze()
@@ -38,6 +38,6 @@
from gevent import monkey
monkey.patch_all()
import gevent.wsgi
- application = Applic... |
e7c5e62da700f51e69662689758ffebf70fa1494 | cms/djangoapps/contentstore/context_processors.py | cms/djangoapps/contentstore/context_processors.py | import ConfigParser
from django.conf import settings
def doc_url(request):
config_file = open(settings.REPO_ROOT / "docs" / "config.ini")
config = ConfigParser.ConfigParser()
config.readfp(config_file)
# in the future, we will detect the locale; for now, we will
# hardcode en_us, since we only ha... | import ConfigParser
from django.conf import settings
config_file = open(settings.REPO_ROOT / "docs" / "config.ini")
config = ConfigParser.ConfigParser()
config.readfp(config_file)
def doc_url(request):
# in the future, we will detect the locale; for now, we will
# hardcode en_us, since we only have English d... | Read from doc url mapping file at load time, rather than once per request | Read from doc url mapping file at load time, rather than once per request
| Python | agpl-3.0 | ampax/edx-platform,Softmotions/edx-platform,dcosentino/edx-platform,chudaol/edx-platform,prarthitm/edxplatform,cyanna/edx-platform,jazztpt/edx-platform,motion2015/a3,nikolas/edx-platform,msegado/edx-platform,hkawasaki/kawasaki-aio8-0,LearnEra/LearnEraPlaftform,pabloborrego93/edx-platform,wwj718/ANALYSE,procangroup/edx-... | ---
+++
@@ -1,12 +1,12 @@
import ConfigParser
from django.conf import settings
+config_file = open(settings.REPO_ROOT / "docs" / "config.ini")
+config = ConfigParser.ConfigParser()
+config.readfp(config_file)
+
def doc_url(request):
- config_file = open(settings.REPO_ROOT / "docs" / "config.ini")
- confi... |
09f649ac0b14269067c43df9f879d963ab99cdac | backend/breach/views.py | backend/breach/views.py | import json
from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from breach.strategy import Strategy
from breach.models import Victim
def get_work(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
... | import json
from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from breach.strategy import Strategy
from breach.models import Victim
def get_work(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
... | Fix response with json for get_work | Fix response with json for get_work
| Python | mit | dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,d... | ---
+++
@@ -22,7 +22,8 @@
new_work = strategy.get_work()
- return HttpResponse(json.dumps(new_work), content_type='application/json')
+ return JsonResponse(new_work)
+
@csrf_exempt
def work_completed(request, victim_id=0): |
0d5c3b5f0c9278e834fc4df2a5d227972a1b513d | tests/unit/modules/file_test.py | tests/unit/modules/file_test.py | import tempfile
from saltunittest import TestCase, TestLoader, TextTestRunner
from salt import config as sconfig
from salt.modules import file as filemod
from salt.modules import cmdmod
filemod.__salt__ = {
'cmd.run': cmdmod.run,
}
SED_CONTENT = """test
some
content
/var/lib/foo/app/test
here
"""
class FileMo... | import tempfile
from saltunittest import TestCase, TestLoader, TextTestRunner
from salt import config as sconfig
from salt.modules import file as filemod
from salt.modules import cmdmod
filemod.__salt__ = {
'cmd.run': cmdmod.run,
'cmd.run_all': cmdmod.run_all
}
SED_CONTENT = """test
some
content
/var/lib/fo... | Add `cmd.run_all` to `__salt__`. Required for the unit test. | Add `cmd.run_all` to `__salt__`. Required for the unit test.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -8,6 +8,7 @@
filemod.__salt__ = {
'cmd.run': cmdmod.run,
+ 'cmd.run_all': cmdmod.run_all
}
SED_CONTENT = """test
@@ -32,7 +33,10 @@
filemod.sed(path, before, after, limit=limit)
with open(path, 'rb') as newfile:
- self.assertEquals(SED_CONTENT.repla... |
fc27b35dd1ac34b19bdc2d71dd71704bd9321b9d | src/test/ed/db/pythonnumbers.py | src/test/ed/db/pythonnumbers.py |
import types
db = connect( "test" );
t = db.pythonnumbers
t.drop()
thing = { "a" : 5 , "b" : 5.5 }
assert( type( thing["a"] ) == types.IntType );
assert( type( thing["b"] ) == types.FloatType );
t.save( thing )
thing = t.findOne()
assert( type( thing["b"] ) == types.FloatType );
assert( type( thing["a"] ) == types... |
import _10gen
import types
db = _10gen.connect( "test" );
t = db.pythonnumbers
t.drop()
thing = { "a" : 5 , "b" : 5.5 }
assert( type( thing["a"] ) == types.IntType );
assert( type( thing["b"] ) == types.FloatType );
t.save( thing )
thing = t.findOne()
assert( type( thing["b"] ) == types.FloatType );
assert( type( ... | Fix test for unwelded scopes. | Fix test for unwelded scopes.
| Python | apache-2.0 | babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble | ---
+++
@@ -1,7 +1,8 @@
+import _10gen
import types
-db = connect( "test" );
+db = _10gen.connect( "test" );
t = db.pythonnumbers
t.drop()
|
94d99dea05bbd17220f3959a965cc6abd456bf12 | demo/tests/conftest.py | demo/tests/conftest.py | """Unit tests configuration file."""
import logging
def pytest_configure(config):
"""Disable verbose output when running tests."""
logging.basicConfig(level=logging.DEBUG)
terminal = config.pluginmanager.getplugin('terminal')
base = terminal.TerminalReporter
class QuietReporter(base):
"... | """Unit tests configuration file."""
import logging
def pytest_configure(config):
"""Disable verbose output when running tests."""
logging.basicConfig(level=logging.DEBUG)
terminal = config.pluginmanager.getplugin('terminal')
base = terminal.TerminalReporter
class QuietReporter(base):
"... | Deploy Travis CI build 976 to GitHub | Deploy Travis CI build 976 to GitHub
| Python | mit | jacebrowning/template-python-demo | ---
+++
@@ -11,7 +11,7 @@
base = terminal.TerminalReporter
class QuietReporter(base):
- ""Reporter that only shows dots when running tests."""
+ """Reporter that only shows dots when running tests."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwar... |
d87a44367c5542ab8052c212e6d51f1532086dd1 | testsuite/python3.py | testsuite/python3.py | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: Class... | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
# Camel-caes
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
... | Make identifiers camel-case; remove redundant space. | Make identifiers camel-case; remove redundant space.
| Python | mit | PyCQA/pep8 | ---
+++
@@ -12,6 +12,7 @@
class Class:
+ # Camel-caes
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
@@ -23,16 +24,16 @@
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_var: ClassVar[str]
- For_var: ClassVar[str]
- While_var: ClassVar[str]
... |
0d96ff52ca66de8afd95fb6dc342e8529764e89b | tflitehub/lit.cfg.py | tflitehub/lit.cfg.py | import os
import sys
import lit.formats
import lit.util
import lit.llvm
# Configuration file for the 'lit' test runner.
lit.llvm.initialize(lit_config, config)
# name: The name of this test suite.
config.name = 'TFLITEHUB'
config.test_format = lit.formats.ShTest()
# suffixes: A list of file extensions to treat as... | import os
import sys
import lit.formats
import lit.util
import lit.llvm
# Configuration file for the 'lit' test runner.
lit.llvm.initialize(lit_config, config)
# name: The name of this test suite.
config.name = 'TFLITEHUB'
config.test_format = lit.formats.ShTest()
# suffixes: A list of file extensions to treat as... | Exclude test data utilities from lit. | Exclude test data utilities from lit.
| Python | apache-2.0 | iree-org/iree-samples,iree-org/iree-samples,iree-org/iree-samples,iree-org/iree-samples | ---
+++
@@ -22,10 +22,12 @@
#config.use_default_substitutions()
config.excludes = [
+ 'imagenet_test_data.py',
'lit.cfg.py',
'lit.site.cfg.py',
+ 'manual_test.py',
+ 'squad_test_data.py',
'test_util.py',
- 'manual_test.py',
]
config.substitutions.extend([ |
7a0b8550fa2f52519df81c7fa795d454e5e3b0bc | scripts/master/factory/dart/channels.py | scripts/master/factory/dart/channels.py | # Copyright 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.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | # Copyright 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.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | Update the build branch for stable to 0.7 | Update the build branch for stable to 0.7
TBR=ricow
Review URL: https://codereview.chromium.org/26993005
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -18,7 +18,7 @@
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 3),
Channel('dev', 'trunk', 1, '-dev', 2),
- Channel('stable', 'branches/0.6', 2, '-stable', 1),
+ Channel('stable', 'branches/0.7', 2, '-stable', 1),
]
CHANNELS_BY_NAME = {} |
4840763265675407ed9fc612dc8884d859bdc28e | recipe_scrapers/_abstract.py | recipe_scrapers/_abstract.py | from urllib import request
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
}
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
... | from urllib import request
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
}
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
... | Use context so the test file to get closed after tests | Use context so the test file to get closed after tests
| Python | mit | hhursev/recipe-scraper | ---
+++
@@ -12,7 +12,8 @@
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
- self.soup = BeautifulSoup(url.read(), "html.parser")
+ with url:
+ self.soup = BeautifulSoup(url.read(), "html.parser")
else:
... |
e59055e29b5cc6a027d3a24803cc05fd709cca90 | functest/opnfv_tests/features/odl_sfc.py | functest/opnfv_tests/features/odl_sfc.py | #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base... | #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base... | Revert "Make SFC test a python call to main()" | Revert "Make SFC test a python call to main()"
This reverts commit d5820bef80ea4bdb871380dbfe41db12290fc5f8.
Robot test runs before SFC test and it imports
https://github.com/robotframework/SSHLibrary
which does a monkey patching in
the python runtime / paramiko.
Untill now sfc run in a new python process (clean)
be... | Python | apache-2.0 | opnfv/functest,mywulin/functest,opnfv/functest,mywulin/functest | ---
+++
@@ -8,7 +8,6 @@
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base as base
-from sfc.tests.functest import run_tests
class OpenDaylightSFC(base.FeatureBase):
@@ -17,6 +16,5 @@
super(OpenDaylightSFC, self).__init__(project='sfc',
... |
f3702870cf912322061678cf7c827959cde2ac02 | south/introspection_plugins/__init__.py | south/introspection_plugins/__init__.py | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | Add import of django-annoying patch | Add import of django-annoying patch
| Python | apache-2.0 | matthiask/south,matthiask/south | ---
+++
@@ -6,4 +6,5 @@
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
+import south.introspection_plugins.annoying_autoonetoone
|
47faf3ad38eff5de2edc529a7347c01ddeddf4c4 | talks/users/models.py | talks/users/models.py | from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class TalksUser(models.Model):
user = models.OneToOneField(User)
class CollectionFollow(models.Model):
"""User... | from django.db import models
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class TalksUser(models.Model):
user = models.OneToOneField(User)
@receiver(mo... | Create TalksUser model when a user is created | Create TalksUser model when a user is created
| Python | apache-2.0 | ox-it/talks.ox,ox-it/talks.ox,ox-it/talks.ox | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.dispatch import receiver
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
@@ -9,17 +10,12 @@
user = models.OneToOneField(Use... |
f39982f0cab45ba898bf8de7a4170e615cd9569c | aldryn_newsblog/managers.py | aldryn_newsblog/managers.py | from collections import Counter
import datetime
from parler.managers import TranslatableManager
class RelatedManager(TranslatableManager):
# TODO: uncomment this when we'll have image field
# def get_query_set(self):
# qs = super(RelatedManager, self).get_query_set()
# return qs.select_rela... | try:
from collections import Counter
except ImportError:
from backport_collections import Counter
import datetime
from parler.managers import TranslatableManager
class RelatedManager(TranslatableManager):
# TODO: uncomment this when we'll have image field
# def get_query_set(self):
# qs = s... | Add fallback: from backport_collections import Counter | Add fallback: from backport_collections import Counter
| Python | bsd-3-clause | mkoistinen/aldryn-newsblog,mkoistinen/aldryn-newsblog,mkoistinen/aldryn-newsblog,czpython/aldryn-newsblog,czpython/aldryn-newsblog,czpython/aldryn-newsblog,czpython/aldryn-newsblog | ---
+++
@@ -1,6 +1,9 @@
-from collections import Counter
+try:
+ from collections import Counter
+except ImportError:
+ from backport_collections import Counter
+
import datetime
-
from parler.managers import TranslatableManager
|
a268a886e0e3cab1057810f488feb6c2227414d3 | users/serializers.py | users/serializers.py | from django.conf import settings
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = (
'username',
'email'... | from copy import deepcopy
from django.conf import settings
from django.contrib.auth import login
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Us... | Fix bug in register aftter login | Fix: Fix bug in register aftter login
| Python | bsd-2-clause | pinry/pinry,lapo-luchini/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry | ---
+++
@@ -1,4 +1,7 @@
+from copy import deepcopy
+
from django.conf import settings
+from django.contrib.auth import login
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
@@ -51,4 +54,9 @@
)
user.set_password(password)
user.save()
+ ... |
d8abffb340a852d69128977fa17bafdfc6babb71 | tests/test_utils.py | tests/test_utils.py | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((*CAMERA_RESOLUTION, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(tes... | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((MAX_WIDTH, MAX_HEIGHT, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(... | Fix test for python 2 | Fix test for python 2
| Python | mit | sergionr2/RacingRobot,sergionr2/RacingRobot,sergionr2/RacingRobot,sergionr2/RacingRobot | ---
+++
@@ -6,7 +6,7 @@
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
-test_image = 234 * np.ones((*CAMERA_RESOLUTION, 3), dtype=np.uint8)
+test_image = 234 * np.ones((MAX_WIDTH, MAX_HEIGHT, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(test_i... |
9f216f1fdde41730b2680eed2174b1ba75d923be | dataset/dataset/spiders/dataset_spider.py | dataset/dataset/spiders/dataset_spider.py | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca']
start_urls = ['http://data.gc.ca/data/en/datas... | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items
class DatasetSpider(CrawlSpider):
pages = 9466
name = 'dataset'
allowed_domains = ['data.gc.ca']
start_urls = []
for i in... | Add to start urls to contain all dataset pages | Add to start urls to contain all dataset pages
| Python | mit | MaxLikelihood/CODE | ---
+++
@@ -5,9 +5,14 @@
class DatasetSpider(CrawlSpider):
+ pages = 9466
name = 'dataset'
allowed_domains = ['data.gc.ca']
- start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
+ start_urls = []
+
+ for i in range(1, pages + 1):
+ start_urls.append('http://data.gc.ca/data/en/d... |
5ac88fd5a10444b8f6384d127c13216545319169 | vies/__init__.py | vies/__init__.py | # -*- coding: utf-8 -*-
import logging
__version__ = "5.0.1"
logger = logging.getLogger('vies')
VIES_WSDL_URL = str('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl') # NoQA
VATIN_MAX_LENGTH = 14
| # -*- coding: utf-8 -*-
import logging
__version__ = "5.0.2"
logger = logging.getLogger('vies')
VIES_WSDL_URL = str('https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl') # NoQA
VATIN_MAX_LENGTH = 14
| Fix vies url -- Increase version number | Fix vies url -- Increase version number
| Python | mit | codingjoe/django-vies | ---
+++
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
import logging
-__version__ = "5.0.1"
+__version__ = "5.0.2"
logger = logging.getLogger('vies')
-VIES_WSDL_URL = str('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl') # NoQA
+VIES_WSDL_URL = str('https://ec.europa.eu/taxation_customs/vies/check... |
95e61ccdebc33c1c610d0672558cd00798c3105f | packages/grid/backend/grid/api/users/models.py | packages/grid/backend/grid/api/users/models.py | # stdlib
from typing import Optional
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
from pydantic import BaseModel
from pydantic import EmailStr
class BaseUser(BaseModel):
email: Optional[EmailStr]
name: Optional[str]
role: Union[Optional[i... | # stdlib
from typing import Optional
from typing import Union
# third party
from nacl.encoding import HexEncoder
from nacl.signing import SigningKey
from pydantic import BaseModel
from pydantic import EmailStr
class BaseUser(BaseModel):
email: Optional[EmailStr]
name: Optional[str]
role: Union[Optional[i... | ADD institution / website as optional fields during user creation | ADD institution / website as optional fields during user creation
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -24,6 +24,12 @@
role: str = "Data Scientist"
name: str
password: str
+ institution: Optional[str]
+ website: Optional[str]
+
+
+class ApplicantStatus(BaseModel):
+ status: str
class UserUpdate(BaseUser):
@@ -45,6 +51,7 @@
website: Optional[str]
added_by: Optional[str]... |
3921c00a6eb4d0dc50bf3efaaeb9b91ff3ad7608 | vcs_gutter_change.py | vcs_gutter_change.py | import sublime_plugin
try:
from VcsGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class VcsGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lin... | import sublime_plugin
try:
from .view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class VcsGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lines:
... | Fix ImportError when loading change_(prev|next) module on windows | Fix ImportError when loading change_(prev|next) module on windows
| Python | mit | ariofrio/VcsGutter,bradsokol/VcsGutter,ariofrio/VcsGutter,bradsokol/VcsGutter | ---
+++
@@ -1,6 +1,6 @@
import sublime_plugin
try:
- from VcsGutter.view_collection import ViewCollection
+ from .view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
|
affad020348ca8aa6a7b9431811d707ab8f6d99a | pyramid/__init__.py | pyramid/__init__.py | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0-dev"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except Nam... | Bump version for v0.7.0 release | Bump version for v0.7.0 release
| Python | mit | tgsmith61591/pyramid,alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima | ---
+++
@@ -4,7 +4,7 @@
#
# The pyramid module
-__version__ = "0.7.0-dev"
+__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable |
194b72c7d3f0f60e73d1e11af716bfbdd9d4f08d | drupdates/plugins/slack/__init__.py | drupdates/plugins/slack/__init__.py | from drupdates.utils import *
from drupdates.constructors.reports import *
import json
class slack(Reports):
def __init__(self):
self.currentDir = os.path.dirname(os.path.realpath(__file__))
self.settings = Settings(self.currentDir)
def sendMessage(self, reportText):
""" Post the report to a Slack ch... | from drupdates.utils import *
from drupdates.constructors.reports import *
import json
class slack(Reports):
def __init__(self):
self.currentDir = os.path.dirname(os.path.realpath(__file__))
self.settings = Settings(self.currentDir)
def sendMessage(self, reportText):
""" Post the report to a Slack ch... | Add Slack channels the Slack Plugin | Add Slack channels the Slack Plugin
| Python | mit | jalama/drupdates | ---
+++
@@ -16,8 +16,11 @@
payload['text'] = reportText
payload['new-bot-name'] = user
dm = self.settings.get('slackRecipient')
+ channel = self.settings.get('slackChannel')
if dm:
payload['channel'] = '@' + dm
+ elif channel:
+ payload['channel'] = '#' + dm
response = u... |
988f4655a96076acd3bfb906d240bd4601fbe535 | getalltext.py | getalltext.py | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... | Add argument to print usernames | Add argument to print usernames
| Python | mit | expectocode/telegram-analysis,expectocode/telegramAnalysis | ---
+++
@@ -10,6 +10,7 @@
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
+ parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store... |
9056746db7406e6640607210bea9e00a12c63926 | ci/fix_paths.py | ci/fix_paths.py | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... | Sort list of files inside h5py | Sort list of files inside h5py
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py | ---
+++
@@ -29,7 +29,7 @@
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
- print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
+ print("In installed h5py:", sorted(os.listdir(pjoin(sitepackagesdir, 'h5py'))))
if __name__ == '__main__... |
cd8d7235190b4040fd135df6bb45e984c341b568 | cities/admin.py | cities/admin.py | from django.contrib.gis import admin
from cities.models import *
class CityAdmin(admin.OSMGeoAdmin):
list_display = ('__unicode__', 'population_2000')
list_filter = ('pop_range',)
search_fields = ('name',)
admin.site.register(City, CityAdmin)
| from django.contrib.gis import admin
from cities.models import *
class CityAdmin(admin.OSMGeoAdmin):
list_display = ('__unicode__', 'population_2000')
list_filter = ('pop_range', 'state')
search_fields = ('name',)
admin.site.register(City, CityAdmin)
| Allow filtering by state code | Allow filtering by state code | Python | bsd-3-clause | adamfast/usgsdata-citiesx020 | ---
+++
@@ -4,7 +4,7 @@
class CityAdmin(admin.OSMGeoAdmin):
list_display = ('__unicode__', 'population_2000')
- list_filter = ('pop_range',)
+ list_filter = ('pop_range', 'state')
search_fields = ('name',)
admin.site.register(City, CityAdmin) |
743f5a72840a5f829720899fe0febcdd7466be3e | bika/lims/upgrade/to1101.py | bika/lims/upgrade/to1101.py | import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
"""
issue #615: missing configuration for some a... | import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
def upgrade(tool):
"""
issue #615: missing configuration for some a... | Fix permission name in upgrade-1101 | Fix permission name in upgrade-1101
| Python | agpl-3.0 | rockfruit/bika.lims,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,DeBortoliWines/Bika-LIMS,veroc/Bika-LIMS | ---
+++
@@ -21,7 +21,7 @@
mp = portal.manage_permission
mp(AddAnalysisSpec, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
mp(AddSamplingDeviation, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
- mp(AddSamplingMatrix, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
+ mp(AddSampleMatri... |
3b091fba819f1ad69d0ce9e9038ccf5d14fea215 | tests/core/tests/test_mixins.py | tests/core/tests/test_mixins.py | from core.models import Category
from django.test.testcases import TestCase
from django.urls import reverse
class ExportViewMixinTest(TestCase):
def setUp(self):
self.url = reverse('export-category')
self.cat1 = Category.objects.create(name='Cat 1')
self.cat2 = Category.objects.create(na... | from core.models import Category
from django.test.testcases import TestCase
from django.urls import reverse
class ExportViewMixinTest(TestCase):
def setUp(self):
self.url = reverse('export-category')
self.cat1 = Category.objects.create(name='Cat 1')
self.cat2 = Category.objects.create(na... | Correct mistaken assertTrue() -> assertEquals() | Correct mistaken assertTrue() -> assertEquals()
| Python | bsd-2-clause | bmihelac/django-import-export,bmihelac/django-import-export,bmihelac/django-import-export,jnns/django-import-export,jnns/django-import-export,jnns/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,django-import-export/djang... | ---
+++
@@ -14,7 +14,7 @@
def test_get(self):
response = self.client.get(self.url)
self.assertContains(response, self.cat1.name, status_code=200)
- self.assertTrue(response['Content-Type'], 'text/html')
+ self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8')
... |
eb0d6d2c1d13e4dc7f84ca602ba95c2ebc31431a | src/lambda_function.py | src/lambda_function.py | """lambda_function.py main entry point for aws lambda"""
import json
import urllib.request
from typing import Dict, Optional
import settings
from logger import logger
from spot import to_msw_id
def close(fulfillment_state: str, message: Dict[str, str]) -> dict:
"""Close dialog generator"""
return {
... | """lambda_function.py main entry point for aws lambda"""
import json
import urllib.request
from typing import Dict, Optional
import settings
from logger import logger
from spot import to_msw_id
def close(fulfillment_state: str, message: Dict[str, str]) -> dict:
"""Close dialog generator"""
return {
... | Move debugger line to the top | Move debugger line to the top
| Python | mit | Smotko/surfbot,Smotko/surfbot | ---
+++
@@ -24,6 +24,9 @@
"""Lambda Handler
Entry point for every lambda function call
"""
+
+ logger.debug('event=%s context=%s', event, context)
+
if not settings.MSW_API:
logger.error("Couldn't read SF_MSW_API env variable")
return None
@@ -36,7 +39,6 @@
return ... |
1ba3536e214e283f503db0a9bf0d1ac4aa64f771 | tcconfig/_tc_command_helper.py | tcconfig/_tc_command_helper.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import errno
import sys
import subprocrunner as spr
from ._common import find_bin_path
from ._const import Tc, TcSubCommand
from ._error import NetworkInterfaceNotFound... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import errno
import sys
import subprocrunner as spr
from ._common import find_bin_path
from ._const import Tc, TcSubCommand
from ._error import NetworkInterfaceNotFound... | Change command installation check process | Change command installation check process
To properly check even if the user is not root.
| Python | mit | thombashi/tcconfig,thombashi/tcconfig | ---
+++
@@ -18,11 +18,11 @@
def check_tc_command_installation():
- try:
- spr.Which("tc").verify()
- except spr.CommandNotFoundError as e:
- logger.error("{:s}: {}".format(e.__class__.__name__, e))
- sys.exit(errno.ENOENT)
+ if find_bin_path("tc"):
+ return
+
+ logger.erro... |
c8291c72b21be4b06a834449d89b2e4f91c1bc2b | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.16.4"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.16.5"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.16.5 | Increment version number to 0.16.5
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.16.4"
+__version__ = "0.16.5"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
abd2df6436d7a4a1304bf521c0f0a6c8922e5826 | src/benchmark_rank_filter.py | src/benchmark_rank_filter.py | #!/usr/bin/env python
import sys
import timeit
import numpy
from rank_filter import lineRankOrderFilter
def benchmark():
input_array = numpy.random.normal(size=(100, 101, 102))
output_array = numpy.empty_like(input_array)
lineRankOrderFilter(input_array, 25, 0.5, 0, output_array)
def main(*argv):
... | #!/usr/bin/env python
from __future__ import division
import sys
import timeit
import numpy
from rank_filter import lineRankOrderFilter
def benchmark():
input_array = numpy.random.normal(size=(100, 101, 102))
output_array = numpy.empty_like(input_array)
lineRankOrderFilter(input_array, 25, 0.5, 0, ou... | Use Python 3 division on Python 2 | Use Python 3 division on Python 2
Make sure that floating point division is used on Python 2. This
basically happens anyways as we have a floating point value divided by
an integral value. Still it is good to ensure that our average doesn't
get truncated by accident.
| Python | bsd-3-clause | nanshe-org/rank_filter,DudLab/rank_filter,jakirkham/rank_filter,jakirkham/rank_filter,nanshe-org/rank_filter,nanshe-org/rank_filter,DudLab/rank_filter,DudLab/rank_filter,jakirkham/rank_filter | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
+from __future__ import division
import sys
import timeit |
d608d9f474f089df8f5d6e0e899554f9324e84f3 | squash/dashboard/urls.py | squash/dashboard/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet)
api_router.register(r'metrics', views.... | from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
admin.site.site_header = 'SQUASH Admin'
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet... | Set title for SQUASH admin interface | Set title for SQUASH admin interface
| Python | mit | lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard | ---
+++
@@ -3,6 +3,7 @@
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
+admin.site.site_header = 'SQUASH Admin'
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet) |
1dca59c4de479d2a75c34c0d1aae3948d819b84b | imagersite/imager_profile/models.py | imagersite/imager_profile/models.py | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
Friends = models.ManyToManyField('self')
Region = models.CharField(max_lengt... | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
friends = models.ManyToManyField('self')
region = models.CharField(max_lengt... | Change model fields to lower case letters | Change model fields to lower case letters
| Python | mit | DZwell/django-imager | ---
+++
@@ -10,8 +10,8 @@
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
- Friends = models.ManyToManyField('self')
- Region = models.CharField(max_length=200)
+ friends = models.ManyToManyField('self')
+ region = models.CharField(max_length=200)
|
918568524f1c5ef7264fee76597e8a88b6e2427f | src/ussclicore/utils/ascii_bar_graph.py | src/ussclicore/utils/ascii_bar_graph.py | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="UShareSoft"
def print_graph(values):
max=0
for v in values:
if len(v)>max:
... | __author__="UShareSoft"
def print_graph(values):
max=0
for v in values:
if len(v)>max:
max=len(v)
for v in values:
value = int(values[v])
if len(v)<max:
newV=v+(" " * int(max-len(v)))
... | Fix bug in the ascii bar graph | Fix bug in the ascii bar graph
| Python | apache-2.0 | yanngit/ussclicore,usharesoft/ussclicore | ---
+++
@@ -1,7 +1,3 @@
-# To change this license header, choose License Headers in Project Properties.
-# To change this template file, choose Tools | Templates
-# and open the template in the editor.
-
__author__="UShareSoft"
def print_graph(values):
@@ -10,16 +6,15 @@
if len(v)>max:
... |
205b832c287bdd587eff7ba266a4429f6aebb277 | data/models.py | data/models.py | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(aut... | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(aut... | Fix __unicode__ for DataPoint model | Fix __unicode__ for DataPoint model
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -19,7 +19,7 @@
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
- return self.exact_name
+ return unicode(self.name)
@classmethod
def get_all_data(cls): |
f8df781d4f2d96496f59942646718e9b30c9337f | tests/test_construct_policy.py | tests/test_construct_policy.py | """Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
's3:GetObject',
's3:ListObject'
],
... | """Test IAM Policies for correctness."""
import json
from foremast.iam.construct_policy import construct_policy
ANSWER1 = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': [
's3:GetObject',
's3:ListObject'
],
... | Test IAM Policy with no "services" | tests: Test IAM Policy with no "services"
See also: PSOBAT-1482
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -23,6 +23,11 @@
def test_main():
"""Check general assemblage."""
+ settings = {}
+
+ policy_json = construct_policy(pipeline_settings=settings)
+ assert json.loads(policy_json) == {}
+
settings = {'services': {'s3': True}}
policy_json = construct_policy(app='unicornforrest',
... |
260daaad18e4889c0e468befd46c38d02bb1316a | tests/test_py35/test_client.py | tests/test_py35/test_client.py | import aiohttp
async def test_async_with_session(loop):
async with aiohttp.ClientSession(loop=loop) as session:
pass
assert session.closed
| from contextlib import suppress
import aiohttp
from aiohttp import web
async def test_async_with_session(loop):
async with aiohttp.ClientSession(loop=loop) as session:
pass
assert session.closed
async def test_close_resp_on_error_async_with_session(loop, test_server):
async def handler(request)... | Add tests on closing connection by error | Add tests on closing connection by error
| Python | apache-2.0 | AraHaanOrg/aiohttp,rutsky/aiohttp,juliatem/aiohttp,singulared/aiohttp,moden-py/aiohttp,singulared/aiohttp,hellysmile/aiohttp,z2v/aiohttp,alex-eri/aiohttp-1,z2v/aiohttp,moden-py/aiohttp,alex-eri/aiohttp-1,z2v/aiohttp,arthurdarcet/aiohttp,KeepSafe/aiohttp,arthurdarcet/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,arthurdarcet/... | ---
+++
@@ -1,7 +1,42 @@
+from contextlib import suppress
+
import aiohttp
+from aiohttp import web
async def test_async_with_session(loop):
async with aiohttp.ClientSession(loop=loop) as session:
pass
assert session.closed
+
+
+async def test_close_resp_on_error_async_with_session(loop, test... |
69d0cf6cc0d19f1669f56a361447935e375ac05c | indico/modules/events/logs/views.py | indico/modules/events/logs/views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Include SUIR JS on logs page | Include SUIR JS on logs page
This is not pretty, as we don't even use SUIR there, but
indico/utils/redux imports a module that imports SUIR and thus breaks
the logs page if SUIR is not included.
| Python | mit | DirkHoffmann/indico,indico/indico,OmeGak/indico,pferreir/indico,ThiefMaster/indico,ThiefMaster/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,indico/indico,OmeGak/indico,mvidalgarcia/indico,indico/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,indico/indico,DirkHoffmann/ind... | ---
+++
@@ -20,6 +20,6 @@
class WPEventLogs(WPEventManagement):
- bundles = ('react.js', 'module_events.logs.js', 'module_events.logs.css')
+ bundles = ('react.js', 'semantic-ui.js', 'module_events.logs.js', 'module_events.logs.css')
template_prefix = 'events/logs/'
sidemenu_option = 'logs' |
839f9edc811776b8898cdf1fa7116eec9aef50a7 | tests/xmlsec/test_templates.py | tests/xmlsec/test_templates.py | import xmlsec
def test_create_signature_template():
node = xmlsec.create_signature_template()
assert node.tag.endswith('Signature')
assert node.xpath('*[local-name() = "SignatureValue"]')
assert node.xpath('*[local-name() = "SignedInfo"]')
return node
def test_add_reference():
node = test_... | import xmlsec
def test_create_signature_template():
node = xmlsec.create_signature_template()
assert node.tag.endswith('Signature')
assert node.xpath('*[local-name() = "SignatureValue"]')
assert node.xpath('*[local-name() = "SignedInfo"]')
def test_add_reference():
node = xmlsec.create_signatur... | Add additional tests for templates. | Add additional tests for templates.
| Python | mit | devsisters/python-xmlsec,concordusapps/python-xmlsec,mehcode/python-xmlsec,devsisters/python-xmlsec,mehcode/python-xmlsec,concordusapps/python-xmlsec | ---
+++
@@ -8,12 +8,41 @@
assert node.xpath('*[local-name() = "SignatureValue"]')
assert node.xpath('*[local-name() = "SignedInfo"]')
- return node
-
def test_add_reference():
- node = test_create_signature_template()
+ node = xmlsec.create_signature_template()
ref = xmlsec.add_reference(... |
0d48a418787e5724078d3821d28c639f0a76c8b2 | src/robot/htmldata/normaltemplate.py | src/robot/htmldata/normaltemplate.py | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | Fix reading log/report templates/dependencies in UTF-8. | Fix reading log/report templates/dependencies in UTF-8.
Some of the updated js dependencies (#2419) had non-ASCII data in
UTF-8 format but our code reading these files didn't take that into
account.
| Python | apache-2.0 | robotframework/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework | ---
+++
@@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import codecs
import os
from os.path import abspath, dirname, join, normpath
@@ -24,6 +25,6 @@
self._path = normpath(join(self._base_dir, filename.replace('/', os.sep)))... |
93fa014ea7a34834ae6bb85ea802879ae0026941 | keystone/common/policies/revoke_event.py | keystone/common/policies/revoke_event.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Add scope_types for revoke event policies | Add scope_types for revoke event policies
This commit associates `system` to revoke event policies, since these
policies were developed to assist the system in offline token
validation.
From now on, a warning will be logged when a project-scoped token is
used to get revocation events. Operators can opt into requiring... | Python | apache-2.0 | mahak/keystone,openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,openstack/keystone | ---
+++
@@ -18,6 +18,11 @@
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN,
+ # NOTE(lbragstad): This API was originally introduced so that services
+ # could invalidate tokens based on revocation events. This is system... |
00ce59d43c4208846234652a0746f048836493f2 | src/ggrc/services/signals.py | src/ggrc/services/signals.py | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: urban@reciprocitylabs.com
# Maintained By: urban@reciprocitylabs.com
from blinker import Namespace
class Signals(object):
signals = Namespace()... | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: urban@reciprocitylabs.com
# Maintained By: urban@reciprocitylabs.com
from blinker import Namespace
class Signals(object):
signals = Namespace(... | Fix new CA signal message | Fix new CA signal message
| Python | apache-2.0 | selahssea/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,kr41/ggrc-cor... | ---
+++
@@ -6,18 +6,18 @@
from blinker import Namespace
+
class Signals(object):
signals = Namespace()
custom_attribute_changed = signals.signal(
- "Custom Attribute updated",
- """
- Indicates that a custom attribute was successfully saved to database.
+ "Custom Attribute updated",
+ ... |
6c6934e8a36429e2a988835d8bd4d66fe95e306b | tensorflow_datasets/image/cifar_test.py | tensorflow_datasets/image/cifar_test.py | # coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | Move references of deleted generate_cifar10_like_example.py to the new name cifar.py | Move references of deleted generate_cifar10_like_example.py to the new name cifar.py
PiperOrigin-RevId: 225386826
| Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | ---
+++
@@ -27,7 +27,7 @@
DATASET_CLASS = cifar.Cifar10
SPLITS = {
"train": 10, # Number of examples.
- "test": 2, # See testing/generate_cifar10_like_example.py
+ "test": 2, # See testing/cifar10.py
}
|
9feb84c39c6988ff31f3d7cb38852a457870111b | bin/readability_to_dr.py | bin/readability_to_dr.py | #!/usr/bin/env python3
import hashlib
import json
import os
import sys
print(sys.path)
from gigacluster import Doc, dr, Tokenizer
tok = Tokenizer()
for root, dirs, files in os.walk(sys.argv[1]):
dirs.sort()
files = set(files)
cluster_dr = os.path.join(root, 'cluster.dr')
with open(cluster_dr, 'wb') as... | #!/usr/bin/env python3
from collections import defaultdict
import hashlib
import json
import os
import sys
from gigacluster import Doc, dr, Tokenizer
tok = Tokenizer()
stats = defaultdict(int)
for root, dirs, files in os.walk(sys.argv[1]):
dirs.sort()
files = set(files)
cluster_dr = os.path.join(root, 'clu... | Check for empty cluster dr files. | Check for empty cluster dr files.
| Python | mit | schwa-lab/gigacluster,schwa-lab/gigacluster | ---
+++
@@ -1,37 +1,43 @@
#!/usr/bin/env python3
-
+from collections import defaultdict
import hashlib
import json
import os
import sys
-print(sys.path)
from gigacluster import Doc, dr, Tokenizer
tok = Tokenizer()
+stats = defaultdict(int)
for root, dirs, files in os.walk(sys.argv[1]):
dirs.sort()
... |
0d98a1c9b2682dde45196c8a3c8e89738aa3ab2a | litmus/cmds/__init__.py | litmus/cmds/__init__.py | #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Raise exception if sdb does not exist | Raise exception if sdb does not exist
| Python | apache-2.0 | dhs-shine/litmus | ---
+++
@@ -32,7 +32,7 @@
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
- call('sdb version', shell=True, timeout=10)
+ call(['sdb', 'version'], timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.for... |
c74b777cc861963595593486cf803a1d7431ad65 | matches/admin.py | matches/admin.py | from django.contrib import admin
from .models import Match
from .models import Tip
def delete_tips(modeladmin, request, queryset):
for match in queryset:
tips = Tip.objects.filter(match = match)
for tip in tips:
tip.score = 0
tip.scoring_field = ""
tip.is_score_c... | from django.contrib import admin
from .models import Match
from .models import Tip
def delete_tips(modeladmin, request, queryset):
for match in queryset:
tips = Tip.objects.filter(match = match)
for tip in tips:
tip.score = 0
tip.scoring_field = ""
tip.is_score_c... | Add action to zero out tips for given match | Add action to zero out tips for given match
| Python | mit | leventebakos/football-ech,leventebakos/football-ech | ---
+++
@@ -9,6 +9,7 @@
tip.score = 0
tip.scoring_field = ""
tip.is_score_calculated = False
+ tip.save()
delete_tips.delete_tips = "Delete calculated scores for tips for these matches"
class MatchAdmin(admin.ModelAdmin): |
d073de94f1896239bd6120893b6a94c43061a279 | byceps/util/image/models.py | byceps/util/image/models.py | """
byceps.util.image.models
~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from collections import namedtuple
from enum import Enum
class Dimensions(namedtuple('Dimensions', ['width', 'height'])):
"""A 2D image's width and height."""
... | """
byceps.util.image.models
~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from collections import namedtuple
from enum import Enum
class Dimensions(namedtuple('Dimensions', ['width', 'height'])):
"""A 2D image's width and height."""
... | Remove type ignore comment from functional enum API call | Remove type ignore comment from functional enum API call
This is supported as of Mypy 0.510 and no longer raises an error.
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -20,4 +20,4 @@
return self.width == self.height
-ImageType = Enum('ImageType', ['gif', 'jpeg', 'png']) # type: ignore
+ImageType = Enum('ImageType', ['gif', 'jpeg', 'png']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.