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(engine, 'connect')
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
| __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(engine, 'connect')
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.close()
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
| 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.close()
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection): |
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 = lumen_to_candela_by_apex_angle("25 lm", "120°")
assert_approx_equal(v, 7.9577471546, significant=5)
self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
| #!/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_by_apex_angle("25 lm", "120°")
assert_approx_equal(v, 7.9577471546, significant=5)
self.assertEqual(auto_format(lumen_to_candela_by_apex_angle, "25 lm", "120°"), "7.96 cd")
| 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_equal(v, 7.9577471546, significant=5) |
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.pages[0].Resources.XObject.Im0
raw_stream = pdf.pages[0].Resources.XObject.Im0.read_raw_stream()
with pytest.raises(RuntimeError):
pdf.pages[0].Resources.XObject.Im0.read_stream()
assert imghdr.what('', h=raw_stream) == 'jpeg'
im = Image.open(BytesIO(raw_stream))
assert im.size == (pdfimage.Width, pdfimage.Height)
assert im.mode == 'RGB' | 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 = pdf.pages[0].Resources.XObject['/Im0']
raw_bytes = pdfimage.read_raw_bytes()
with pytest.raises(RuntimeError):
pdfimage.read_bytes()
assert imghdr.what('', h=raw_bytes) == 'jpeg'
im = Image.open(BytesIO(raw_bytes))
assert im.size == (pdfimage.Width, pdfimage.Height)
assert im.mode == 'RGB'
def test_replace_jpeg(resources, outdir):
pdf = Pdf.open(resources / 'congress.pdf')
pdfimage = pdf.pages[0].Resources.XObject['/Im0']
raw_bytes = pdfimage.read_raw_bytes()
im = Image.open(BytesIO(raw_bytes))
grayscale = im.convert('L')
#newimage = Object.Stream(pdf, grayscale.tobytes())
pdfimage.write(zlib.compress(grayscale.tobytes()), Object.Name("/FlateDecode"), Object.Null())
pdfimage.ColorSpace = Object.Name('/DeviceGray')
pdf.save(outdir / 'congress_gray.pdf') | 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')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
- pdfimage = pdf.pages[0].Resources.XObject.Im0
- raw_stream = pdf.pages[0].Resources.XObject.Im0.read_raw_stream()
+ pdfimage = pdf.pages[0].Resources.XObject['/Im0']
+ raw_bytes = pdfimage.read_raw_bytes()
with pytest.raises(RuntimeError):
- pdf.pages[0].Resources.XObject.Im0.read_stream()
+ pdfimage.read_bytes()
- assert imghdr.what('', h=raw_stream) == 'jpeg'
+ assert imghdr.what('', h=raw_bytes) == 'jpeg'
- im = Image.open(BytesIO(raw_stream))
+ im = Image.open(BytesIO(raw_bytes))
assert im.size == (pdfimage.Width, pdfimage.Height)
assert im.mode == 'RGB'
+
+
+def test_replace_jpeg(resources, outdir):
+ pdf = Pdf.open(resources / 'congress.pdf')
+
+ pdfimage = pdf.pages[0].Resources.XObject['/Im0']
+ raw_bytes = pdfimage.read_raw_bytes()
+
+ im = Image.open(BytesIO(raw_bytes))
+ grayscale = im.convert('L')
+
+ #newimage = Object.Stream(pdf, grayscale.tobytes())
+
+ pdfimage.write(zlib.compress(grayscale.tobytes()), Object.Name("/FlateDecode"), Object.Null())
+ pdfimage.ColorSpace = Object.Name('/DeviceGray')
+
+ pdf.save(outdir / 'congress_gray.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, static_folder=static_directory)
app.config.from_object('config.flask_config')
def init_db():
"""
Initialize the SQLAlchemy database object.
:return: A SQLAlchemy instance used universally for database operations.
"""
return SQLAlchemy(app, session_options={
'expire_on_commit': False,
})
def init_login_manager():
"""
Initialize the login manager.
:return: A LoginManager instance used universally for flask-login loaders.
"""
login_manager = LoginManager()
login_manager.init_app(app)
return login_manager
| 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, static_folder=static_directory)
app.config.from_object('config.flask_config')
def init_db():
"""
Initialize the SQLAlchemy database object.
:return: A SQLAlchemy instance used universally for database operations.
"""
return SQLAlchemy(app, session_options={
'expire_on_commit': False,
})
def init_login_manager():
"""
Initialize the login manager.
:return: A LoginManager instance used universally for flask-login loaders.
"""
login_manager = LoginManager()
login_manager.init_app(app)
return login_manager
| 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_folder=static_directory)
app.config.from_object('config.flask_config') |
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'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^/', 'store.views.frontpage'),
)
| 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'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'', 'store.views.frontpage'),
)
| 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
mdformat."""
@functools.lru_cache()
def read_toml_opts(conf_dir: Path) -> Mapping:
conf_path = conf_dir / ".mdformat.toml"
if not conf_path.is_file():
parent_dir = conf_dir.parent
if conf_dir == parent_dir:
return {}
return read_toml_opts(parent_dir)
with open(conf_path, "rb") as f:
try:
toml_opts = tomli.load(f)
except tomli.TOMLDecodeError as e:
raise InvalidConfError(f"Invalid TOML syntax: {e}")
for key in toml_opts:
if key not in DEFAULT_OPTS:
raise InvalidConfError(f"Invalid key {key!r} in {conf_path}")
return toml_opts
| 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
mdformat."""
@functools.lru_cache()
def read_toml_opts(conf_dir: Path) -> Mapping:
conf_path = conf_dir / ".mdformat.toml"
if not conf_path.is_file():
parent_dir = conf_dir.parent
if conf_dir == parent_dir:
return {}
return read_toml_opts(parent_dir)
with open(conf_path, "rb") as f:
try:
toml_opts = tomli.load(f)
except tomli.TOMLDecodeError as e:
raise InvalidConfError(f"Invalid TOML syntax: {e}")
for key in toml_opts:
if key not in DEFAULT_OPTS:
raise InvalidConfError(
f"Invalid key {key!r} in {conf_path}."
f" Keys must be one of {set(DEFAULT_OPTS)}."
)
return toml_opts
| 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)}."
+ )
return toml_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": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc("@info:whatsthis", "Provides support for reading GCode files."),
"api": 2
},
"mesh_reader": [
{
"extension": "gcode",
"description": catalog.i18nc("@item:inlistbox", "Gcode File")
}
]
}
def register(app):
return { "mesh_reader": GCodeReader.GCodeReader() }
| # 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": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc("@info:whatsthis", "Provides support for reading GCode files."),
"api": 2
},
"profile_reader": {
"extension": "gcode",
"description": catalog.i18nc("@item:inlistbox", "Gcode File")
}
}
def register(app):
return { "profile_reader": GCodeReader.GCodeReader() }
| 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", "Gcode File")
- }
- ]
+ "profile_reader": {
+ "extension": "gcode",
+ "description": catalog.i18nc("@item:inlistbox", "Gcode File")
+ }
}
def register(app):
- return { "mesh_reader": GCodeReader.GCodeReader() }
+ return { "profile_reader": GCodeReader.GCodeReader() } |
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.Operator('...')))),
('Zilch',
vgl.SPPF(vgl.ParseTreeChar(vl.Class('Zilch')))),
('True',
vgl.SPPF(vgl.ParseTreeChar(vl.Class('True')))),
('False',
vgl.SPPF(vgl.ParseTreeChar(vl.Class('False')))),
])
def test_atom(line: str, sppf: vgl.SPPF):
atom = vg.GRAMMAR.get_rule('atom')
lexemes = vl.lex_line(line)
assert sppf == vg.make_sppf(atom, lexemes)
| 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(vl.Number('42')))),
('...',
SPPF(PTC(vl.Operator('...')))),
('Zilch',
SPPF(PTC(vl.Class('Zilch')))),
('True',
SPPF(PTC(vl.Class('True')))),
('False',
SPPF(PTC(vl.Class('False')))),
('()',
SPPF(PTP(SPPF(PTC(vl.OpenParen())),
SPPF(PTC(vl.CloseParen()))))),
('(foo)',
SPPF(PTP(SPPF(PTC(vl.OpenParen())),
SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))),
SPPF(PTR(SPPF())))),
SPPF(PTC(vl.CloseParen()))))))),
])
def test_atom(line: str, sppf: SPPF):
atom = vg.GRAMMAR.get_rule('atom')
lexemes = vl.lex_line(line)
assert sppf == vg.make_sppf(atom, lexemes)
| 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,sppf', [
('foo',
- vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))),
- ('2',
- vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))),
+ SPPF(PTC(vl.Name('foo')))),
+ ('42',
+ SPPF(PTC(vl.Number('42')))),
('...',
- vgl.SPPF(vgl.ParseTreeChar(vl.Operator('...')))),
+ SPPF(PTC(vl.Operator('...')))),
('Zilch',
- vgl.SPPF(vgl.ParseTreeChar(vl.Class('Zilch')))),
+ SPPF(PTC(vl.Class('Zilch')))),
('True',
- vgl.SPPF(vgl.ParseTreeChar(vl.Class('True')))),
+ SPPF(PTC(vl.Class('True')))),
('False',
- vgl.SPPF(vgl.ParseTreeChar(vl.Class('False')))),
+ SPPF(PTC(vl.Class('False')))),
+ ('()',
+ SPPF(PTP(SPPF(PTC(vl.OpenParen())),
+ SPPF(PTC(vl.CloseParen()))))),
+ ('(foo)',
+ SPPF(PTP(SPPF(PTC(vl.OpenParen())),
+ SPPF(PTP(SPPF(PTP(SPPF(PTC(vl.Name('foo'))),
+ SPPF(PTR(SPPF())))),
+ SPPF(PTC(vl.CloseParen()))))))),
])
-def test_atom(line: str, sppf: vgl.SPPF):
+def test_atom(line: str, sppf: SPPF):
atom = vg.GRAMMAR.get_rule('atom')
lexemes = vl.lex_line(line)
assert sppf == vg.make_sppf(atom, lexemes) |
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, 5, 5, 5]
knot = 5. / 2.
span = 3
to_check = helpers.basis_function_one(degree, knot_vector, span, knot)
result = 0.75
assert to_check == result
def test_basis_function_ders_one():
degree = 2
knot_vector = [0, 0, 0, 1, 2, 3, 4, 4, 5, 5, 5]
knot = 5. / 2.
span = 4
to_check = helpers.basis_function_ders_one(degree, knot_vector, 4, knot, 2)
result = [0.125, 0.5, 1.0]
assert to_check == result
| 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 = 2
+ knot_vector = [0, 0, 0, 1, 2, 3, 4, 4, 5, 5, 5]
+ knot = 5. / 2.
+ span = 3
+
+ to_check = helpers.basis_function_one(degree, knot_vector, span, knot)
+ result = 0.75
+
+ assert to_check == result
+
+def test_basis_function_ders_one():
+ degree = 2
+ knot_vector = [0, 0, 0, 1, 2, 3, 4, 4, 5, 5, 5]
+ knot = 5. / 2.
+ span = 4
+
+ to_check = helpers.basis_function_ders_one(degree, knot_vector, 4, knot, 2)
+ result = [0.125, 0.5, 1.0]
+
+ assert to_check == result | |
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 <= b and b <= upper_bound
def interleave(self, method, a, b, ideals, num=100):
results = []
for i in range(num):
res = method().interleave(a, b)
results.append(tuple(res))
results = set(results)
possible_results = set([tuple(i) for i in ideals])
assert results == possible_results
def multileave(self, method, a, b, ideals, num=100):
results = []
for i in range(num):
res = method().multileave(a, b)
results.append(tuple(res))
results = set(results)
possible_results = set([tuple(i) for i in ideals])
assert results == possible_results
def evaluate(self, method, ranking, clicks, result):
res = method().evaluate(ranking, clicks)
assert set(res) == set(result)
| 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 <= b and b <= upper_bound
def interleave(self, method, k, a, b, ideals, num=100):
results = []
for i in range(num):
res = method().interleave(k, a, b)
results.append(tuple(res))
results = set(results)
possible_results = set([tuple(i) for i in ideals])
assert results == possible_results
def multileave(self, method, a, b, ideals, num=100):
results = []
for i in range(num):
res = method().multileave(a, b)
results.append(tuple(res))
results = set(results)
possible_results = set([tuple(i) for i in ideals])
assert results == possible_results
def evaluate(self, method, ranking, clicks, result):
res = method().evaluate(ranking, clicks)
assert set(res) == set(result)
| 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):
- res = method().interleave(a, b)
+ res = method().interleave(k, a, b)
results.append(tuple(res))
results = set(results)
possible_results = set([tuple(i) for i in ideals]) |
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.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.name}** thinks that **{1.name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
| 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.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
| 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, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
|
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 take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
from . import payment_slip_from_invoice
| # -*- 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 take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
from . import payment_slip_from_invoice
from . import reports_common
| 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-opennet/ons_cyp_github,BT-aestebanez/l10n-switzerland,michl/l10n-switzerland,ndtran/l10n-switzerland | ---
+++
@@ -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__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
parent_pattern = None if pattern._regex == "^" else pattern
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
| 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):
self.endpoints = []
root_urlconf = import_string(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
parent_pattern = None if pattern._regex == "^" else pattern
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
| 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. Switching to Django's `import_string` method allows importing the final module in the path string, in my case the equivalent would be `from appname.config import urls`. | 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 __init__(self):
self.endpoints = []
- root_urlconf = __import__(settings.ROOT_URLCONF)
+ root_urlconf = import_string(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else: |
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=today, end_date__gt=today)
| 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_date__lte=today, end_date__gte=today)
| 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,WillisXChen/django-oscar,josesanch/django-oscar,ka7eh/django-oscar,WillisXChen/django-oscar,WadeYuChen/django-oscar,taedori81/django-oscar,manevant/django-oscar,sonofatailor/django-oscar,binarydud/django-oscar,vovanbo/django-oscar,solarissmoke/django-oscar,adamend/django-oscar,QLGu/django-oscar,Jannes123/django-oscar,elliotthill/django-oscar,WadeYuChen/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,jlmadurga/django-oscar,eddiep1101/django-oscar,bnprk/django-oscar,Bogh/django-oscar,lijoantony/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,rocopartners/django-oscar,QLGu/django-oscar,spartonia/django-oscar,jinnykoo/wuyisj,Idematica/django-oscar,anentropic/django-oscar,saadatqadri/django-oscar,machtfit/django-oscar,itbabu/django-oscar,faratro/django-oscar,WadeYuChen/django-oscar,josesanch/django-oscar,jmt4/django-oscar,dongguangming/django-oscar,michaelkuty/django-oscar,sonofatailor/django-oscar,DrOctogon/unwash_ecom,mexeniz/django-oscar,jinnykoo/wuyisj,taedori81/django-oscar,josesanch/django-oscar,nfletton/django-oscar,DrOctogon/unwash_ecom,lijoantony/django-oscar,kapari/django-oscar,ka7eh/django-oscar,Bogh/django-oscar,MatthewWilkes/django-oscar,nfletton/django-oscar,ka7eh/django-oscar,django-oscar/django-oscar,DrOctogon/unwash_ecom,faratro/django-oscar,ademuk/django-oscar,ademuk/django-oscar,sasha0/django-oscar,makielab/django-oscar,michaelkuty/django-oscar,faratro/django-oscar,amirrpp/django-oscar,anentropic/django-oscar,vovanbo/django-oscar,nfletton/django-oscar,anentropic/django-oscar,michaelkuty/django-oscar,Bogh/django-oscar,john-parton/django-oscar,pasqualguerrero/django-oscar,john-parton/django-oscar,bschuon/django-oscar,bnprk/django-oscar,vovanbo/django-oscar,binarydud/django-oscar,mexeniz/django-oscar,thechampanurag/django-oscar,makielab/django-oscar,kapari/django-oscar,WillisXChen/django-oscar,nickpack/django-oscar,eddiep1101/django-oscar,mexeniz/django-oscar,binarydud/django-oscar,pasqualguerrero/django-oscar,marcoantoniooliveira/labweb,kapari/django-oscar,lijoantony/django-oscar,amirrpp/django-oscar,binarydud/django-oscar,okfish/django-oscar,sasha0/django-oscar,monikasulik/django-oscar,Jannes123/django-oscar,manevant/django-oscar,django-oscar/django-oscar,WillisXChen/django-oscar,WillisXChen/django-oscar,manevant/django-oscar,rocopartners/django-oscar,dongguangming/django-oscar,jmt4/django-oscar,MatthewWilkes/django-oscar,taedori81/django-oscar,jmt4/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,jlmadurga/django-oscar,saadatqadri/django-oscar,solarissmoke/django-oscar,saadatqadri/django-oscar,ademuk/django-oscar,bnprk/django-oscar,saadatqadri/django-oscar,marcoantoniooliveira/labweb,django-oscar/django-oscar,rocopartners/django-oscar,manevant/django-oscar,john-parton/django-oscar,thechampanurag/django-oscar,jinnykoo/wuyisj.com,jlmadurga/django-oscar,itbabu/django-oscar,Bogh/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj.com,adamend/django-oscar,ahmetdaglarbas/e-commerce,MatthewWilkes/django-oscar,jlmadurga/django-oscar,Jannes123/django-oscar,faratro/django-oscar,spartonia/django-oscar,spartonia/django-oscar,itbabu/django-oscar,monikasulik/django-oscar,WillisXChen/django-oscar,MatthewWilkes/django-oscar,kapari/django-oscar,marcoantoniooliveira/labweb,sasha0/django-oscar,anentropic/django-oscar,kapt/django-oscar,vovanbo/django-oscar,Idematica/django-oscar,makielab/django-oscar,jinnykoo/christmas,ademuk/django-oscar,solarissmoke/django-oscar,kapt/django-oscar,ahmetdaglarbas/e-commerce,sonofatailor/django-oscar,jinnykoo/wuyisj,monikasulik/django-oscar,pdonadeo/django-oscar,okfish/django-oscar,amirrpp/django-oscar,bschuon/django-oscar,marcoantoniooliveira/labweb,jinnykoo/christmas,ahmetdaglarbas/e-commerce,machtfit/django-oscar,jinnykoo/wuyisj,nickpack/django-oscar,ahmetdaglarbas/e-commerce,Jannes123/django-oscar,itbabu/django-oscar,nickpack/django-oscar,jinnykoo/christmas,Idematica/django-oscar,pasqualguerrero/django-oscar,WadeYuChen/django-oscar,pdonadeo/django-oscar,QLGu/django-oscar,taedori81/django-oscar,jinnykoo/wuyisj.com,pdonadeo/django-oscar,adamend/django-oscar,makielab/django-oscar,okfish/django-oscar,pasqualguerrero/django-oscar,thechampanurag/django-oscar,michaelkuty/django-oscar,elliotthill/django-oscar,dongguangming/django-oscar,kapt/django-oscar,jinnykoo/wuyisj.com,dongguangming/django-oscar,okfish/django-oscar,eddiep1101/django-oscar,nickpack/django-oscar,bschuon/django-oscar,spartonia/django-oscar,amirrpp/django-oscar | ---
+++
@@ -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_query_set().filter(
- start_date__lte=today, end_date__gt=today)
+ start_date__lte=today, end_date__gte=today) |
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, **kwargs):
url = page.get_navigation_url()
return [
PagePretender(
title=capfirst(_('drudges')),
url='%sdrudges/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('regional offices')),
url='%sregional_offices/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('scope statements')),
url='%sscope_statements/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('assignments')),
url='%sassignments/' % url,
level=3,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('expense reports')),
url='%sexpense_reports/' % url,
level=3,
tree_id=page.tree_id,
),
]
| 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, **kwargs):
url = page.get_navigation_url()
return [
PagePretender(
title=capfirst(_('drudges')),
url='%sdrudges/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('regional offices')),
url='%sregional_offices/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('scope statements')),
url='%sscope_statements/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('assignments')),
url='%sassignments/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('expense reports')),
url='%sexpense_reports/' % url,
level=page.level+1,
tree_id=page.tree_id,
),
]
| 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=capfirst(_('regional offices')),
url='%sregional_offices/' % url,
- level=3,
+ level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('scope statements')),
url='%sscope_statements/' % url,
- level=3,
+ level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('assignments')),
url='%sassignments/' % url,
- level=3,
+ level=page.level+1,
tree_id=page.tree_id,
),
PagePretender(
title=capfirst(_('expense reports')),
url='%sexpense_reports/' % url,
- level=3,
+ level=page.level+1,
tree_id=page.tree_id,
),
] |
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):
"""Provides an interface to perl -c."""
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
def cmd(self):
"""
Return the command line to execute.
Overridden so we can add include paths based on the 'include_dirs'
settings.
"""
full_cmd = self.base_cmd
settings = self.get_view_settings()
include_dirs = settings.get('include_dirs', [])
if include_dirs:
full_cmd += ' ' . join([' -I ' + shlex.quote(include)
for include in include_dirs])
return full_cmd
| #
# 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):
"""Provides an interface to perl -c."""
syntax = ('modernperl', 'perl')
executable = 'perl'
regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?'
error_stream = util.STREAM_STDERR
def cmd(self):
"""
Return the command line to execute.
Overridden so we can add include paths based on the 'include_dirs'
settings.
"""
command = [self.executable_path, '-c']
include_dirs = self.get_view_settings().get('include_dirs', [])
for e in include_dirs:
command.append('-I')
command.append(shlex.quote(e))
return command
| 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
+ command = [self.executable_path, '-c']
- settings = self.get_view_settings()
+ include_dirs = self.get_view_settings().get('include_dirs', [])
- include_dirs = settings.get('include_dirs', [])
+ for e in include_dirs:
+ command.append('-I')
+ command.append(shlex.quote(e))
- if include_dirs:
- full_cmd += ' ' . join([' -I ' + shlex.quote(include)
- for include in include_dirs])
-
- return full_cmd
+ return command |
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,
index=None,
key=None,
prevValue=None,
value=None,
expiration=None,
ttl=None,
newKey=None):
return super(EtcdResult, cls).__new__(
cls,
action,
index,
key,
prevValue,
value,
expiration,
ttl,
newKey)
class EtcdException(Exception):
"""
Generic Etcd Exception.
"""
pass
| import collections
from client import Client
class EtcdResult(collections.namedtuple(
'EtcdResult',
[
'action',
'index',
'key',
'prevValue',
'value',
'expiration',
'ttl',
'newKey'])):
def __new__(
cls,
action=None,
index=None,
key=None,
prevValue=None,
value=None,
expiration=None,
ttl=None,
newKey=None):
return super(EtcdResult, cls).__new__(
cls,
action,
index,
key,
prevValue,
value,
expiration,
ttl,
newKey)
class EtcdException(Exception):
"""
Generic Etcd Exception.
"""
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
| 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,aziontech/python-etcd,jlamillan/python-etcd,kireal/python-etcd,jplana/python-etcd,kireal/python-etcd,mbrukman/python-etcd,vodik/python-etcd,thepwagner/python-etcd,projectcalico/python-etcd,sentinelleader/python-etcd | ---
+++
@@ -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, uid):
stack = api.content.get(UID=uid)
return stack.restrictedTraverse('@@folderListing')()
def item_index(self, uid):
return len(self.contained_items(uid))
def preview_image(self, uid):
images = self.contained_items(uid)
preview = None
if len(images):
first_item = images[0].getObject()
if IATBlobImage.providedBy(first_item):
preview = first_item
return preview
| # -*- 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, uid):
stack = api.content.get(UID=uid)
return stack.restrictedTraverse('@@folderListing')()
def item_index(self, uid):
return len(self.contained_items(uid))
def preview_image(self, uid):
images = self.contained_items(uid)
preview = None
if len(images):
first_item = images[0].getObject()
if IImage.providedBy(first_item):
preview = first_item
return preview
| 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 content page default view """
@@ -20,6 +19,6 @@
preview = None
if len(images):
first_item = images[0].getObject()
- if IATBlobImage.providedBy(first_item):
+ if IImage.providedBy(first_item):
preview = first_item
return preview |
1dd257b157cfcb13a13a9c97ff6580045026118c | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_menu_entries.xml',
'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| # -*- coding: utf-8 -*-
##############################################################################
#
##############################################################################
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_move_line_journal_view.xml',
'account_menu_entries.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| 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/analytic.dimension.csv',
'data/analytic.structure.csv' |
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/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
#
# Like /bin/touch, but takes a time using the LLVM epoch.
#
# ----------------------------------------------------------------------------
import os
import sys
assert len(sys.argv) >= 2
timeVal = int(sys.argv[1])
# offset between Unix and LLVM epochs
timeVal += 946684800
# Update the output file mtime, or create it if necessary.
# From http://stackoverflow.com/a/1160227.
for outputFile in sys.argv[1:]:
with open(outputFile, 'a'):
os.utime(outputFile, (timeVal, timeVal))
| #!/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/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
#
# Like /bin/touch, but takes a time using the system_clock epoch.
#
# ----------------------------------------------------------------------------
import os
import sys
assert len(sys.argv) >= 2
timeVal = int(sys.argv[1])
# Update the output file mtime, or create it if necessary.
# From http://stackoverflow.com/a/1160227.
for outputFile in sys.argv[1:]:
with open(outputFile, 'a'):
os.utime(outputFile, (timeVal, timeVal))
| 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 avoid merge conflicts in the test files.
| 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,practicalswift/swift,frootloops/swift,tardieu/swift,jckarter/swift,return/swift,benlangmuir/swift,xwu/swift,danielmartin/swift,djwbrown/swift,gribozavr/swift,return/swift,atrick/swift,arvedviehweger/swift,danielmartin/swift,nathawes/swift,tjw/swift,OscarSwanros/swift,shahmishal/swift,benlangmuir/swift,benlangmuir/swift,brentdax/swift,JGiola/swift,amraboelela/swift,roambotics/swift,tardieu/swift,tinysun212/swift-windows,jmgc/swift,parkera/swift,tardieu/swift,danielmartin/swift,gribozavr/swift,sschiau/swift,natecook1000/swift,huonw/swift,karwa/swift,gregomni/swift,harlanhaskins/swift,aschwaighofer/swift,practicalswift/swift,manavgabhawala/swift,glessard/swift,uasys/swift,gregomni/swift,allevato/swift,jckarter/swift,alblue/swift,natecook1000/swift,amraboelela/swift,xedin/swift,gottesmm/swift,hughbe/swift,harlanhaskins/swift,felix91gr/swift,return/swift,tkremenek/swift,shajrawi/swift,allevato/swift,sschiau/swift,sschiau/swift,stephentyrone/swift,tkremenek/swift,uasys/swift,JaSpa/swift,stephentyrone/swift,apple/swift,milseman/swift,lorentey/swift,shahmishal/swift,shajrawi/swift,atrick/swift,practicalswift/swift,xwu/swift,gribozavr/swift,return/swift,xedin/swift,hooman/swift,CodaFi/swift,gregomni/swift,apple/swift,austinzheng/swift,zisko/swift,milseman/swift,huonw/swift,jopamer/swift,jckarter/swift,benlangmuir/swift,stephentyrone/swift,xwu/swift,tardieu/swift,amraboelela/swift,swiftix/swift,CodaFi/swift,bitjammer/swift,danielmartin/swift,huonw/swift,JaSpa/swift,xedin/swift,austinzheng/swift,lorentey/swift,huonw/swift,deyton/swift,nathawes/swift,lorentey/swift,apple/swift,austinzheng/swift,harlanhaskins/swift,milseman/swift,glessard/swift,devincoughlin/swift,airspeedswift/swift,OscarSwanros/swift,glessard/swift,felix91gr/swift,OscarSwanros/swift,nathawes/swift,karwa/swift,gregomni/swift,tardieu/swift,felix91gr/swift,hooman/swift,apple/swift,atrick/swift,parkera/swift,gottesmm/swift,deyton/swift,aschwaighofer/swift,devincoughlin/swift,arvedviehweger/swift,bitjammer/swift,harlanhaskins/swift,gregomni/swift,felix91gr/swift,alblue/swift,shajrawi/swift,zisko/swift,jmgc/swift,tjw/swift,sschiau/swift,frootloops/swift,jtbandes/swift,xedin/swift,ahoppen/swift,xedin/swift,austinzheng/swift,JaSpa/swift,shahmishal/swift,atrick/swift,brentdax/swift,arvedviehweger/swift,brentdax/swift,tardieu/swift,JGiola/swift,xwu/swift,devincoughlin/swift,xwu/swift,calebd/swift,lorentey/swift,xedin/swift,jopamer/swift,atrick/swift,rudkx/swift,aschwaighofer/swift,jtbandes/swift,natecook1000/swift,hooman/swift,natecook1000/swift,tinysun212/swift-windows,uasys/swift,danielmartin/swift,airspeedswift/swift,brentdax/swift,swiftix/swift,devincoughlin/swift,natecook1000/swift,hooman/swift,codestergit/swift,tjw/swift,Jnosh/swift,swiftix/swift,gribozavr/swift,JGiola/swift,Jnosh/swift,harlanhaskins/swift,gottesmm/swift,hughbe/swift,tkremenek/swift,CodaFi/swift,hooman/swift,alblue/swift,karwa/swift,brentdax/swift,sschiau/swift,bitjammer/swift,uasys/swift,sschiau/swift,allevato/swift,return/swift,austinzheng/swift,gregomni/swift,arvedviehweger/swift,uasys/swift,zisko/swift,stephentyrone/swift,swiftix/swift,uasys/swift,shajrawi/swift,CodaFi/swift,lorentey/swift,hughbe/swift,bitjammer/swift,austinzheng/swift,tkremenek/swift,devincoughlin/swift,stephentyrone/swift,aschwaighofer/swift,frootloops/swift,xwu/swift,manavgabhawala/swift,manavgabhawala/swift,manavgabhawala/swift,Jnosh/swift,bitjammer/swift,bitjammer/swift,OscarSwanros/swift,karwa/swift,shahmishal/swift,hughbe/swift,milseman/swift,atrick/swift,hooman/swift,austinzheng/swift,glessard/swift,JGiola/swift,danielmartin/swift,parkera/swift,parkera/swift,return/swift,zisko/swift,glessard/swift,milseman/swift,alblue/swift,tkremenek/swift,tardieu/swift,rudkx/swift,jmgc/swift,shajrawi/swift,frootloops/swift,calebd/swift,tjw/swift,karwa/swift,ahoppen/swift,allevato/swift,tjw/swift,frootloops/swift,sschiau/swift,CodaFi/swift,felix91gr/swift,shahmishal/swift,aschwaighofer/swift,arvedviehweger/swift,codestergit/swift,JaSpa/swift,stephentyrone/swift,jopamer/swift,OscarSwanros/swift,apple/swift,apple/swift,jckarter/swift,djwbrown/swift,practicalswift/swift,deyton/swift,jopamer/swift,parkera/swift,harlanhaskins/swift,jmgc/swift,roambotics/swift,djwbrown/swift,gribozavr/swift,benlangmuir/swift,manavgabhawala/swift,parkera/swift,huonw/swift,amraboelela/swift,jtbandes/swift,tinysun212/swift-windows,shajrawi/swift,felix91gr/swift,roambotics/swift,ahoppen/swift,airspeedswift/swift,jtbandes/swift,djwbrown/swift,ahoppen/swift,tinysun212/swift-windows,devincoughlin/swift,tinysun212/swift-windows,JaSpa/swift,swiftix/swift,benlangmuir/swift,jtbandes/swift,amraboelela/swift,codestergit/swift,uasys/swift,milseman/swift,devincoughlin/swift,felix91gr/swift,lorentey/swift,OscarSwanros/swift,codestergit/swift,calebd/swift,Jnosh/swift,tjw/swift,rudkx/swift,manavgabhawala/swift,JaSpa/swift,zisko/swift,xedin/swift,jopamer/swift,allevato/swift,rudkx/swift,roambotics/swift,alblue/swift,rudkx/swift,lorentey/swift,shajrawi/swift,practicalswift/swift,jckarter/swift,stephentyrone/swift,natecook1000/swift,gribozavr/swift,calebd/swift,tjw/swift,practicalswift/swift,arvedviehweger/swift,gottesmm/swift,nathawes/swift,shahmishal/swift,Jnosh/swift,Jnosh/swift,hughbe/swift,nathawes/swift,practicalswift/swift,jmgc/swift,danielmartin/swift,jckarter/swift,devincoughlin/swift,shahmishal/swift,bitjammer/swift,shahmishal/swift,jtbandes/swift,jopamer/swift,airspeedswift/swift,gribozavr/swift,nathawes/swift,swiftix/swift,ahoppen/swift,djwbrown/swift,manavgabhawala/swift,hooman/swift,Jnosh/swift,codestergit/swift,gottesmm/swift,aschwaighofer/swift,sschiau/swift,calebd/swift,natecook1000/swift,roambotics/swift,allevato/swift,zisko/swift,karwa/swift,glessard/swift,airspeedswift/swift,gottesmm/swift,huonw/swift,djwbrown/swift,harlanhaskins/swift,hughbe/swift,practicalswift/swift,brentdax/swift,jopamer/swift,gottesmm/swift,return/swift,swiftix/swift,alblue/swift,frootloops/swift,amraboelela/swift,airspeedswift/swift,calebd/swift,karwa/swift,deyton/swift,allevato/swift,nathawes/swift,brentdax/swift,milseman/swift,tkremenek/swift,deyton/swift,gribozavr/swift,djwbrown/swift,OscarSwanros/swift,shajrawi/swift,lorentey/swift,jmgc/swift,xedin/swift,amraboelela/swift,jmgc/swift,frootloops/swift,CodaFi/swift,jckarter/swift,roambotics/swift,calebd/swift,alblue/swift,karwa/swift,deyton/swift,ahoppen/swift,deyton/swift | ---
+++
@@ -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.
#
# ----------------------------------------------------------------------------
@@ -21,9 +21,6 @@
assert len(sys.argv) >= 2
timeVal = int(sys.argv[1])
-# offset between Unix and LLVM epochs
-timeVal += 946684800
-
# Update the output file mtime, or create it if necessary.
# From http://stackoverflow.com/a/1160227.
for outputFile in sys.argv[1:]: |
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"."""
# First, we'll start a fake debugserver (a simple echo server).
fakeserver = pexpect.spawn('./EchoServer.py')
# Turn on logging for what the child sends back.
if self.TraceOn():
fakeserver.logfile_read = sys.stdout
# Schedule the fake debugserver to be shutting down during teardown.
def shutdown_fakeserver():
fakeserver.close()
self.addTearDownHook(shutdown_fakeserver)
# Wait until we receive the server ready message before continuing.
fakeserver.expect_exact('Listening on localhost:12345')
# Connect to the fake server....
self.runCmd("process connect connect://localhost:12345")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
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 start a fake debugserver (a simple echo server).
fakeserver = pexpect.spawn('./EchoServer.py')
# Turn on logging for what the child sends back.
if self.TraceOn():
fakeserver.logfile_read = sys.stdout
# Schedule the fake debugserver to be shutting down during teardown.
def shutdown_fakeserver():
fakeserver.close()
self.addTearDownHook(shutdown_fakeserver)
# Wait until we receive the server ready message before continuing.
fakeserver.expect_exact('Listening on localhost:12345')
# Connect to the fake server....
self.runCmd("process connect connect://localhost:12345")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| 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, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Canadian numbers."""
| # __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, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Canadian numbers."""
from stdnum.ca import bn as vat # noqa: F401
| 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...")
for n in xrange(0, 10000):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%1417773'")
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
| #!/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)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
| 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 xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
@@ -24,7 +27,7 @@
print("Selecting employees...")
while True:
cursor = connection.cursor()
- cursor.execute("select * from employees where name like '%1417773'")
+ cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close() |
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__ = "1.2"
| #!/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__ = "1.2.0"
| 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 AddressableComponent, VectorComponent, Signal
from .component import Field, Reg, Regfile, Addrmap, Mem
| 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
+
+from .component import AddressableComponent, VectorComponent, Signal
+from .component import Field, Reg, Regfile, Addrmap, Mem |
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 = ClassAttributes(class_item, (str, bool, object))
model.append([None, False, None])
path = Gtk.TreePath.new_first()
iter = model.get_iter(path)
model.update(iter, col=0, value="attr")
assert model[iter][-1] is class_item.subject.ownedAttribute[0]
| 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 = ClassAttributes(class_item, (str, bool, object))
model.append([None, False, None])
path = Gtk.TreePath.new_first()
iter = model.get_iter(path)
model.update(iter, col=0, value="attr")
assert model[iter][-1] is class_item.subject.ownedAttribute[0]
def test_enumeration_editing(case):
enum_item = case.create(EnumerationItem, UML.Enumeration)
model = ClassEnumerationLiterals(enum_item, (str, object))
model.append([None, None])
path = Gtk.TreePath.new_first()
iter = model.get_iter(path)
model.update(iter, col=0, value="enum")
assert model[iter][-1] is enum_item.subject.ownedLiteral[0]
| 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 (
+ ClassAttributes,
+ ClassEnumerationLiterals,
+)
-class TestClassPropertyPages:
- def test_attribute_editing(self, case):
- class_item = case.create(ClassItem, UML.Class)
- model = ClassAttributes(class_item, (str, bool, object))
- model.append([None, False, None])
- path = Gtk.TreePath.new_first()
- iter = model.get_iter(path)
- model.update(iter, col=0, value="attr")
+def test_attribute_editing(case):
+ class_item = case.create(ClassItem, UML.Class)
+ model = ClassAttributes(class_item, (str, bool, object))
+ model.append([None, False, None])
+ path = Gtk.TreePath.new_first()
+ iter = model.get_iter(path)
+ model.update(iter, col=0, value="attr")
- assert model[iter][-1] is class_item.subject.ownedAttribute[0]
+ assert model[iter][-1] is class_item.subject.ownedAttribute[0]
+
+
+def test_enumeration_editing(case):
+ enum_item = case.create(EnumerationItem, UML.Enumeration)
+ model = ClassEnumerationLiterals(enum_item, (str, object))
+ model.append([None, None])
+ path = Gtk.TreePath.new_first()
+ iter = model.get_iter(path)
+ model.update(iter, col=0, value="enum")
+
+ assert model[iter][-1] is enum_item.subject.ownedLiteral[0] |
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_filename(__name__, 'include')
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
| 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_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 = packages[0]
deps = packages[1:]
retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
| 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 = packages[0]
+ deps = packages[1:]
+
+ retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
+ retval += " - c/c++ dependencies:\n"
+ for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
+ retval += " - python dependencies:\n"
+ for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
+
+ return retval.strip()
+
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')] |
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)%(b - a) + 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.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N)
def wrap(x, a, b):
assert b > a
return (x - a)%(b - a) + a
| 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.randn()/np.sqrt(-np.log(rng.rand()))))*rng.randn()
+ return 10.0**(1.5 - 3*np.abs(rng.randn(N)/np.sqrt(-np.log(rng.rand(N)))))*rng.randn(N)
+
def wrap(x, a, b):
assert b > a |
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': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
]
}
| SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
],
'TokenSyntax': [
'BinaryOperatorExpr'
]
}
| 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,roambotics/swift,glessard/swift,benlangmuir/swift,atrick/swift,benlangmuir/swift,apple/swift,benlangmuir/swift,ahoppen/swift,benlangmuir/swift,roambotics/swift,apple/swift,gregomni/swift,JGiola/swift,gregomni/swift,gregomni/swift,apple/swift,gregomni/swift,gregomni/swift,JGiola/swift,ahoppen/swift,glessard/swift,glessard/swift,roambotics/swift,JGiola/swift,benlangmuir/swift,ahoppen/swift,roambotics/swift,rudkx/swift,rudkx/swift,gregomni/swift,JGiola/swift | ---
+++
@@ -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_SETTINGS['port'] = PORT
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
USE_SYSLOG = False
LOGGING_CONFIG = 'astral.conf.logconfig.initialize_logging'
LOGGING = {
'loggers': {
'astral': {},
},
'syslog_facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
'syslog_tag': "astral",
'log_level': LOG_LEVEL,
'use_syslog': USE_SYSLOG,
}
ASTRAL_WEBSERVER = "http://localhost:4567"
BOOTSTRAP_NODES = [
]
DOWNSTREAM_CHECK_LIMIT = 1024 * 1024 * 2
UPSTREAM_CHECK_LIMIT = 1024 * 256
OUTGOING_STREAM_LIMIT = 2
| 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_SETTINGS['port'] = PORT
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
USE_SYSLOG = False
LOGGING_CONFIG = 'astral.conf.logconfig.initialize_logging'
LOGGING = {
'loggers': {
'astral': {},
},
'syslog_facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
'syslog_tag': "astral",
'log_level': LOG_LEVEL,
'use_syslog': USE_SYSLOG,
}
if DEBUG:
ASTRAL_WEBSERVER = "http://localhost:4567"
else:
ASTRAL_WEBSERVER = "http://astral-video.heroku.com"
BOOTSTRAP_NODES = [
]
DOWNSTREAM_CHECK_LIMIT = 1024 * 1024 * 2
UPSTREAM_CHECK_LIMIT = 1024 * 256
OUTGOING_STREAM_LIMIT = 2
| 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/$',
MyAccountView.as_view(),
name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
| 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/$',
MyAccountView.as_view(),
name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/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<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
| 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/reviewboard,bkochendorfer/reviewboard,sgallagher/reviewboard,sgallagher/reviewboard,beol/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,1tush/reviewboard,brennie/reviewboard,sgallagher/reviewboard,1tush/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,custode/reviewboard,beol/reviewboard,chipx86/reviewboard,beol/reviewboard,davidt/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,KnowNo/reviewboard,1tush/reviewboard,chipx86/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,brennie/reviewboard,reviewboard/reviewboard | ---
+++
@@ -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<token>.+)/$', |
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 = Column(Integer, primary_key=True)
globalName = Column(String(250), nullable=False)
nickname = Column(String(250), nullable=True)
role = Column(String(250), nullable=True)
points = Column(Integer, nullable=True)
def __init__(self,id,globalAccountName,serverNickname,role,points):
self.id = id
self.globalAccountName = globalAccountName
self.serverNickname = serverNickname
self.role = role
self.points = points
#Display member method.
def displayMember(self):
print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points)
#Example of creating one object, changing value of an object and displaying an object using a method.
'''mem1 = Member(43344454,"larry","doessuck","officer",150)
mem1.globalAccountName="Jack"
mem1.displayMember()'''
engine = create_engine('sqlite:///bayohwoolph.db')
Base.metadata.create_all(engine) | #!/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 = Column(Integer, primary_key=True)
globalName = Column(String(250), nullable=True)
nickname = Column(String(250), nullable=True)
role = Column(String(250), nullable=True)
points = Column(Integer, nullable=True)
def __init__(self,id,globalAccountName,serverNickname,role,points):
self.id = id
self.globalAccountName = globalAccountName
self.serverNickname = serverNickname
self.role = role
self.points = points
#Display member method.
def displayMember(self):
print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points)
#Example of creating one object, changing value of an object and displaying an object using a method.
'''mem1 = Member(43344454,"larry","doessuck","officer",150)
mem1.globalAccountName="Jack"
mem1.displayMember()'''
engine = create_engine('sqlite:///bayohwoolph.db')
Base.metadata.create_all(engine)
| 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 = Column(Integer, nullable=True) |
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
def test_bad_domain_fails(webapp):
"""Test the analyse page checks domain validity."""
with pytest.raises(webtest.app.AppError) as err:
webapp.get('/analyse/3234jskdnfsdf7y34')
assert '400 BAD REQUEST' in err.value.message
| 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 analyse page checks domain validity."""
+ with pytest.raises(webtest.app.AppError) as err:
+ webapp.get('/analyse/3234jskdnfsdf7y34')
+ assert '400 BAD REQUEST' in err.value.message |
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 @-mention, it initially
replies with one message containing a `1`. Every time the bot
is @-mentioned, this number will be incremented in the same message.
'''
def handle_message(self, message, bot_handler, state_handler):
self.number += 1
if self.message_id is None:
result = bot_handler.send_reply(message, str(self.number))
self.message_id = result['id']
else:
bot_handler.update_message(dict(
message_id=self.message_id,
content=str(self.number),
))
handler_class = IncrementorHandler
| # 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 the bot
is @-mentioned, this number will be incremented in the same message.
'''
def handle_message(self, message, bot_handler, state_handler):
state = state_handler.get_state() or {'number': 0, 'message_id': None}
state['number'] += 1
state_handler.set_state(state)
if state['message_id'] is None:
result = bot_handler.send_reply(message, str(state['number']))
state['message_id'] = result['id']
state_handler.set_state(state)
else:
bot_handler.update_message(dict(
message_id = state['message_id'],
content = str(state['number'])
))
handler_class = IncrementorHandler
| 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,punchagan/zulip,vaidap/zulip,synicalsyntax/zulip,vaidap/zulip,verma-varsha/zulip,vabs22/zulip,tommyip/zulip,jackrzhang/zulip,punchagan/zulip,Galexrt/zulip,amanharitsh123/zulip,verma-varsha/zulip,hackerkid/zulip,brockwhittaker/zulip,jackrzhang/zulip,showell/zulip,jrowan/zulip,showell/zulip,Galexrt/zulip,vaidap/zulip,synicalsyntax/zulip,tommyip/zulip,synicalsyntax/zulip,brainwane/zulip,jackrzhang/zulip,mahim97/zulip,eeshangarg/zulip,hackerkid/zulip,kou/zulip,eeshangarg/zulip,dhcrzf/zulip,kou/zulip,dhcrzf/zulip,rishig/zulip,rht/zulip,showell/zulip,andersk/zulip,dhcrzf/zulip,Galexrt/zulip,punchagan/zulip,synicalsyntax/zulip,zulip/zulip,andersk/zulip,dhcrzf/zulip,tommyip/zulip,timabbott/zulip,tommyip/zulip,vabs22/zulip,timabbott/zulip,kou/zulip,jrowan/zulip,jackrzhang/zulip,jrowan/zulip,amanharitsh123/zulip,vaidap/zulip,rht/zulip,eeshangarg/zulip,rht/zulip,amanharitsh123/zulip,shubhamdhama/zulip,rht/zulip,brainwane/zulip,mahim97/zulip,mahim97/zulip,jrowan/zulip,brockwhittaker/zulip,brainwane/zulip,brainwane/zulip,punchagan/zulip,dhcrzf/zulip,rht/zulip,zulip/zulip,mahim97/zulip,kou/zulip,kou/zulip,shubhamdhama/zulip,Galexrt/zulip,shubhamdhama/zulip,vaidap/zulip,jrowan/zulip,brockwhittaker/zulip,timabbott/zulip,hackerkid/zulip,andersk/zulip,mahim97/zulip,eeshangarg/zulip,andersk/zulip,brockwhittaker/zulip,brockwhittaker/zulip,punchagan/zulip,rishig/zulip,timabbott/zulip,amanharitsh123/zulip,shubhamdhama/zulip,showell/zulip,eeshangarg/zulip,jackrzhang/zulip,andersk/zulip,eeshangarg/zulip,zulip/zulip,amanharitsh123/zulip,zulip/zulip,shubhamdhama/zulip,dhcrzf/zulip,verma-varsha/zulip,rht/zulip,tommyip/zulip,showell/zulip,dhcrzf/zulip,tommyip/zulip,showell/zulip,hackerkid/zulip,tommyip/zulip,vabs22/zulip,verma-varsha/zulip,shubhamdhama/zulip,synicalsyntax/zulip,brainwane/zulip,showell/zulip,rishig/zulip,synicalsyntax/zulip,shubhamdhama/zulip,rishig/zulip,vaidap/zulip,hackerkid/zulip,Galexrt/zulip,vabs22/zulip,brainwane/zulip,Galexrt/zulip,brockwhittaker/zulip,rishig/zulip,zulip/zulip,amanharitsh123/zulip,rishig/zulip,jrowan/zulip,kou/zulip,andersk/zulip,synicalsyntax/zulip,vabs22/zulip,andersk/zulip | ---
+++
@@ -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 += 1
- if self.message_id is None:
- result = bot_handler.send_reply(message, str(self.number))
- self.message_id = result['id']
+ state = state_handler.get_state() or {'number': 0, 'message_id': None}
+ state['number'] += 1
+ state_handler.set_state(state)
+ if state['message_id'] is None:
+ result = bot_handler.send_reply(message, str(state['number']))
+ state['message_id'] = result['id']
+ state_handler.set_state(state)
else:
bot_handler.update_message(dict(
- message_id=self.message_id,
- content=str(self.number),
+ message_id = state['message_id'],
+ content = str(state['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.
description = db.StringField(required = True)
# The owner of the entry.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class CategoryBudget(db.Document):
# The amount of the budget.
amount = db.DecimalField(precision = 2, required = True)
# The category.
category = db.ReferenceField(Category, required = True)
def sumEntries():
return sum([entry.amount for entry in Entry.objects if entry.amount > 0])
| 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.
description = db.StringField(required = True)
# The owner of the entry.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class Expense(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the expense.
description = db.StringField(required = True)
# The owner of the expense.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class CategoryBudget(db.Document):
# The amount of the budget.
amount = db.DecimalField(precision = 2, required = True)
# The category.
category = db.ReferenceField(Category, required = True)
def sumEntries():
return sum([entry.amount for entry in Entry.objects if entry.amount > 0])
| 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 = True)
# The owner of the entry.
+ # Should the owner be deleted, we also want to delete all of his entries.
+ owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
+
+ # The category of this entry.
+ category = db.ReferenceField(Category, required = True)
+
+class Expense(db.Document):
+ # The amount of the entry.
+ amount = db.DecimalField(precision = 2, required = True)
+
+ # A short description for the expense.
+ description = db.StringField(required = True)
+
+ # The owner of the expense.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
|
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(unidecode(self.instance.name))
super(CollectionForm, self).save(commit=commit)
return self.instance
| 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 save(self, commit=True):
+ self.instance.slug = slugify(unidecode(self.instance.name))
+ super(CollectionForm, self).save(commit=commit)
+ return self.instance |
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.Column(db.String())
graphs = db.relationship("Graph", backref="user", lazy="dynamic")
def __init__(self, username, email, name, password):
self.username = username
self.email = email
self.name = name
self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8")
def __repr__(self):
return self.username
def check_password(self, password):
return bcrypt.check_password_hash(self.pw_hash, password)
class Graph(db.Model):
__tablename__ = "graphs"
id = db.Column(db.Integer, primary_key=True)
created_at = db.Column(db.DateTime)
title = db.Column(db.String())
serialized_string = db.Column(db.String())
user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
def __init__(self, serialized_string):
self.created_at = datetime.utcnow()
self.serialized_string = serialized_string
def __repr__(self):
return self.title
| 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.Column(db.String())
graphs = db.relationship("Graph", backref="user", lazy="dynamic")
def __init__(self, username, email, name, password):
self.username = username
self.email = email
self.name = name
self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8")
def __repr__(self):
return self.username
def check_password(self, password):
return bcrypt.check_password_hash(self.pw_hash, password)
class Graph(db.Model):
__tablename__ = "graphs"
id = db.Column(db.Integer, primary_key=True)
created_at = db.Column(db.DateTime)
title = db.Column(db.String())
serialized_string = db.Column(db.String())
user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
def __init__(self, title, serialized_string):
self.created_at = datetime.utcnow()
self.title = title
self.serialized_string = serialized_string
def __repr__(self):
return self.title
| 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
self.serialized_string = serialized_string
def __repr__(self): |
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)
address_1 = models.CharField(max_length=150, blank=True)
address_2 = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=100, blank=True)
region = models.CharField(max_length=100, blank=True)
zipcode = models.CharField(max_length=100, blank=True)
country = EnumField(CountryEnum)
| 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_length=100, blank=True)
address_1 = models.CharField(max_length=150, blank=True)
address_2 = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=100, blank=True)
region = models.CharField(max_length=100, blank=True)
zipcode = models.CharField(max_length=100, blank=True)
country = EnumField(CountryEnum)
| 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
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
| 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,danielsamuels/django-registration,awakeup/django-registration,ubernostrum/django-registration,sandipagr/django-registration,gone/django-registration,hacklabr/django-registration | ---
+++
@@ -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."
+ 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
+ # | {a|b|c}N - for alpha, beta and rc releases
+
+ parts = 2 if VERSION[2] == 0 else 3
+ main = '.'.join(str(x) for x in VERSION[:parts])
+
+ sub = ''
+ if VERSION[3] != 'final':
+ mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
+ sub = mapping[VERSION[3]] + str(VERSION[4])
+
+ return str(main + sub) |
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 blueprint
api = Blueprint('api', __name__)
# Import the endpoints belonging to this blueprint
from . import endpoints
from . import errors
@api.before_request
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'])
if token == app.config['SECRET_TOKEN']:
app.logger.info('Validated request token')
app.logger.warn('Unauthorized: Invalid request token')
app.logger.warn('Unauthorized: No request token included')
return jsonify({'error': 'unauthorized'}), 401
app.logger.info('No authentication required')
# register blueprints
app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
| 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 blueprint
api = Blueprint('api', __name__)
# Import the endpoints belonging to this blueprint
from . import endpoints
from . import errors
@api.before_request
def before_request():
"""All routes in this blueprint require authentication."""
if app.config['AUTH_REQUIRED']:
token_header = app.config['TOKEN_HEADER']
if request.headers.get(token_header):
token = request.headers[token_header]
if token == app.config['SECRET_TOKEN']:
app.logger.info('Validated request token')
app.logger.warn('Unauthorized: Invalid request token')
app.logger.warn('Unauthorized: No request token included')
return jsonify({'error': 'unauthorized'}), 401
app.logger.info('No authentication required')
# register blueprints
app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
| 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']
+ if request.headers.get(token_header):
+ token = request.headers[token_header]
if token == app.config['SECRET_TOKEN']:
app.logger.info('Validated request token')
app.logger.warn('Unauthorized: Invalid request token') |
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='jupyter', IpPermissions=[{'PrefixListIds': [], 'UserIdGroupPairs': [], 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'IpProtocol': 'tcp', 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'ToPort': 8888, 'FromPort': 8888}])
print("create a security group")
except botocore.exceptions.ClientError as e:
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'])
print_res = False
while (not print_res):
time.sleep(1)
for i in ec2.instances.filter(InstanceIds=[o[0].id]):
if i.public_ip_address is not None:
print("The public IP address: " + str(i.public_ip_address))
print_res = True
| 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='jupyter', IpPermissions=[{'PrefixListIds': [], 'UserIdGroupPairs': [], 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'IpProtocol': 'tcp', 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'ToPort': 8888, 'FromPort': 8888}])
print("create a security group")
except botocore.exceptions.ClientError as e:
sg = client.describe_security_groups(GroupNames=['jupyter'])
print("the security group exist")
o = ec2.create_instances(ImageId='ami-622a0119', MinCount=1, MaxCount=1, InstanceType='i3.8xlarge', SecurityGroups=['jupyter'])
print_res = False
while (not print_res):
time.sleep(1)
for i in ec2.instances.filter(InstanceIds=[o[0].id]):
if i.public_ip_address is not None:
print("The public IP address: " + str(i.public_ip_address))
print_res = True
| 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', MinCount=1, MaxCount=1, InstanceType='i3.8xlarge', SecurityGroups=['jupyter'])
print_res = False
while (not print_res):
time.sleep(1) |
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,
indent=4,
separators=(', ', ': ')
), mimetype='application/json')
return new_f
@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
return Story.find()
@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
return Story.get(story_id)
if __name__ == '__main__':
app.run(debug=True) | 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 new_f(*args, **kwargs):
result = inner_f(*args, **kwargs)
return Response(json.dumps(
result,
indent=4,
separators=(', ', ': ')
), mimetype='application/json')
return new_f
@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
return Story.find()
@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
return Story.get(story_id)
if __name__ == '__main__':
app.run(debug=True) | 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 = serializers.Field(source='timesince')
class Meta:
model = Notification
fields = ('target', 'action_object', 'actor', 'verb', 'timesince',
'date_created', 'date_modified')
| 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.SerializerMethodField('get_action_object_data')
actor = serializers.Field(source='data.sender')
timesince = serializers.Field(source='timesince')
class Meta:
model = Notification
fields = ('target', 'action_object', 'actor', 'verb', 'timesince',
'date_created', 'date_modified')
def get_action_object_data(self, obj):
return self._data_with_signed_urls(obj.data['action_object'])
def get_target_data(self, obj):
return self._data_with_signed_urls(obj.data['target'])
def _data_with_signed_urls(self, data):
thumbnail_keys = [
'thumbnail_sm_path',
'thumbnail_md_path',
'thumbnail_lg_path'
]
for key, value in data.items():
if key in thumbnail_keys and value:
split_results = list(tuple(parse.urlsplit(value)))
split_results[-2] = ''
cleaned_url = parse.unquote(parse.urlunsplit(split_results))
data[key] = sign_s3_url(cleaned_url)
return data
| 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')
- action_object = serializers.Field(source='data.action_object')
+ target = serializers.SerializerMethodField('get_target_data')
+ action_object = serializers.SerializerMethodField('get_action_object_data')
actor = serializers.Field(source='data.sender')
timesince = serializers.Field(source='timesince')
@@ -13,3 +16,25 @@
model = Notification
fields = ('target', 'action_object', 'actor', 'verb', 'timesince',
'date_created', 'date_modified')
+
+ def get_action_object_data(self, obj):
+ return self._data_with_signed_urls(obj.data['action_object'])
+
+ def get_target_data(self, obj):
+ return self._data_with_signed_urls(obj.data['target'])
+
+ def _data_with_signed_urls(self, data):
+ thumbnail_keys = [
+ 'thumbnail_sm_path',
+ 'thumbnail_md_path',
+ 'thumbnail_lg_path'
+ ]
+
+ for key, value in data.items():
+ if key in thumbnail_keys and value:
+ split_results = list(tuple(parse.urlsplit(value)))
+ split_results[-2] = ''
+ cleaned_url = parse.unquote(parse.urlunsplit(split_results))
+ data[key] = sign_s3_url(cleaned_url)
+
+ return data |
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_value).roots
positive_roots = [root for root in roots if root > 0]
if len(positive_roots) > 0:
return positive_roots[0]
else:
raise ValueError("No corresponding positive machine value:", roots)
class UcPchip():
def __init__(self, x, y):
self.x = x
self.y = y
self.pp = PchipInterpolator(x, y)
def machine_to_physics(self, machine_value):
return self.pp(machine_value)
def physics_to_machine(self, physics_value):
pass
| 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 - physics_value).roots
positive_roots = [root for root in roots if root > 0]
if len(positive_roots) > 0:
return positive_roots[0]
else:
raise ValueError("No corresponding positive machine value:", roots)
class UcPchip(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.pp = PchipInterpolator(x, y)
def machine_to_physics(self, machine_value):
return self.pp(machine_value)
def physics_to_machine(self, physics_value):
pass
| 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 UcPchip(object):
def __init__(self, x, y):
self.x = x
self.y = y |
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.
"""
import os
import importlib
from functools import wraps
from . import cython
try:
from . import numba
except ModuleNotFoundError:
numba = None
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']
if mod.lower() not in ('cython', 'numba'):
# Use python function
if verbose:
print(func.__name__ + ' not optimized')
return func
mod = importlib.import_module('shenfun.optimization.'+mod.lower())
fun = getattr(mod, func.__name__, func)
if verbose:
if fun is func:
print(fun.__name__ + ' not optimized')
@wraps(func)
def wrapped_function(*args, **kwargs):
u0 = fun(*args, **kwargs)
return u0
return wrapped_function
| """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.
"""
import os
import importlib
from functools import wraps
from . import cython
try:
from . import numba
except ModuleNotFoundError:
numba = None
def optimizer(func):
"""Decorator used to wrap calls to optimized versions of functions."""
from shenfun.config import config
mod = 'cython'
verbose = False
try:
mod = config['optimization']['mode']
verbose = config['optimization']['verbose']
except KeyError:
pass
if mod.lower() not in ('cython', 'numba'):
# Use python function
if verbose:
print(func.__name__ + ' not optimized')
return func
mod = importlib.import_module('shenfun.optimization.'+mod.lower())
fun = getattr(mod, func.__name__, func)
if verbose:
if fun is func:
print(fun.__name__ + ' not optimized')
@wraps(func)
def wrapped_function(*args, **kwargs):
u0 = fun(*args, **kwargs)
return u0
return wrapped_function
| 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 = config['optimization']['mode']
+ verbose = config['optimization']['verbose']
+ except KeyError:
+ pass
+
if mod.lower() not in ('cython', 'numba'):
# Use python function
if verbose: |
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 <a> elements by
replacing the internal <a> element with its content.
Assumes that the text does not span multiple lines and that
the <a> tags are lowercase.
"""
while True:
text, sub_count = link_inside_link_regex.subn(
ur"\g<outer_link>\g<internal_content>", text)
if sub_count == 0:
return text # Return only when no more subs possible
| 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 flatten_links(text):
"""
Fix <a> elements that have embedded <a> elements by
replacing the internal <a> element with its content.
"""
while True:
text, sub_count = link_inside_link_regex.subn(
ur"\g<outer_link>\g<inner_content>", text)
if sub_count == 0:
return text
| 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<internal_content>((?!</a>).)*)</a>)",
+ ur"(?P<outer_link><a ((?!</a>).)*)<a .*?>(?P<inner_content>.*?)</a>",
re.IGNORECASE | re.DOTALL)
@@ -11,12 +12,10 @@
"""
Fix <a> elements that have embedded <a> elements by
replacing the internal <a> element with its content.
- Assumes that the text does not span multiple lines and that
- the <a> tags are lowercase.
"""
while True:
text, sub_count = link_inside_link_regex.subn(
- ur"\g<outer_link>\g<internal_content>", text)
+ ur"\g<outer_link>\g<inner_content>", text)
if sub_count == 0:
- return text # Return only when no more subs possible
+ return text |
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())))
self.trainer = BERTTrainer(output_dir=self.output_dir)
self.data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
def train_model(self):
self.trainer.train(self.data['abstract'], self.data['section'])
def test_train(self):
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.data['section'])
eval_acc1, eval_acc2 = results['eval_accuracy'], results2['eval_accuracy']
self.assertEqual(eval_acc1, eval_acc2)
loss1, loss2 = results['loss'], results2['loss']
self.assertEqual(eval_acc1, eval_acc2)
shutil.rmtree(self.output_dir)
def test_train_and_predict(self):
self.train_model()
input_sentences = [
"test four",
"test one",
] * 5
preds = self.trainer.predict(input_sentences)
shutil.rmtree(self.output_dir)
if __name__ == '__main__':
unittest.main()
| 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())))
self.trainer = BERTTrainer(output_dir=self.output_dir)
self.data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
def train_model(self):
self.trainer.train(self.data['abstract'], self.data['section'])
def test_train(self):
self.train_model()
shutil.rmtree(self.output_dir)
def test_train_and_predict(self):
self.train_model()
input_sentences = [
"test four",
"test one",
] * 5
preds = self.trainer.predict(input_sentences)
shutil.rmtree(self.output_dir)
if __name__ == '__main__':
unittest.main()
| 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.data['section'])
- eval_acc1, eval_acc2 = results['eval_accuracy'], results2['eval_accuracy']
- self.assertEqual(eval_acc1, eval_acc2)
- loss1, loss2 = results['loss'], results2['loss']
- self.assertEqual(eval_acc1, eval_acc2)
- shutil.rmtree(self.output_dir)
-
def test_train_and_predict(self):
self.train_model()
input_sentences = [ |
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 serverio.'))
password = forms.CharField(label=_(u'Slaptažodis'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_(u'Naudotojo vardas arba slaptažodis '
'yra neteisingi'))
return {'user': user}
| #! 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 serverio.'))
password = forms.CharField(label=_(u'Slaptažodis'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_(u'Naudotojo vardas arba slaptažodis '
'yra neteisingi'))
cleaned_data['user'] = user
return cleaned_data
| 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, None)
else:
os.makedirs(directory)
if filename is not None:
open(file_path, 'a').close()
return file_path
def run_cmd(command, **kwargs):
""" Runs a command and returns an array of its results
: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']
try:
ret = check_call(command, shell=True, cwd=cwd)
return {'success': True, 'return': ret, 'exception': None}
except CalledProcessError as exc:
return {'success': False,
'return': None,
'exception': exc,
'command': command}
@contextmanager
def cleanup(stage):
try:
yield
except (Exception, KeyboardInterrupt):
LOG.exception('Run failed')
finally:
stage.destroy()
def rand_name(prefix):
return '{}-{}'.format(prefix, str(uuid.uuid4()))
| 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, None)
else:
os.makedirs(directory)
if filename is not None:
open(file_path, 'a').close()
return file_path
def run_cmd(command, **kwargs):
""" Runs a command and returns an array of its results
:param command: String of a command to run within a shell
:returns: Dictionary with keys relating to the execution's success
"""
cwd = kwargs.get('cwd', None)
try:
ret = check_call(command, shell=True, cwd=cwd)
return {'success': True, 'return': ret, 'exception': None}
except CalledProcessError as exc:
return {'success': False,
'return': None,
'exception': exc,
'command': command}
@contextmanager
def cleanup(stage):
try:
yield
except (Exception, KeyboardInterrupt):
LOG.exception('Run failed')
finally:
stage.destroy()
def rand_name(prefix):
return '{}-{}'.format(prefix, str(uuid.uuid4()))
| 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, cwd=cwd) |
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.argv:
from os import getenv
from sqlalchemy import create_engine
from sqlalchemy.ext.sqlsoup import SqlSoup
import code
engine = create_engine(config.CONFIG["DB_URL"], echo=True)
db = SqlSoup(engine)
Visit = db.visit
Keys = db.keys
class FunkyConsole(code.InteractiveConsole):
def showtraceback(self):
import pdb
import sys
code.InteractiveConsole.showtraceback(self)
pdb.post_mortem(sys.exc_info()[2])
console = FunkyConsole(locals=globals())
if getenv("PYTHONSTARTUP"):
execfile(getenv("PYTHONSTARTUP"))
console.interact()
else:
from pystil.service.http import Application
from gevent import monkey
monkey.patch_all()
import gevent.wsgi
application = Application(werkzeug.contrib.fixers.ProxyFix(app()))
ws = gevent.wsgi.WSGIServer(('', 1789), application)
ws.serve_forever()
| #!/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 sys.argv:
from os import getenv
from sqlalchemy import create_engine
from sqlalchemy.ext.sqlsoup import SqlSoup
import code
engine = create_engine(config.CONFIG["DB_URL"], echo=True)
db = SqlSoup(engine)
Visit = db.visit
Keys = db.keys
class FunkyConsole(code.InteractiveConsole):
def showtraceback(self):
import pdb
import sys
code.InteractiveConsole.showtraceback(self)
pdb.post_mortem(sys.exc_info()[2])
console = FunkyConsole(locals=globals())
if getenv("PYTHONSTARTUP"):
execfile(getenv("PYTHONSTARTUP"))
console.interact()
else:
from pystil.service.http import Application
from gevent import monkey
monkey.patch_all()
import gevent.wsgi
application = werkzeug.contrib.fixers.ProxyFix(Application(app()))
ws = gevent.wsgi.WSGIServer(('', 1789), application)
ws.serve_forever()
| 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 = Application(werkzeug.contrib.fixers.ProxyFix(app()))
+ application = werkzeug.contrib.fixers.ProxyFix(Application(app()))
ws = gevent.wsgi.WSGIServer(('', 1789), application)
ws.serve_forever() |
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 have English documentation
locale = "en_us"
def get_doc_url(token):
try:
return config.get(locale, token)
except ConfigParser.NoOptionError:
return config.get(locale, "default")
return {"doc_url": get_doc_url}
| 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 documentation
locale = "en_us"
def get_doc_url(token):
try:
return config.get(locale, token)
except ConfigParser.NoOptionError:
return config.get(locale, "default")
return {"doc_url": get_doc_url}
| 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-platform,ahmadiga/min_edx,wwj718/edx-platform,edx/edx-platform,morenopc/edx-platform,leansoft/edx-platform,cyanna/edx-platform,shubhdev/edxOnBaadal,leansoft/edx-platform,SivilTaram/edx-platform,shabab12/edx-platform,zadgroup/edx-platform,dsajkl/123,pku9104038/edx-platform,antoviaque/edx-platform,ovnicraft/edx-platform,mahendra-r/edx-platform,zhenzhai/edx-platform,eestay/edx-platform,abdoosh00/edraak,jjmiranda/edx-platform,leansoft/edx-platform,nikolas/edx-platform,longmen21/edx-platform,jruiperezv/ANALYSE,kamalx/edx-platform,Kalyzee/edx-platform,andyzsf/edx,CourseTalk/edx-platform,beacloudgenius/edx-platform,chauhanhardik/populo_2,fly19890211/edx-platform,rismalrv/edx-platform,hkawasaki/kawasaki-aio8-0,teltek/edx-platform,openfun/edx-platform,devs1991/test_edx_docmode,shubhdev/openedx,zadgroup/edx-platform,waheedahmed/edx-platform,Kalyzee/edx-platform,vasyarv/edx-platform,shubhdev/openedx,louyihua/edx-platform,Shrhawk/edx-platform,don-github/edx-platform,alu042/edx-platform,zhenzhai/edx-platform,mcgachey/edx-platform,mitocw/edx-platform,xuxiao19910803/edx-platform,LICEF/edx-platform,jswope00/griffinx,y12uc231/edx-platform,nanolearning/edx-platform,inares/edx-platform,benpatterson/edx-platform,ahmedaljazzar/edx-platform,mjirayu/sit_academy,gsehub/edx-platform,deepsrijit1105/edx-platform,Stanford-Online/edx-platform,zofuthan/edx-platform,playm2mboy/edx-platform,a-parhom/edx-platform,miptliot/edx-platform,playm2mboy/edx-platform,beni55/edx-platform,alu042/edx-platform,LICEF/edx-platform,naresh21/synergetics-edx-platform,bigdatauniversity/edx-platform,AkA84/edx-platform,caesar2164/edx-platform,WatanabeYasumasa/edx-platform,4eek/edx-platform,AkA84/edx-platform,UOMx/edx-platform,openfun/edx-platform,pku9104038/edx-platform,eestay/edx-platform,ampax/edx-platform,doganov/edx-platform,synergeticsedx/deployment-wipro,hkawasaki/kawasaki-aio8-0,jzoldak/edx-platform,franosincic/edx-platform,jswope00/griffinx,hkawasaki/kawasaki-aio8-2,proversity-org/edx-platform,dcosentino/edx-platform,dkarakats/edx-platform,tanmaykm/edx-platform,appliedx/edx-platform,nagyistoce/edx-platform,knehez/edx-platform,openfun/edx-platform,torchingloom/edx-platform,alu042/edx-platform,iivic/BoiseStateX,a-parhom/edx-platform,xuxiao19910803/edx-platform,etzhou/edx-platform,SravanthiSinha/edx-platform,pomegranited/edx-platform,EDUlib/edx-platform,cognitiveclass/edx-platform,arifsetiawan/edx-platform,cselis86/edx-platform,Ayub-Khan/edx-platform,vismartltd/edx-platform,unicri/edx-platform,kursitet/edx-platform,adoosii/edx-platform,fintech-circle/edx-platform,bitifirefly/edx-platform,mitocw/edx-platform,zerobatu/edx-platform,solashirai/edx-platform,doismellburning/edx-platform,proversity-org/edx-platform,xuxiao19910803/edx,ampax/edx-platform-backup,jazztpt/edx-platform,ak2703/edx-platform,cecep-edu/edx-platform,jelugbo/tundex,RPI-OPENEDX/edx-platform,chauhanhardik/populo_2,BehavioralInsightsTeam/edx-platform,rhndg/openedx,martynovp/edx-platform,tiagochiavericosta/edx-platform,jamiefolsom/edx-platform,nanolearning/edx-platform,BehavioralInsightsTeam/edx-platform,doganov/edx-platform,vasyarv/edx-platform,edry/edx-platform,tiagochiavericosta/edx-platform,fintech-circle/edx-platform,DefyVentures/edx-platform,OmarIthawi/edx-platform,jamesblunt/edx-platform,ZLLab-Mooc/edx-platform,alexthered/kienhoc-platform,devs1991/test_edx_docmode,cecep-edu/edx-platform,tiagochiavericosta/edx-platform,Edraak/edx-platform,jelugbo/tundex,motion2015/edx-platform,nanolearningllc/edx-platform-cypress-2,rismalrv/edx-platform,halvertoluke/edx-platform,mbareta/edx-platform-ft,marcore/edx-platform,miptliot/edx-platform,vikas1885/test1,B-MOOC/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,Livit/Livit.Learn.EdX,appsembler/edx-platform,amir-qayyum-khan/edx-platform,playm2mboy/edx-platform,nanolearningllc/edx-platform-cypress,procangroup/edx-platform,J861449197/edx-platform,nttks/jenkins-test,jbassen/edx-platform,ovnicraft/edx-platform,appliedx/edx-platform,gymnasium/edx-platform,mushtaqak/edx-platform,marcore/edx-platform,hkawasaki/kawasaki-aio8-2,ferabra/edx-platform,mbareta/edx-platform-ft,kursitet/edx-platform,nagyistoce/edx-platform,hkawasaki/kawasaki-aio8-1,ovnicraft/edx-platform,inares/edx-platform,jonathan-beard/edx-platform,IndonesiaX/edx-platform,UOMx/edx-platform,marcore/edx-platform,peterm-itr/edx-platform,shashank971/edx-platform,devs1991/test_edx_docmode,Shrhawk/edx-platform,naresh21/synergetics-edx-platform,morenopc/edx-platform,nanolearningllc/edx-platform-cypress-2,zofuthan/edx-platform,zhenzhai/edx-platform,EDUlib/edx-platform,polimediaupv/edx-platform,procangroup/edx-platform,jazztpt/edx-platform,atsolakid/edx-platform,stvstnfrd/edx-platform,doismellburning/edx-platform,xingyepei/edx-platform,jswope00/griffinx,hamzehd/edx-platform,motion2015/edx-platform,Edraak/circleci-edx-platform,sudheerchintala/LearnEraPlatForm,xinjiguaike/edx-platform,nttks/jenkins-test,mushtaqak/edx-platform,alu042/edx-platform,analyseuc3m/ANALYSE-v1,appliedx/edx-platform,chudaol/edx-platform,ahmadiga/min_edx,sameetb-cuelogic/edx-platform-test,romain-li/edx-platform,ESOedX/edx-platform,simbs/edx-platform,abdoosh00/edraak,chauhanhardik/populo,TeachAtTUM/edx-platform,shubhdev/edx-platform,gsehub/edx-platform,martynovp/edx-platform,ampax/edx-platform,appliedx/edx-platform,vikas1885/test1,IONISx/edx-platform,TeachAtTUM/edx-platform,shabab12/edx-platform,dsajkl/123,shubhdev/edxOnBaadal,hastexo/edx-platform,hkawasaki/kawasaki-aio8-2,prarthitm/edxplatform,cecep-edu/edx-platform,ubc/edx-platform,shurihell/testasia,kamalx/edx-platform,valtech-mooc/edx-platform,polimediaupv/edx-platform,motion2015/a3,antoviaque/edx-platform,JioEducation/edx-platform,prarthitm/edxplatform,benpatterson/edx-platform,defance/edx-platform,cognitiveclass/edx-platform,romain-li/edx-platform,hkawasaki/kawasaki-aio8-2,nanolearningllc/edx-platform-cypress,UXE/local-edx,zerobatu/edx-platform,xuxiao19910803/edx,peterm-itr/edx-platform,synergeticsedx/deployment-wipro,Stanford-Online/edx-platform,Semi-global/edx-platform,caesar2164/edx-platform,atsolakid/edx-platform,DNFcode/edx-platform,ahmadio/edx-platform,ahmadio/edx-platform,mahendra-r/edx-platform,polimediaupv/edx-platform,10clouds/edx-platform,rhndg/openedx,xuxiao19910803/edx-platform,kmoocdev2/edx-platform,shubhdev/edxOnBaadal,wwj718/edx-platform,vikas1885/test1,ahmedaljazzar/edx-platform,J861449197/edx-platform,inares/edx-platform,atsolakid/edx-platform,abdoosh00/edraak,UOMx/edx-platform,jazkarta/edx-platform-for-isc,simbs/edx-platform,nanolearningllc/edx-platform-cypress-2,OmarIthawi/edx-platform,shubhdev/openedx,ampax/edx-platform-backup,stvstnfrd/edx-platform,synergeticsedx/deployment-wipro,itsjeyd/edx-platform,romain-li/edx-platform,analyseuc3m/ANALYSE-v1,chand3040/cloud_that,SivilTaram/edx-platform,mushtaqak/edx-platform,msegado/edx-platform,beni55/edx-platform,hamzehd/edx-platform,Ayub-Khan/edx-platform,vikas1885/test1,kamalx/edx-platform,eduNEXT/edunext-platform,jazkarta/edx-platform,mahendra-r/edx-platform,OmarIthawi/edx-platform,defance/edx-platform,andyzsf/edx,CourseTalk/edx-platform,arifsetiawan/edx-platform,JioEducation/edx-platform,chrisndodge/edx-platform,openfun/edx-platform,kmoocdev2/edx-platform,IONISx/edx-platform,yokose-ks/edx-platform,shurihell/testasia,wwj718/ANALYSE,alexthered/kienhoc-platform,solashirai/edx-platform,tanmaykm/edx-platform,mjirayu/sit_academy,chudaol/edx-platform,cognitiveclass/edx-platform,kxliugang/edx-platform,ahmadiga/min_edx,Edraak/edraak-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,knehez/edx-platform,fly19890211/edx-platform,jonathan-beard/edx-platform,sameetb-cuelogic/edx-platform-test,AkA84/edx-platform,cyanna/edx-platform,zhenzhai/edx-platform,kmoocdev/edx-platform,etzhou/edx-platform,jelugbo/tundex,iivic/BoiseStateX,msegado/edx-platform,angelapper/edx-platform,jolyonb/edx-platform,zofuthan/edx-platform,itsjeyd/edx-platform,rhndg/openedx,chudaol/edx-platform,mtlchun/edx,ESOedX/edx-platform,xuxiao19910803/edx-platform,jamiefolsom/edx-platform,CourseTalk/edx-platform,rue89-tech/edx-platform,ZLLab-Mooc/edx-platform,jazztpt/edx-platform,UXE/local-edx,Semi-global/edx-platform,unicri/edx-platform,raccoongang/edx-platform,polimediaupv/edx-platform,MSOpenTech/edx-platform,Kalyzee/edx-platform,jbassen/edx-platform,pomegranited/edx-platform,arifsetiawan/edx-platform,Softmotions/edx-platform,IndonesiaX/edx-platform,ovnicraft/edx-platform,SivilTaram/edx-platform,longmen21/edx-platform,jamiefolsom/edx-platform,hmcmooc/muddx-platform,ubc/edx-platform,valtech-mooc/edx-platform,JCBarahona/edX,halvertoluke/edx-platform,jswope00/griffinx,DefyVentures/edx-platform,kmoocdev/edx-platform,zerobatu/edx-platform,Stanford-Online/edx-platform,cecep-edu/edx-platform,utecuy/edx-platform,Edraak/edraak-platform,nanolearningllc/edx-platform-cypress-2,defance/edx-platform,pku9104038/edx-platform,jswope00/GAI,stvstnfrd/edx-platform,chand3040/cloud_that,OmarIthawi/edx-platform,openfun/edx-platform,playm2mboy/edx-platform,adoosii/edx-platform,ampax/edx-platform-backup,olexiim/edx-platform,don-github/edx-platform,DefyVentures/edx-platform,appliedx/edx-platform,edry/edx-platform,dsajkl/reqiop,fintech-circle/edx-platform,martynovp/edx-platform,angelapper/edx-platform,SivilTaram/edx-platform,leansoft/edx-platform,edx/edx-platform,hkawasaki/kawasaki-aio8-1,doganov/edx-platform,ak2703/edx-platform,pomegranited/edx-platform,philanthropy-u/edx-platform,pomegranited/edx-platform,hamzehd/edx-platform,jbassen/edx-platform,dsajkl/123,franosincic/edx-platform,tanmaykm/edx-platform,hmcmooc/muddx-platform,mcgachey/edx-platform,SravanthiSinha/edx-platform,gsehub/edx-platform,louyihua/edx-platform,eemirtekin/edx-platform,sudheerchintala/LearnEraPlatForm,ampax/edx-platform-backup,bdero/edx-platform,xinjiguaike/edx-platform,jolyonb/edx-platform,nttks/jenkins-test,J861449197/edx-platform,jjmiranda/edx-platform,Shrhawk/edx-platform,jonathan-beard/edx-platform,antonve/s4-project-mooc,hamzehd/edx-platform,antoviaque/edx-platform,RPI-OPENEDX/edx-platform,solashirai/edx-platform,chauhanhardik/populo_2,jbzdak/edx-platform,nttks/edx-platform,ESOedX/edx-platform,EDUlib/edx-platform,edx-solutions/edx-platform,jamesblunt/edx-platform,xingyepei/edx-platform,mcgachey/edx-platform,kmoocdev2/edx-platform,dcosentino/edx-platform,rue89-tech/edx-platform,xuxiao19910803/edx,ampax/edx-platform,4eek/edx-platform,ahmadiga/min_edx,deepsrijit1105/edx-platform,jolyonb/edx-platform,unicri/edx-platform,ubc/edx-platform,rismalrv/edx-platform,MakeHer/edx-platform,motion2015/edx-platform,CredoReference/edx-platform,solashirai/edx-platform,jbzdak/edx-platform,Livit/Livit.Learn.EdX,RPI-OPENEDX/edx-platform,eduNEXT/edx-platform,hkawasaki/kawasaki-aio8-1,kmoocdev/edx-platform,devs1991/test_edx_docmode,Softmotions/edx-platform,morenopc/edx-platform,beni55/edx-platform,J861449197/edx-platform,jolyonb/edx-platform,itsjeyd/edx-platform,morenopc/edx-platform,shubhdev/edxOnBaadal,jazkarta/edx-platform,dkarakats/edx-platform,simbs/edx-platform,Lektorium-LLC/edx-platform,zadgroup/edx-platform,TeachAtTUM/edx-platform,RPI-OPENEDX/edx-platform,sameetb-cuelogic/edx-platform-test,nagyistoce/edx-platform,kursitet/edx-platform,jswope00/GAI,unicri/edx-platform,nikolas/edx-platform,Softmotions/edx-platform,LICEF/edx-platform,cognitiveclass/edx-platform,atsolakid/edx-platform,MSOpenTech/edx-platform,ahmadio/edx-platform,bitifirefly/edx-platform,carsongee/edx-platform,beacloudgenius/edx-platform,ak2703/edx-platform,defance/edx-platform,pepeportela/edx-platform,amir-qayyum-khan/edx-platform,JCBarahona/edX,carsongee/edx-platform,rhndg/openedx,gymnasium/edx-platform,beacloudgenius/edx-platform,kxliugang/edx-platform,longmen21/edx-platform,4eek/edx-platform,bitifirefly/edx-platform,mbareta/edx-platform-ft,ferabra/edx-platform,doganov/edx-platform,jonathan-beard/edx-platform,abdoosh00/edraak,vikas1885/test1,cecep-edu/edx-platform,franosincic/edx-platform,beni55/edx-platform,cpennington/edx-platform,Semi-global/edx-platform,B-MOOC/edx-platform,angelapper/edx-platform,ak2703/edx-platform,MakeHer/edx-platform,utecuy/edx-platform,zadgroup/edx-platform,jbzdak/edx-platform,olexiim/edx-platform,adoosii/edx-platform,cselis86/edx-platform,deepsrijit1105/edx-platform,bdero/edx-platform,angelapper/edx-platform,knehez/edx-platform,xingyepei/edx-platform,mbareta/edx-platform-ft,shubhdev/edx-platform,fly19890211/edx-platform,shashank971/edx-platform,xuxiao19910803/edx,edx/edx-platform,caesar2164/edx-platform,simbs/edx-platform,mahendra-r/edx-platform,Edraak/circleci-edx-platform,lduarte1991/edx-platform,jswope00/GAI,B-MOOC/edx-platform,chand3040/cloud_that,valtech-mooc/edx-platform,amir-qayyum-khan/edx-platform,B-MOOC/edx-platform,martynovp/edx-platform,vasyarv/edx-platform,zerobatu/edx-platform,jzoldak/edx-platform,mitocw/edx-platform,alexthered/kienhoc-platform,lduarte1991/edx-platform,motion2015/a3,alexthered/kienhoc-platform,BehavioralInsightsTeam/edx-platform,edx-solutions/edx-platform,shurihell/testasia,wwj718/ANALYSE,mtlchun/edx,philanthropy-u/edx-platform,olexiim/edx-platform,tiagochiavericosta/edx-platform,jelugbo/tundex,IONISx/edx-platform,mtlchun/edx,doismellburning/edx-platform,xinjiguaike/edx-platform,eemirtekin/edx-platform,vasyarv/edx-platform,MSOpenTech/edx-platform,Livit/Livit.Learn.EdX,knehez/edx-platform,bdero/edx-platform,raccoongang/edx-platform,mcgachey/edx-platform,shashank971/edx-platform,jzoldak/edx-platform,EDUlib/edx-platform,dkarakats/edx-platform,ZLLab-Mooc/edx-platform,itsjeyd/edx-platform,shabab12/edx-platform,J861449197/edx-platform,antonve/s4-project-mooc,jamesblunt/edx-platform,hmcmooc/muddx-platform,gymnasium/edx-platform,zubair-arbi/edx-platform,doismellburning/edx-platform,xuxiao19910803/edx-platform,appsembler/edx-platform,kamalx/edx-platform,zubair-arbi/edx-platform,LearnEra/LearnEraPlaftform,mcgachey/edx-platform,edry/edx-platform,shubhdev/openedx,JioEducation/edx-platform,solashirai/edx-platform,nanolearningllc/edx-platform-cypress,jruiperezv/ANALYSE,halvertoluke/edx-platform,analyseuc3m/ANALYSE-v1,arifsetiawan/edx-platform,appsembler/edx-platform,lduarte1991/edx-platform,Stanford-Online/edx-platform,ovnicraft/edx-platform,vismartltd/edx-platform,nagyistoce/edx-platform,LICEF/edx-platform,Lektorium-LLC/edx-platform,chauhanhardik/populo,chand3040/cloud_that,chrisndodge/edx-platform,cyanna/edx-platform,benpatterson/edx-platform,franosincic/edx-platform,Ayub-Khan/edx-platform,cselis86/edx-platform,mtlchun/edx,Lektorium-LLC/edx-platform,CredoReference/edx-platform,dcosentino/edx-platform,cognitiveclass/edx-platform,bigdatauniversity/edx-platform,JCBarahona/edX,jazztpt/edx-platform,antonve/s4-project-mooc,Edraak/edx-platform,shashank971/edx-platform,nanolearning/edx-platform,nanolearning/edx-platform,rue89-tech/edx-platform,miptliot/edx-platform,jonathan-beard/edx-platform,beni55/edx-platform,edx/edx-platform,devs1991/test_edx_docmode,nttks/edx-platform,dsajkl/reqiop,proversity-org/edx-platform,devs1991/test_edx_docmode,yokose-ks/edx-platform,antonve/s4-project-mooc,arbrandes/edx-platform,mahendra-r/edx-platform,y12uc231/edx-platform,zofuthan/edx-platform,sudheerchintala/LearnEraPlatForm,Ayub-Khan/edx-platform,ferabra/edx-platform,halvertoluke/edx-platform,beacloudgenius/edx-platform,inares/edx-platform,olexiim/edx-platform,beacloudgenius/edx-platform,hkawasaki/kawasaki-aio8-1,B-MOOC/edx-platform,vasyarv/edx-platform,wwj718/ANALYSE,arbrandes/edx-platform,4eek/edx-platform,WatanabeYasumasa/edx-platform,waheedahmed/edx-platform,ahmadio/edx-platform,a-parhom/edx-platform,valtech-mooc/edx-platform,eemirtekin/edx-platform,jruiperezv/ANALYSE,eduNEXT/edunext-platform,eduNEXT/edx-platform,bitifirefly/edx-platform,don-github/edx-platform,nttks/edx-platform,a-parhom/edx-platform,mjirayu/sit_academy,rismalrv/edx-platform,etzhou/edx-platform,inares/edx-platform,teltek/edx-platform,chauhanhardik/populo,kxliugang/edx-platform,IndonesiaX/edx-platform,jruiperezv/ANALYSE,shubhdev/edx-platform,Lektorium-LLC/edx-platform,ubc/edx-platform,ZLLab-Mooc/edx-platform,tanmaykm/edx-platform,jruiperezv/ANALYSE,devs1991/test_edx_docmode,jbzdak/edx-platform,rue89-tech/edx-platform,edx-solutions/edx-platform,doganov/edx-platform,edry/edx-platform,jamiefolsom/edx-platform,pabloborrego93/edx-platform,chrisndodge/edx-platform,SravanthiSinha/edx-platform,antonve/s4-project-mooc,proversity-org/edx-platform,jelugbo/tundex,auferack08/edx-platform,synergeticsedx/deployment-wipro,arifsetiawan/edx-platform,cselis86/edx-platform,marcore/edx-platform,jamesblunt/edx-platform,SravanthiSinha/edx-platform,hkawasaki/kawasaki-aio8-0,shurihell/testasia,UXE/local-edx,LearnEra/LearnEraPlaftform,LearnEra/LearnEraPlaftform,naresh21/synergetics-edx-platform,xinjiguaike/edx-platform,jazkarta/edx-platform,vismartltd/edx-platform,msegado/edx-platform,nikolas/edx-platform,jazkarta/edx-platform-for-isc,torchingloom/edx-platform,olexiim/edx-platform,wwj718/edx-platform,jazkarta/edx-platform,peterm-itr/edx-platform,louyihua/edx-platform,xinjiguaike/edx-platform,fly19890211/edx-platform,pepeportela/edx-platform,MakeHer/edx-platform,Edraak/edx-platform,yokose-ks/edx-platform,etzhou/edx-platform,BehavioralInsightsTeam/edx-platform,Endika/edx-platform,utecuy/edx-platform,waheedahmed/edx-platform,don-github/edx-platform,auferack08/edx-platform,hamzehd/edx-platform,utecuy/edx-platform,jbassen/edx-platform,chauhanhardik/populo,kamalx/edx-platform,atsolakid/edx-platform,bitifirefly/edx-platform,kursitet/edx-platform,chrisndodge/edx-platform,Shrhawk/edx-platform,UXE/local-edx,Unow/edx-platform,Endika/edx-platform,valtech-mooc/edx-platform,bigdatauniversity/edx-platform,eemirtekin/edx-platform,jamiefolsom/edx-platform,MakeHer/edx-platform,Ayub-Khan/edx-platform,jjmiranda/edx-platform,kxliugang/edx-platform,SravanthiSinha/edx-platform,10clouds/edx-platform,y12uc231/edx-platform,ZLLab-Mooc/edx-platform,ahmadiga/min_edx,Kalyzee/edx-platform,sameetb-cuelogic/edx-platform-test,ampax/edx-platform-backup,miptliot/edx-platform,jzoldak/edx-platform,cpennington/edx-platform,hastexo/edx-platform,ahmedaljazzar/edx-platform,eduNEXT/edunext-platform,don-github/edx-platform,arbrandes/edx-platform,10clouds/edx-platform,DefyVentures/edx-platform,yokose-ks/edx-platform,unicri/edx-platform,chudaol/edx-platform,chand3040/cloud_that,10clouds/edx-platform,eestay/edx-platform,jswope00/GAI,etzhou/edx-platform,zubair-arbi/edx-platform,analyseuc3m/ANALYSE-v1,morenopc/edx-platform,JCBarahona/edX,carsongee/edx-platform,kmoocdev/edx-platform,simbs/edx-platform,utecuy/edx-platform,deepsrijit1105/edx-platform,shabab12/edx-platform,yokose-ks/edx-platform,jswope00/griffinx,lduarte1991/edx-platform,romain-li/edx-platform,wwj718/edx-platform,zadgroup/edx-platform,fly19890211/edx-platform,Edraak/edx-platform,Edraak/edx-platform,WatanabeYasumasa/edx-platform,sameetb-cuelogic/edx-platform-test,jazkarta/edx-platform-for-isc,arbrandes/edx-platform,prarthitm/edxplatform,mushtaqak/edx-platform,CourseTalk/edx-platform,bdero/edx-platform,kmoocdev2/edx-platform,IONISx/edx-platform,cpennington/edx-platform,cyanna/edx-platform,4eek/edx-platform,polimediaupv/edx-platform,adoosii/edx-platform,nanolearningllc/edx-platform-cypress,amir-qayyum-khan/edx-platform,devs1991/test_edx_docmode,UOMx/edx-platform,torchingloom/edx-platform,bigdatauniversity/edx-platform,andyzsf/edx,stvstnfrd/edx-platform,antoviaque/edx-platform,edx-solutions/edx-platform,andyzsf/edx,Shrhawk/edx-platform,dkarakats/edx-platform,ferabra/edx-platform,motion2015/a3,iivic/BoiseStateX,eemirtekin/edx-platform,teltek/edx-platform,WatanabeYasumasa/edx-platform,Endika/edx-platform,franosincic/edx-platform,romain-li/edx-platform,chauhanhardik/populo_2,mjirayu/sit_academy,ak2703/edx-platform,kmoocdev2/edx-platform,gsehub/edx-platform,halvertoluke/edx-platform,LICEF/edx-platform,fintech-circle/edx-platform,SivilTaram/edx-platform,Unow/edx-platform,waheedahmed/edx-platform,kxliugang/edx-platform,jjmiranda/edx-platform,benpatterson/edx-platform,Endika/edx-platform,nttks/edx-platform,teltek/edx-platform,xuxiao19910803/edx,peterm-itr/edx-platform,nttks/edx-platform,jazkarta/edx-platform,caesar2164/edx-platform,torchingloom/edx-platform,CredoReference/edx-platform,dsajkl/123,edry/edx-platform,Edraak/circleci-edx-platform,shubhdev/edxOnBaadal,iivic/BoiseStateX,chauhanhardik/populo_2,raccoongang/edx-platform,y12uc231/edx-platform,nttks/jenkins-test,pabloborrego93/edx-platform,playm2mboy/edx-platform,AkA84/edx-platform,nanolearning/edx-platform,xingyepei/edx-platform,martynovp/edx-platform,sudheerchintala/LearnEraPlatForm,mitocw/edx-platform,ferabra/edx-platform,Softmotions/edx-platform,zerobatu/edx-platform,DefyVentures/edx-platform,iivic/BoiseStateX,CredoReference/edx-platform,eduNEXT/edx-platform,doismellburning/edx-platform,shubhdev/openedx,DNFcode/edx-platform,waheedahmed/edx-platform,shurihell/testasia,y12uc231/edx-platform,dsajkl/123,gymnasium/edx-platform,eestay/edx-platform,dsajkl/reqiop,raccoongang/edx-platform,alexthered/kienhoc-platform,chauhanhardik/populo,Unow/edx-platform,kursitet/edx-platform,kmoocdev/edx-platform,ahmedaljazzar/edx-platform,philanthropy-u/edx-platform,hmcmooc/muddx-platform,dcosentino/edx-platform,auferack08/edx-platform,nikolas/edx-platform,adoosii/edx-platform,ubc/edx-platform,auferack08/edx-platform,MSOpenTech/edx-platform,mushtaqak/edx-platform,eduNEXT/edx-platform,MSOpenTech/edx-platform,Edraak/edraak-platform,zubair-arbi/edx-platform,motion2015/edx-platform,vismartltd/edx-platform,carsongee/edx-platform,mjirayu/sit_academy,TeachAtTUM/edx-platform,JCBarahona/edX,rue89-tech/edx-platform,ESOedX/edx-platform,shubhdev/edx-platform,Unow/edx-platform,nanolearningllc/edx-platform-cypress-2,cpennington/edx-platform,pku9104038/edx-platform,eduNEXT/edunext-platform,shubhdev/edx-platform,philanthropy-u/edx-platform,hastexo/edx-platform,motion2015/edx-platform,jbassen/edx-platform,longmen21/edx-platform,Edraak/edraak-platform,rismalrv/edx-platform,MakeHer/edx-platform,xingyepei/edx-platform,jamesblunt/edx-platform,RPI-OPENEDX/edx-platform,zhenzhai/edx-platform,zubair-arbi/edx-platform,pepeportela/edx-platform,nagyistoce/edx-platform,benpatterson/edx-platform,vismartltd/edx-platform,Semi-global/edx-platform,jazkarta/edx-platform-for-isc,DNFcode/edx-platform,procangroup/edx-platform,ahmadio/edx-platform,naresh21/synergetics-edx-platform,IONISx/edx-platform,torchingloom/edx-platform,leansoft/edx-platform,shashank971/edx-platform,msegado/edx-platform,longmen21/edx-platform,zofuthan/edx-platform,appsembler/edx-platform,AkA84/edx-platform,IndonesiaX/edx-platform,dkarakats/edx-platform,IndonesiaX/edx-platform,DNFcode/edx-platform,eestay/edx-platform,nanolearningllc/edx-platform-cypress,pabloborrego93/edx-platform,motion2015/a3,tiagochiavericosta/edx-platform,Semi-global/edx-platform,louyihua/edx-platform,knehez/edx-platform,wwj718/edx-platform,JioEducation/edx-platform,pomegranited/edx-platform,cselis86/edx-platform,nttks/jenkins-test,mtlchun/edx,jazkarta/edx-platform-for-isc,jbzdak/edx-platform,Livit/Livit.Learn.EdX,bigdatauniversity/edx-platform,pepeportela/edx-platform,wwj718/ANALYSE,DNFcode/edx-platform,rhndg/openedx,hastexo/edx-platform | ---
+++
@@ -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")
- 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 have English documentation
locale = "en_us" |
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:
raise Http404('Victim not found')
strategy = Strategy(victim)
# Example work structure:
# return {'url': 'https://www.dimkarakostas.com/?breach-test',
# 'amount': 10,
# 'timeout': 0}
new_work = strategy.get_work()
return HttpResponse(json.dumps(new_work), content_type='application/json')
@csrf_exempt
def work_completed(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
raise Http404('Victim not found')
strategy = Strategy(victim)
victory = strategy.work_completed()
return JsonResponse({
'victory': victory
})
| 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:
raise Http404('Victim not found')
strategy = Strategy(victim)
# Example work structure:
# return {'url': 'https://www.dimkarakostas.com/?breach-test',
# 'amount': 10,
# 'timeout': 0}
new_work = strategy.get_work()
return JsonResponse(new_work)
@csrf_exempt
def work_completed(request, victim_id=0):
assert(victim_id)
try:
victim = Victim.objects.get(pk=victim_id)
except:
raise Http404('Victim not found')
strategy = Strategy(victim)
victory = strategy.work_completed()
return JsonResponse({
'victory': victory
})
| 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,dimriou/rupture,esarafianou/rupture | ---
+++
@@ -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 FileModuleTestCase(TestCase):
def test_sed_limit_escaped(self):
with tempfile.NamedTemporaryFile() as tfile:
tfile.write(SED_CONTENT)
tfile.seek(0, 0)
path = tfile.name
before = '/var/lib/foo'
after = ''
limit = '^{0}'.format(before)
filemod.sed(path, before, after, limit=limit)
with open(path, 'rb') as newfile:
self.assertEquals(SED_CONTENT.replace(before, ''), newfile.read())
if __name__ == "__main__":
loader = TestLoader()
tests = loader.loadTestsFromTestCase(FileModuleTestCase)
TextTestRunner(verbosity=1).run(tests)
| 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/foo/app/test
here
"""
class FileModuleTestCase(TestCase):
def test_sed_limit_escaped(self):
with tempfile.NamedTemporaryFile() as tfile:
tfile.write(SED_CONTENT)
tfile.seek(0, 0)
path = tfile.name
before = '/var/lib/foo'
after = ''
limit = '^{0}'.format(before)
filemod.sed(path, before, after, limit=limit)
with open(path, 'rb') as newfile:
self.assertEquals(
SED_CONTENT.replace(before, ''),
newfile.read()
)
if __name__ == "__main__":
loader = TestLoader()
tests = loader.loadTestsFromTestCase(FileModuleTestCase)
TextTestRunner(verbosity=1).run(tests)
| 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.replace(before, ''), newfile.read())
+ self.assertEquals(
+ SED_CONTENT.replace(before, ''),
+ newfile.read()
+ )
if __name__ == "__main__": |
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.IntType );
t.drop();
t.save( { "a" : 1 , "b" : 1.0 } );
assert( t.findOne() );
assert( t.findOne( { "a" : 1 } ) );
assert( t.findOne( { "b" : 1.0 } ) );
assert( not t.findOne( { "b" : 2.0 } ) );
assert( t.findOne( { "a" : 1.0 } ) );
assert( t.findOne( { "b" : 1 } ) );
|
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( thing["a"] ) == types.IntType );
t.drop();
t.save( { "a" : 1 , "b" : 1.0 } );
assert( t.findOne() );
assert( t.findOne( { "a" : 1 } ) );
assert( t.findOne( { "b" : 1.0 } ) );
assert( not t.findOne( { "b" : 2.0 } ) );
assert( t.findOne( { "a" : 1.0 } ) );
assert( t.findOne( { "b" : 1 } ) );
| 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):
""Reporter that only shows dots when running tests."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.verbosity = 0
self.showlongtestinfo = False
self.showfspath = False
terminal.TerminalReporter = QuietReporter
| """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):
"""Reporter that only shows dots when running tests."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.verbosity = 0
self.showlongtestinfo = False
self.showfspath = False
terminal.TerminalReporter = QuietReporter
| 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, **kwargs) |
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: ClassVar[str]
elif_var: ClassVar[str]
else_var: ClassVar[str]
try_var: ClassVar[str]
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_var: ClassVar[str]
For_var: ClassVar[str]
While_var: ClassVar[str]
Def_var: ClassVar[str]
If_var: ClassVar[str]
Elif_var: ClassVar[str]
Else_var: ClassVar[str]
Try_var: ClassVar[str]
Except_var: ClassVar[str]
Finally_var: ClassVar[str]
With_var: ClassVar[str]
def m(self):
xs: List[int] = []
| #!/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]
if_var: ClassVar[str]
elif_var: ClassVar[str]
else_var: ClassVar[str]
try_var: ClassVar[str]
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_var: ClassVar[str]
forVar: ClassVar[str]
whileVar: ClassVar[str]
defVar: ClassVar[str]
ifVar: ClassVar[str]
elifVar: ClassVar[str]
elseVar: ClassVar[str]
tryVar: ClassVar[str]
exceptVar: ClassVar[str]
finallyVar: ClassVar[str]
withVar: ClassVar[str]
def m(self):
xs: List[int] = []
| 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]
- Def_var: ClassVar[str]
- If_var: ClassVar[str]
- Elif_var: ClassVar[str]
- Else_var: ClassVar[str]
- Try_var: ClassVar[str]
- Except_var: ClassVar[str]
- Finally_var: ClassVar[str]
- With_var: ClassVar[str]
-
+ forVar: ClassVar[str]
+ whileVar: ClassVar[str]
+ defVar: ClassVar[str]
+ ifVar: ClassVar[str]
+ elifVar: ClassVar[str]
+ elseVar: ClassVar[str]
+ tryVar: ClassVar[str]
+ exceptVar: ClassVar[str]
+ finallyVar: ClassVar[str]
+ withVar: ClassVar[str]
+
def m(self):
xs: List[int] = [] |
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 test files.
config.suffixes = ['.py']
# test_source_root: The root path where tests are located.
config.test_source_root = os.path.dirname(__file__)
#config.use_default_substitutions()
config.excludes = [
'lit.cfg.py',
'lit.site.cfg.py',
'test_util.py',
'manual_test.py',
]
config.substitutions.extend([
('%PYTHON', sys.executable),
])
config.environment['PYTHONPATH'] = ":".join(sys.path)
project_root = os.path.dirname(os.path.dirname(__file__))
# Enable features based on -D FEATURES=hugetest,vulkan
# syntax.
features_param = lit_config.params.get('FEATURES')
if features_param:
config.available_features.update(features_param.split(','))
| 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 test files.
config.suffixes = ['.py']
# test_source_root: The root path where tests are located.
config.test_source_root = os.path.dirname(__file__)
#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',
]
config.substitutions.extend([
('%PYTHON', sys.executable),
])
config.environment['PYTHONPATH'] = ":".join(sys.path)
project_root = os.path.dirname(os.path.dirname(__file__))
# Enable features based on -D FEATURES=hugetest,vulkan
# syntax.
features_param = lit_config.params.get('FEATURES')
if features_param:
config.available_features.update(features_param.split(','))
| 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 = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 3),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/0.6', 2, '-stable', 1),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
| # 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 = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 3),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/0.7', 2, '-stable', 1),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
| 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
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.urlopen(
request.Request(url, headers=HEADERS)).read(), "html.parser")
def host(self):
""" get the host of the url, so we can use the correct scraper (check __init__.py) """
raise NotImplementedError("This should be implemented.")
def publisher_site(self):
""" the original url of the publisher site """
raise NotImplementedError("This should be implemented.")
def title(self):
""" title of the recipe itself """
raise NotImplementedError("This should be implemented.")
def total_time(self):
""" total time it takes to preparate the recipe in minutes """
raise NotImplementedError("This should be implemented.")
def ingredients(self):
""" list of ingredients needed for the recipe """
raise NotImplementedError("This should be implemented.")
def instructions(self):
""" directions provided on the recipe link """
raise NotImplementedError("This should be implemented.")
def social_rating(self):
""" social rating of the recipe in 0 - 100 scale """
raise NotImplementedError("This should be implemented.")
| 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
with url:
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.urlopen(
request.Request(url, headers=HEADERS)).read(), "html.parser")
def host(self):
""" get the host of the url, so we can use the correct scraper (check __init__.py) """
raise NotImplementedError("This should be implemented.")
def publisher_site(self):
""" the original url of the publisher site """
raise NotImplementedError("This should be implemented.")
def title(self):
""" title of the recipe itself """
raise NotImplementedError("This should be implemented.")
def total_time(self):
""" total time it takes to preparate the recipe in minutes """
raise NotImplementedError("This should be implemented.")
def ingredients(self):
""" list of ingredients needed for the recipe """
raise NotImplementedError("This should be implemented.")
def instructions(self):
""" directions provided on the recipe link """
raise NotImplementedError("This should be implemented.")
def social_rating(self):
""" social rating of the recipe in 0 - 100 scale """
raise NotImplementedError("This should be implemented.")
| 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:
self.soup = BeautifulSoup(request.urlopen(
request.Request(url, headers=HEADERS)).read(), "html.parser") |
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 as base
from sfc.tests.functest import run_tests
class OpenDaylightSFC(base.FeatureBase):
def __init__(self):
super(OpenDaylightSFC, self).__init__(project='sfc',
case='functest-odl-sfc',
repo='dir_repo_sfc')
def execute(self):
return run_tests.main()
| #!/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 as base
class OpenDaylightSFC(base.FeatureBase):
def __init__(self):
super(OpenDaylightSFC, self).__init__(project='sfc',
case='functest-odl-sfc',
repo='dir_repo_sfc')
dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo)
self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest
| 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)
because it run using the bash command.
But when importing it as a module and call main()
from python, it will run in the patched runtime
and it will error out.
https://hastebin.com/iyobuxutib.py
Change-Id: I54237c32c957718b363d302efe84e01bc78e4f47
Signed-off-by: George Paraskevopoulos <97fa9f4b61869a8ee92863df90135c882f7b3aa0@intracom-telecom.com>
| 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',
case='functest-odl-sfc',
repo='dir_repo_sfc')
-
- def execute(self):
- return run_tests.main()
+ dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo)
+ self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest |
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_objectpermissions
| # 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_objectpermissions
import south.introspection_plugins.annoying_autoonetoone
| 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 following a Collection
"""
user = models.ForeignKey(TalksUser)
collection = models.ForeignKey(Collection)
is_owner = models.BooleanField()
is_main = models.BooleanField() # main collection of the user
class Meta:
unique_together = ('user', 'collection')
class Collection(models.Model):
slug = models.SlugField()
title = models.CharField(max_length=250)
# TODO list private or public/shared?
# TODO qualify list? (e.g. "Talks I want to attend"?)
class CollectionItem(models.Model):
collection = models.ForeignKey(Collection)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
item = GenericForeignKey('content_type', 'object_id') # atm: Talk, Event, Series
class DepartmentFollow(models.Model):
pass
class LocationFollow(models.Model):
pass
| 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(models.signals.post_save, sender=User)
def ensure_profile_exists(sender, instance, created, **kwargs):
"""If the User has just been created we use a signal to also create a TalksUser
"""
if created:
TalksUser.objects.get_or_create(user=instance)
class Collection(models.Model):
slug = models.SlugField()
title = models.CharField(max_length=250)
# TODO list private or public/shared?
# TODO qualify list? (e.g. "Talks I want to attend"?)
class CollectionFollow(models.Model):
"""User following a Collection
"""
user = models.ForeignKey(TalksUser)
collection = models.ForeignKey(Collection)
is_owner = models.BooleanField(default=False)
# Main/default collection of the user
is_main = models.BooleanField(default=False)
class Meta:
unique_together = ('user', 'collection')
class CollectionItem(models.Model):
collection = models.ForeignKey(Collection)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
# Currently item can be an Event or EventGroup
item = GenericForeignKey('content_type', 'object_id')
class DepartmentFollow(models.Model):
pass
class LocationFollow(models.Model):
pass
| 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(User)
-class CollectionFollow(models.Model):
- """User following a Collection
+@receiver(models.signals.post_save, sender=User)
+def ensure_profile_exists(sender, instance, created, **kwargs):
+ """If the User has just been created we use a signal to also create a TalksUser
"""
-
- user = models.ForeignKey(TalksUser)
- collection = models.ForeignKey(Collection)
- is_owner = models.BooleanField()
- is_main = models.BooleanField() # main collection of the user
-
- class Meta:
- unique_together = ('user', 'collection')
+ if created:
+ TalksUser.objects.get_or_create(user=instance)
class Collection(models.Model):
@@ -31,12 +27,27 @@
# TODO qualify list? (e.g. "Talks I want to attend"?)
+class CollectionFollow(models.Model):
+ """User following a Collection
+ """
+
+ user = models.ForeignKey(TalksUser)
+ collection = models.ForeignKey(Collection)
+ is_owner = models.BooleanField(default=False)
+ # Main/default collection of the user
+ is_main = models.BooleanField(default=False)
+
+ class Meta:
+ unique_together = ('user', 'collection')
+
+
class CollectionItem(models.Model):
collection = models.ForeignKey(Collection)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
- item = GenericForeignKey('content_type', 'object_id') # atm: Talk, Event, Series
+ # Currently item can be an Event or EventGroup
+ item = GenericForeignKey('content_type', 'object_id')
class DepartmentFollow(models.Model): |
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_related('image_fk')
def get_months(self, namespace):
"""
Get months with posts count for given namespace string.
This means how much posts there are in each month. Results are ordered
by date.
"""
# done in a naive way as Django is having tough time while aggregating
# on date fields
entries = self.filter(namespace__namespace=namespace)
dates = entries.values_list('publishing_date', flat=True)
dates = [(x.year, x.month) for x in dates]
date_counter = Counter(dates)
dates = set(dates)
dates = sorted(dates, reverse=True)
months = [
# Use day=3 to make sure timezone won't affect this hacks'
# month value. There are UTC+14 and UTC-12 timezones.
{'date': datetime.date(year=year, month=month, day=3),
'count': date_counter[year, month]}
for year, month in dates]
return months
| 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 = super(RelatedManager, self).get_query_set()
# return qs.select_related('image_fk')
def get_months(self, namespace):
"""
Get months with posts count for given namespace string.
This means how much posts there are in each month. Results are ordered
by date.
"""
# done in a naive way as Django is having tough time while aggregating
# on date fields
entries = self.filter(namespace__namespace=namespace)
dates = entries.values_list('publishing_date', flat=True)
dates = [(x.year, x.month) for x in dates]
date_counter = Counter(dates)
dates = set(dates)
dates = sorted(dates, reverse=True)
months = [
# Use day=3 to make sure timezone won't affect this hacks'
# month value. There are UTC+14 and UTC-12 timezones.
{'date': datetime.date(year=year, month=month, day=3),
'count': date_counter[year, month]}
for year, month in dates]
return months
| 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',
'gravatar',
'password',
'password_repeat',
settings.DRF_URL_FIELD_NAME,
)
extra_kwargs = {
settings.DRF_URL_FIELD_NAME: {
"view_name": "users:user-detail",
},
}
password = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
password_repeat = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
def create(self, validated_data):
if validated_data['password'] != validated_data['password']:
raise ValidationError(
detail={
"password_repeat": "Tow password doesn't match",
}
)
validated_data.pop('password_repeat')
password = validated_data.pop('password')
user = super(UserSerializer, self).create(
validated_data,
)
user.set_password(password)
user.save()
return user
| 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 = User
fields = (
'username',
'email',
'gravatar',
'password',
'password_repeat',
settings.DRF_URL_FIELD_NAME,
)
extra_kwargs = {
settings.DRF_URL_FIELD_NAME: {
"view_name": "users:user-detail",
},
}
password = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
password_repeat = serializers.CharField(
write_only=True,
required=True,
allow_blank=False,
min_length=6,
max_length=32,
)
def create(self, validated_data):
if validated_data['password'] != validated_data['password']:
raise ValidationError(
detail={
"password_repeat": "Tow password doesn't match",
}
)
validated_data.pop('password_repeat')
password = validated_data.pop('password')
user = super(UserSerializer, self).create(
validated_data,
)
user.set_password(password)
user.save()
login(
self.context['request'],
user=user,
backend=settings.AUTHENTICATION_BACKENDS[0],
)
return user
| 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()
+ login(
+ self.context['request'],
+ user=user,
+ backend=settings.AUTHENTICATION_BACKENDS[0],
+ )
return user |
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(test_image, INPUT_WIDTH, INPUT_HEIGHT)
# Check normalization
assertEq(len(np.where(np.abs(image) > 1)[0]), 0)
# Check resize
assertEq(image.size, 3 * INPUT_WIDTH * INPUT_HEIGHT)
# Check normalization on one element
assertEq(image[0, 0, 0], ((234 / 255.) - 0.5) * 2)
def testPredict():
model = loadNetwork(WEIGHTS_PTH, NUM_OUTPUT, MODEL_TYPE)
x, y = predict(model, test_image)
| 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(test_image, INPUT_WIDTH, INPUT_HEIGHT)
# Check normalization
assertEq(len(np.where(np.abs(image) > 1)[0]), 0)
# Check resize
assertEq(image.size, 3 * INPUT_WIDTH * INPUT_HEIGHT)
# Check normalization on one element
assertEq(image[0, 0, 0], ((234 / 255.) - 0.5) * 2)
def testPredict():
model = loadNetwork(WEIGHTS_PTH, NUM_OUTPUT, MODEL_TYPE)
x, y = predict(model, test_image)
| 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_image, INPUT_WIDTH, INPUT_HEIGHT) |
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/dataset?page=1']
rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
'parse_dataset')]
def parse_dataset(self, response):
sel = Selector(response)
dataset = items.DatasetItem()
dataset['url'] = response.url
dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()
return dataset
| 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 range(1, pages + 1):
start_urls.append('http://data.gc.ca/data/en/dataset?page=' + str(i))
rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
'parse_dataset')]
def parse_dataset(self, response):
sel = Selector(response)
dataset = items.DatasetItem()
dataset['url'] = response.url
dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()
return dataset
| 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/dataset?page=' + str(i))
+
rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
'parse_dataset')]
|
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/checkVatService.wsdl') # NoQA
VATIN_MAX_LENGTH = 14 |
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[int], Optional[str]] # TODO: Should be int in SyftUser
daa_pdf: Optional[bytes] = b""
class Config:
orm_mode = True
class UserCreate(BaseUser):
email: EmailStr
role: str = "Data Scientist"
name: str
password: str
class UserUpdate(BaseUser):
password: Optional[str]
budget: Optional[float]
class UserCandidate(BaseUser):
email: EmailStr
status: str = "pending"
name: str
class User(BaseUser):
id: int
role: Union[int, str] # TODO: This should be int. Perhaps add role_name instead?
budget_spent: Optional[float]
institution: Optional[str]
website: Optional[str]
added_by: Optional[str]
class UserPrivate(User):
private_key: str
def get_signing_key(self) -> SigningKey:
return SigningKey(self.private_key.encode(), encoder=HexEncoder)
class UserSyft(User):
hashed_password: str
salt: str
verify_key: str
| # 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[int], Optional[str]] # TODO: Should be int in SyftUser
daa_pdf: Optional[bytes] = b""
class Config:
orm_mode = True
class UserCreate(BaseUser):
email: EmailStr
role: str = "Data Scientist"
name: str
password: str
institution: Optional[str]
website: Optional[str]
class ApplicantStatus(BaseModel):
status: str
class UserUpdate(BaseUser):
password: Optional[str]
budget: Optional[float]
class UserCandidate(BaseUser):
email: EmailStr
status: str = "pending"
name: str
class User(BaseUser):
id: int
role: Union[int, str] # TODO: This should be int. Perhaps add role_name instead?
budget_spent: Optional[float]
institution: Optional[str]
website: Optional[str]
added_by: Optional[str]
class UserPrivate(User):
private_key: str
def get_signing_key(self) -> SigningKey:
return SigningKey(self.private_key.encode(), encoder=HexEncoder)
class UserSyft(User):
hashed_password: str
salt: str
verify_key: str
| 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]
+
class UserPrivate(User):
private_key: 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 lines:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
if all_changes:
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class VcsGutterNextChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), all_changes[0])
class VcsGutterPrevChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), all_changes[-1])
| 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:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
if all_changes:
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class VcsGutterNextChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), all_changes[0])
class VcsGutterPrevChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), all_changes[-1])
| 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 NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| # -*- 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 NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| 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 channel or DM a specific user."""
url = self.settings.get('slackURL')
user = self.settings.get('slackUser')
payload = {}
payload['text'] = reportText
payload['new-bot-name'] = user
dm = self.settings.get('slackRecipient')
if dm:
payload['channel'] = '@' + dm
response = utils.apiCall(url, 'Slack', 'post', data = json.dumps(payload))
| 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 channel or DM a specific user."""
url = self.settings.get('slackURL')
user = self.settings.get('slackUser')
payload = {}
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 = utils.apiCall(url, 'Slack', 'post', data = json.dumps(payload))
| 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 = utils.apiCall(url, 'Slack', 'post', data = json.dumps(payload))
|
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 analyse')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
| #!/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 analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
| 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_true')
args=parser.parse_args()
filepath = args.filepath
@@ -19,6 +20,8 @@
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
+ if args.usernames:
+ print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
|
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)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
zlib_root = os.environ.get("ZLIB_ROOT")
if zlib_root:
f = pjoin(zlib_root, 'bin_release', 'zlib.dll')
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
| 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)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
zlib_root = os.environ.get("ZLIB_ROOT")
if zlib_root:
f = pjoin(zlib_root, 'bin_release', 'zlib.dll')
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
print("In installed h5py:", sorted(os.listdir(pjoin(sitepackagesdir, 'h5py'))))
if __name__ == '__main__':
main()
| 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__':
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 add permissions
"""
portal = aq_parent(aq_inner(tool))
# batch permission defaults
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)
portal.reindexObject()
return True
| 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 add permissions
"""
portal = aq_parent(aq_inner(tool))
# batch permission defaults
mp = portal.manage_permission
mp(AddAnalysisSpec, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
mp(AddSamplingDeviation, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
mp(AddSampleMatrix, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
portal.reindexObject()
return True
| 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(AddSampleMatrix, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)
portal.reindexObject()
return True |
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(name='Cat 2')
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')
def test_post(self):
data = {
'file_format': '0',
}
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertTrue(response['Content-Type'], 'text/csv')
| 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(name='Cat 2')
def test_get(self):
response = self.client.get(self.url)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8')
def test_post(self):
data = {
'file_format': '0',
}
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertEquals(response['Content-Type'], 'text/csv')
| 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/django-import-export,jnns/django-import-export,bmihelac/django-import-export | ---
+++
@@ -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')
def test_post(self):
data = {
@@ -23,4 +23,4 @@
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
- self.assertTrue(response['Content-Type'], 'text/csv')
+ self.assertEquals(response['Content-Type'], 'text/csv') |
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 {
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
def lambda_handler(event: dict, context: dict) -> Optional[dict]:
"""Lambda Handler
Entry point for every lambda function call
"""
if not settings.MSW_API:
logger.error("Couldn't read SF_MSW_API env variable")
return None
spot = event.get("slots", {}).get("SurfSpot", None)
spot = to_msw_id(spot) if spot is not None else None
if not spot:
logger.error("Couldn't parse spot id")
return close('Fulfilled',
{'contentType': 'PlainText',
'content': 'Surf spot not found :('})
logger.debug('event=%s context=%s', event, context)
res = json.loads(urllib.request.urlopen(
"http://magicseaweed.com/api/{}/forecast/?spot_id={}".format(
settings.MSW_API, spot)).read())
logger.debug('json.response=%s', res)
return close('Fulfilled',
{'contentType': 'PlainText',
'content': 'Number of stars: {}'.format(
res[0]['solidRating'])})
| """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 {
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
def lambda_handler(event: dict, context: dict) -> Optional[dict]:
"""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
spot = event.get("slots", {}).get("SurfSpot", None)
spot = to_msw_id(spot) if spot is not None else None
if not spot:
logger.error("Couldn't parse spot id")
return close('Fulfilled',
{'contentType': 'PlainText',
'content': 'Surf spot not found :('})
res = json.loads(urllib.request.urlopen(
"http://magicseaweed.com/api/{}/forecast/?spot_id={}".format(
settings.MSW_API, spot)).read())
logger.debug('json.response=%s', res)
return close('Fulfilled',
{'contentType': 'PlainText',
'content': 'Number of stars: {}'.format(
res[0]['solidRating'])})
| 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 close('Fulfilled',
{'contentType': 'PlainText',
'content': 'Surf spot not found :('})
- logger.debug('event=%s context=%s', event, context)
res = json.loads(urllib.request.urlopen(
"http://magicseaweed.com/api/{}/forecast/?spot_id={}".format( |
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 NetworkInterfaceNotFoundError
from ._logger import logger
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)
def get_tc_base_command(tc_subcommand):
if tc_subcommand not in TcSubCommand:
raise ValueError("the argument must be a TcSubCommand value")
return "{:s} {:s}".format(find_bin_path("tc"), tc_subcommand.value)
def run_tc_show(subcommand, device):
from ._network import verify_network_interface
verify_network_interface(device)
runner = spr.SubprocessRunner(
"{:s} show dev {:s}".format(get_tc_base_command(subcommand), device))
if runner.run() != 0 and runner.stderr.find("Cannot find device") != -1:
# reach here if the device does not exist at the system and netiface
# not installed.
raise NetworkInterfaceNotFoundError(device=device)
return runner.stdout
| # 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 NetworkInterfaceNotFoundError
from ._logger import logger
def check_tc_command_installation():
if find_bin_path("tc"):
return
logger.error("command not found: tc")
sys.exit(errno.ENOENT)
def get_tc_base_command(tc_subcommand):
if tc_subcommand not in TcSubCommand:
raise ValueError("the argument must be a TcSubCommand value")
return "{:s} {:s}".format(find_bin_path("tc"), tc_subcommand.value)
def run_tc_show(subcommand, device):
from ._network import verify_network_interface
verify_network_interface(device)
runner = spr.SubprocessRunner(
"{:s} show dev {:s}".format(get_tc_base_command(subcommand), device))
if runner.run() != 0 and runner.stderr.find("Cannot find device") != -1:
# reach here if the device does not exist at the system and netiface
# not installed.
raise NetworkInterfaceNotFoundError(device=device)
return runner.stdout
| 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.error("command not found: tc")
+ sys.exit(errno.ENOENT)
def get_tc_base_command(tc_subcommand): |
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):
times = 10
avg_time = timeit.timeit(
"benchmark()",
setup="from __main__ import benchmark",
number=times
) / times
print(
"Of " + repr(times) + " trials," +
" the average runtime = " + repr(avg_time) + "s."
)
return(0)
if __name__ == '__main__':
sys.exit(main(*sys.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, output_array)
def main(*argv):
times = 10
avg_time = timeit.timeit(
"benchmark()",
setup="from __main__ import benchmark",
number=times
) / times
print(
"Of " + repr(times) + " trials," +
" the average runtime = " + repr(avg_time) + "s."
)
return(0)
if __name__ == '__main__':
sys.exit(main(*sys.argv))
| 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.MetricViewSet)
urlpatterns = [
url(r'^dashboard/admin', include(admin.site.urls)),
url(r'^dashboard/api/', include(api_router.urls)),
url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'),
url(r'^$', views.HomeView.as_view(), name='home'),
url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(),
name='metrics-list'),
]
| 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)
api_router.register(r'metrics', views.MetricViewSet)
urlpatterns = [
url(r'^dashboard/admin', include(admin.site.urls)),
url(r'^dashboard/api/', include(api_router.urls)),
url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'),
url(r'^$', views.HomeView.as_view(), name='home'),
url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(),
name='metrics-list'),
]
| 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_length=200)
| """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_length=200)
| 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:
max=len(v)
for v in values:
if len(v)<max:
newV=v+(" " * int(max-len(v)))
if values[v]!=-1:
print newV, values[v]*'|'+'-'*int(50-values[v])
else:
print newV,20*'-'+"UNLIMITED"+21*'-'
else:
if values[v]!=-1:
print v, values[v]*'|'+'-'*int(50-values[v])
else:
print v,20*'-'+"UNLIMITED"+21*'-'
| __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)))
if value!=-1:
print newV, value*'|'+'-'*int(50-value)
else:
print newV,20*'-'+"UNLIMITED"+21*'-'
else:
if value!=-1:
print v, value*'|'+'-'*int(50-value)
else:
print v,20*'-'+"UNLIMITED"+21*'-'
| 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:
max=len(v)
for v in values:
+ value = int(values[v])
if len(v)<max:
newV=v+(" " * int(max-len(v)))
- if values[v]!=-1:
- print newV, values[v]*'|'+'-'*int(50-values[v])
+ if value!=-1:
+ print newV, value*'|'+'-'*int(50-value)
else:
print newV,20*'-'+"UNLIMITED"+21*'-'
else:
- if values[v]!=-1:
- print v, values[v]*'|'+'-'*int(50-values[v])
+ if value!=-1:
+ print v, value*'|'+'-'*int(50-value)
else:
print v,20*'-'+"UNLIMITED"+21*'-'
-
- |
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(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP | 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(auto_now_add=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return unicode(self.name)
@classmethod
def get_all_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP | 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'
],
'Resource': [
'arn:aws:s3:::archaius-stage/forrest/unicornforrest',
'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*'
]
}
]
}
def test_main():
"""Check general assemblage."""
settings = {'services': {'s3': True}}
policy_json = construct_policy(app='unicornforrest',
env='stage',
group='forrest',
pipeline_settings=settings)
assert json.loads(policy_json) == ANSWER1
# TODO: Test other services besides S3
settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest',
'attendantdevops']}})
policy_json = construct_policy(pipeline_settings=settings)
policy = json.loads(policy_json)
| """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'
],
'Resource': [
'arn:aws:s3:::archaius-stage/forrest/unicornforrest',
'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*'
]
}
]
}
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',
env='stage',
group='forrest',
pipeline_settings=settings)
assert json.loads(policy_json) == ANSWER1
# TODO: Test other services besides S3
settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest',
'attendantdevops']}})
policy_json = construct_policy(pipeline_settings=settings)
policy = json.loads(policy_json)
| 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',
env='stage', |
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):
return web.Response()
app = web.Application(loop=loop)
app.router.add_get('/', handler)
server = await test_server(app)
async with aiohttp.ClientSession(loop=loop) as session:
with suppress(RuntimeError):
async with session.get(server.make_url('/')) as resp:
resp.content.set_exception(RuntimeError())
await resp.read()
assert len(session._connector._conns) == 0
async def test_release_resp_on_normal_exit_from_cm(loop, test_server):
async def handler(request):
return web.Response()
app = web.Application(loop=loop)
app.router.add_get('/', handler)
server = await test_server(app)
async with aiohttp.ClientSession(loop=loop) as session:
async with session.get(server.make_url('/')) as resp:
await resp.read()
assert len(session._connector._conns) == 1
| 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/aiohttp,hellysmile/aiohttp,singulared/aiohttp,pfreixes/aiohttp,KeepSafe/aiohttp,Eyepea/aiohttp,alex-eri/aiohttp-1,juliatem/aiohttp,moden-py/aiohttp,AraHaanOrg/aiohttp,pfreixes/aiohttp,playpauseandstop/aiohttp,rutsky/aiohttp | ---
+++
@@ -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_server):
+ async def handler(request):
+ return web.Response()
+
+ app = web.Application(loop=loop)
+ app.router.add_get('/', handler)
+ server = await test_server(app)
+
+ async with aiohttp.ClientSession(loop=loop) as session:
+ with suppress(RuntimeError):
+ async with session.get(server.make_url('/')) as resp:
+ resp.content.set_exception(RuntimeError())
+ await resp.read()
+
+ assert len(session._connector._conns) == 0
+
+
+async def test_release_resp_on_normal_exit_from_cm(loop, test_server):
+ async def handler(request):
+ return web.Response()
+
+ app = web.Application(loop=loop)
+ app.router.add_get('/', handler)
+ server = await test_server(app)
+
+ async with aiohttp.ClientSession(loop=loop) as session:
+ async with session.get(server.make_url('/')) as resp:
+ await resp.read()
+
+ assert len(session._connector._conns) == 1 |
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 (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.modules.events.management.views import WPEventManagement
class WPEventLogs(WPEventManagement):
bundles = ('react.js', 'module_events.logs.js', 'module_events.logs.css')
template_prefix = 'events/logs/'
sidemenu_option = 'logs'
| # 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 (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.modules.events.management.views import WPEventManagement
class WPEventLogs(WPEventManagement):
bundles = ('react.js', 'semantic-ui.js', 'module_events.logs.js', 'module_events.logs.css')
template_prefix = 'events/logs/'
sidemenu_option = 'logs'
| 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/indico,mic4ael/indico,pferreir/indico,OmeGak/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,mvidalgarcia/indico,mic4ael/indico,mic4ael/indico | ---
+++
@@ -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_create_signature_template()
ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690')
assert ref.tag.endswith('Reference')
assert node.xpath('.//*[local-name() = "Reference"]')
| 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_signature_template()
ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690')
assert ref.tag.endswith('Reference')
assert node.xpath('.//*[local-name() = "Reference"]')
def test_add_transform():
node = xmlsec.create_signature_template()
ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690')
xmlsec.add_transform(ref, xmlsec.method.ENVELOPED)
assert ref.xpath('.//*[local-name() = "Transform"]')
def test_ensure_key_info():
node = xmlsec.create_signature_template()
xmlsec.ensure_key_info(node)
assert node.xpath('.//*[local-name() = "KeyInfo"]')
def test_add_x509_data():
node = xmlsec.create_signature_template()
info = xmlsec.ensure_key_info(node)
xmlsec.add_x509_data(info)
assert node.xpath('.//*[local-name() = "X509Data"]')
def test_add_key_name():
node = xmlsec.create_signature_template()
info = xmlsec.ensure_key_info(node)
xmlsec.add_key_name(info, b'bob.pem')
assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]')
| 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(node, uri=b'#_34275907093489075620748690')
assert ref.tag.endswith('Reference')
assert node.xpath('.//*[local-name() = "Reference"]')
+
+
+def test_add_transform():
+ node = xmlsec.create_signature_template()
+ ref = xmlsec.add_reference(node, uri=b'#_34275907093489075620748690')
+ xmlsec.add_transform(ref, xmlsec.method.ENVELOPED)
+
+ assert ref.xpath('.//*[local-name() = "Transform"]')
+
+
+def test_ensure_key_info():
+ node = xmlsec.create_signature_template()
+ xmlsec.ensure_key_info(node)
+
+ assert node.xpath('.//*[local-name() = "KeyInfo"]')
+
+
+def test_add_x509_data():
+ node = xmlsec.create_signature_template()
+ info = xmlsec.ensure_key_info(node)
+ xmlsec.add_x509_data(info)
+
+ assert node.xpath('.//*[local-name() = "X509Data"]')
+
+
+def test_add_key_name():
+ node = xmlsec.create_signature_template()
+ info = xmlsec.ensure_key_info(node)
+ xmlsec.add_key_name(info, b'bob.pem')
+
+ assert node.xpath('.//*[local-name() = "KeyName" and text() = "bob.pem"]') |
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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from os.path import abspath, dirname, join, normpath
class HtmlTemplate(object):
_base_dir = join(dirname(abspath(__file__)), '..', 'htmldata')
def __init__(self, filename):
self._path = normpath(join(self._base_dir, filename.replace('/', os.sep)))
def __iter__(self):
with open(self._path) as file:
for line in file:
yield line.rstrip()
| # 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# 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
class HtmlTemplate(object):
_base_dir = join(dirname(abspath(__file__)), '..', 'htmldata')
def __init__(self, filename):
self._path = normpath(join(self._base_dir, filename.replace('/', os.sep)))
def __iter__(self):
with codecs.open(self._path, encoding='UTF-8') as file:
for line in file:
yield line.rstrip()
| 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)))
def __iter__(self):
- with open(self._path) as file:
+ with codecs.open(self._path, encoding='UTF-8') as file:
for line in file:
yield line.rstrip() |
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 the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'list_revoke_events',
check_str=base.RULE_SERVICE_OR_ADMIN,
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}])
]
def list_rules():
return revoke_event_policies
| # 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 the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
revoke_event_policies = [
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
# specific so it make sense to associate `system` as the scope type
# required for this policy.
scope_types=['system'],
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}])
]
def list_rules():
return revoke_event_policies
| 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
system-scoped tokens for these policies by enabling oslo.policy's
`enforce_scope` configuration option, which will result in an
HTTP Forbidden exception when mismatching scope is used.
Change-Id: I1dddeb216b2523b8471e5f2d5370921bb7a45e7f
| 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
+ # specific so it make sense to associate `system` as the scope type
+ # required for this policy.
+ scope_types=['system'],
description='List revocation events.',
operations=[{'path': '/v3/OS-REVOKE/events',
'method': 'GET'}]) |
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()
custom_attribute_changed = signals.signal(
"Custom Attribute updated",
"""
Indicates that a custom attribute was successfully saved to database.
:obj: The model instance
:value: New custom attribute value
:service: The instance of model handling the Custom Attribute update
operation
""",
)
| # 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()
custom_attribute_changed = signals.signal(
"Custom Attribute updated",
"""
Indicates that a custom attribute was successfully saved to database.
:obj: The model instance
:value: New custom attribute value
:service: The instance of model handling the Custom Attribute update
operation
""",
)
| 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-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core | ---
+++
@@ -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",
+ """
+ Indicates that a custom attribute was successfully saved to database.
- :obj: The model instance
- :value: New custom attribute value
- :service: The instance of model handling the Custom Attribute update
- operation
- """,
+ :obj: The model instance
+ :value: New custom attribute value
+ :service: The instance of model handling the Custom Attribute update
+ operation
+ """,
)
- |
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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for cifar dataset module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets.image import cifar
from tensorflow_datasets.testing import dataset_builder_testing
class Cifar10Test(dataset_builder_testing.TestCase):
DATASET_CLASS = cifar.Cifar10
SPLITS = {
"train": 10, # Number of examples.
"test": 2, # See testing/generate_cifar10_like_example.py
}
if __name__ == "__main__":
dataset_builder_testing.main()
| # 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for cifar dataset module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets.image import cifar
from tensorflow_datasets.testing import dataset_builder_testing
class Cifar10Test(dataset_builder_testing.TestCase):
DATASET_CLASS = cifar.Cifar10
SPLITS = {
"train": 10, # Number of examples.
"test": 2, # See testing/cifar10.py
}
if __name__ == "__main__":
dataset_builder_testing.main()
| 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 f_dr:
writer = dr.Writer(f_dr, Doc)
for filename in sorted(f for f in files if f.endswith('.readability')):
dr_filename = filename.replace('.readability', '.dr')
if not dr_filename in files:
path = os.path.join(root, filename)
with open(path) as f:
try:
data = json.load(f)
except Exception:
pass
else:
if not ('url' in data and 'title' in data and 'content' in data):
continue
id = hashlib.md5(data['url'].encode('utf8')).hexdigest()
title = data.get('title', '')
text = data.get('content', '')
doc = Doc(id=id)
title = title.encode('utf8')
tok.tokenize(title, doc, 0, is_headline=True)
tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False)
print(doc)
writer.write(doc)
| #!/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, 'cluster.dr')
with open(cluster_dr, 'wb') as f_dr:
writer = dr.Writer(f_dr, Doc)
written = 0
for filename in sorted(f for f in files if f.endswith('.readability')):
path = os.path.join(root, filename)
with open(path) as f:
try:
data = json.load(f)
except Exception:
stats['bad json'] += 1
pass
else:
if not ('url' in data and 'title' in data and 'content' in data):
stats['no url/title/content'] += 1
continue
id = hashlib.md5(data['url'].encode('utf8')).hexdigest()
title = data.get('title', '')
text = data.get('content', '')
doc = Doc(id=id)
title = title.encode('utf8')
tok.tokenize(title, doc, 0, is_headline=True)
tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False)
writer.write(doc)
stats['ok'] += 1
written += 1
if not written:
print('No docs written for {}'.format(cluster_dr))
os.remove(cluster_dr)
print('Stats\t{}'.format(dict(stats)))
| 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()
files = set(files)
cluster_dr = os.path.join(root, 'cluster.dr')
with open(cluster_dr, 'wb') as f_dr:
writer = dr.Writer(f_dr, Doc)
+ written = 0
for filename in sorted(f for f in files if f.endswith('.readability')):
- dr_filename = filename.replace('.readability', '.dr')
- if not dr_filename in files:
- path = os.path.join(root, filename)
- with open(path) as f:
- try:
- data = json.load(f)
- except Exception:
- pass
- else:
- if not ('url' in data and 'title' in data and 'content' in data):
- continue
- id = hashlib.md5(data['url'].encode('utf8')).hexdigest()
- title = data.get('title', '')
- text = data.get('content', '')
- doc = Doc(id=id)
- title = title.encode('utf8')
- tok.tokenize(title, doc, 0, is_headline=True)
- tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False)
- print(doc)
- writer.write(doc)
+ path = os.path.join(root, filename)
+ with open(path) as f:
+ try:
+ data = json.load(f)
+ except Exception:
+ stats['bad json'] += 1
+ pass
+ else:
+ if not ('url' in data and 'title' in data and 'content' in data):
+ stats['no url/title/content'] += 1
+ continue
+ id = hashlib.md5(data['url'].encode('utf8')).hexdigest()
+ title = data.get('title', '')
+ text = data.get('content', '')
+ doc = Doc(id=id)
+ title = title.encode('utf8')
+ tok.tokenize(title, doc, 0, is_headline=True)
+ tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False)
+ writer.write(doc)
+ stats['ok'] += 1
+ written += 1
+ if not written:
+ print('No docs written for {}'.format(cluster_dr))
+ os.remove(cluster_dr)
+print('Stats\t{}'.format(dict(stats))) |
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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call('sdb version', shell=True, timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
| #!/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 required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call(['sdb', 'version'], timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
| 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 {}'.format(help_url))
return |
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_calculated = False
delete_tips.delete_tips = "Delete calculated scores for tips for these matches"
class MatchAdmin(admin.ModelAdmin):
actions = [delete_tips]
admin.site.register(Match, MatchAdmin)
admin.site.register(Tip)
| 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_calculated = False
tip.save()
delete_tips.delete_tips = "Delete calculated scores for tips for these matches"
class MatchAdmin(admin.ModelAdmin):
actions = [delete_tips]
admin.site.register(Match, MatchAdmin)
admin.site.register(Tip)
| 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."""
__slots__ = ()
@property
def is_square(self):
return self.width == self.height
ImageType = Enum('ImageType', ['gif', 'jpeg', 'png']) # type: ignore
| """
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."""
__slots__ = ()
@property
def is_square(self):
return self.width == self.height
ImageType = Enum('ImageType', ['gif', 'jpeg', 'png'])
| 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.