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
ce38ad1884cdc602d1b70d5a23d749ff3683f440
reqon/utils.py
reqon/utils.py
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' for item in value: if isinstance(item, dict): return True return False
def dict_in(value): ''' Checks for the existence of a dictionary in a list Arguments: value -- A list Returns: A Boolean ''' return any(isinstance(item, dict) for item in value)
Make the dict_in function sleeker and sexier
Make the dict_in function sleeker and sexier
Python
mit
dmpayton/reqon
--- +++ @@ -8,7 +8,4 @@ Returns: A Boolean ''' - for item in value: - if isinstance(item, dict): - return True - return False + return any(isinstance(item, dict) for item in value)
1e2d1f25cb36db7383e6a2300e2e96d47113cc16
cryptography/primitives/block/ciphers.py
cryptography/primitives/block/ciphers.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...
# 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...
Make key_sizes a frozenset, since these are/should be immutable
Make key_sizes a frozenset, since these are/should be immutable
Python
bsd-3-clause
kimvais/cryptography,Ayrx/cryptography,kimvais/cryptography,Hasimir/cryptography,Lukasa/cryptography,dstufft/cryptography,skeuomorf/cryptography,sholsapp/cryptography,Hasimir/cryptography,Ayrx/cryptography,kimvais/cryptography,dstufft/cryptography,sholsapp/cryptography,dstufft/cryptography,skeuomorf/cryptography,sholsa...
--- +++ @@ -17,7 +17,7 @@ class AES(object): name = "AES" block_size = 128 - key_sizes = set([128, 192, 256]) + key_sizes = frozenset([128, 192, 256]) def __init__(self, key): super(AES, self).__init__()
ad79f01358aa83162730b15507d7d6d3c3575ab3
akanda/horizon/configuration/tabs.py
akanda/horizon/configuration/tabs.py
import collections import logging from django.utils.translation import ugettext as _ from horizon.api import quantum from horizon import tabs from akanda.horizon.configuration.tables.publicips import PublicIPsTable # The table rendering code assumes it is getting an # object with an "id" property and other propert...
import collections import logging from django.utils.translation import ugettext as _ from horizon.api import quantum from horizon import tabs from akanda.horizon.configuration.tables.publicips import PublicIPsTable # The table rendering code assumes it is getting an # object with an "id" property and other propert...
Handle missing port and router data
Handle missing port and router data On some systems routers have no ports and ports have no fixed IPs, so don't assume they do. Also includes some pep8 fixes. Change-Id: I73b5f22754958b897a6ae55e453c294f47bf9539 Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>
Python
apache-2.0
dreamhost/akanda-horizon,dreamhost/akanda-horizon
--- +++ @@ -28,10 +28,11 @@ def get_publicips_data(self): data = [] c = quantum.quantumclient(self.request) - for router in c.list_routers(tenant_id=self.request.user.tenant_id).values()[0]: - for port in router['ports']: - if port['device_owner'] != 'network:ro...
024209cdefd34e26983ea4910071ccbd1a33faaa
pyramid_celery/__init__.py
pyramid_celery/__init__.py
from celery.app import default_app from celery.app import defaults def clean_quoted_config(config, key): # ini doesn't allow quoting, but lets support it to fit with celery config[key] = config[key].replace('"', '') TYPES_TO_OBJ = { 'any': (object, None), 'bool': (bool, defaults.str_to_bool), 'di...
from celery.app import default_app from celery.app import defaults def clean_quoted_config(config, key): # ini doesn't allow quoting, but lets support it to fit with celery config[key] = config[key].replace('"', '') TYPES_TO_OBJ = { 'any': (object, None), 'bool': (bool, defaults.str_to_bool), 'di...
Change dict-comprehension for python 2.6 compatibility.
Change dict-comprehension for python 2.6 compatibility.
Python
mit
edelooff/pyramid_celery,miohtama/pyramid_celery
--- +++ @@ -18,10 +18,10 @@ } -OPTIONS = { - key: TYPES_TO_OBJ[opt.type] +OPTIONS = ( + (key, TYPES_TO_OBJ[opt.type]) for key, opt in defaults.flatten(defaults.NAMESPACES) -} +) def convert_celery_options(config):
b0b1be44c64ed48c15f9e796b90a21e7e4597df8
jsrn/encoding.py
jsrn/encoding.py
# -*- coding: utf-8 -*- import json import registration import resources class JSRNEncoder(json.JSONEncoder): """ Encoder for JSRN resources. """ def default(self, o): if isinstance(o, resources.Resource): state = o.__getstate__() state['$'] = o._meta.resource_name ...
# -*- coding: utf-8 -*- import json import resources class JSRNEncoder(json.JSONEncoder): """ Encoder for JSRN resources. """ def default(self, o): if isinstance(o, resources.Resource): obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields} obj[resour...
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
Python
bsd-3-clause
timsavage/jsrn,timsavage/jsrn
--- +++ @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- import json -import registration import resources @@ -10,24 +9,21 @@ """ def default(self, o): if isinstance(o, resources.Resource): - state = o.__getstate__() - state['$'] = o._meta.resource_name - return state...
f6e35897ce3b7e335310016c16a3bf76645bf077
lib/authenticator.py
lib/authenticator.py
# # HamperAuthenticator is the class to handle the authentication part of the provisioning portal. # Instantiate with the email and password you want, it'll pass back the cookie jar if successful, # or an error message on failure # from helpers.driver import HamperDriver class HamperAuthenticator(object): def __init...
# # HamperAuthenticator is the class to handle the authentication part of the provisioning portal. # Instantiate with the email and password you want, it'll pass back the cookie jar if successful, # or an error message on failure # from helpers.driver import HamperDriver from helpers.error import HamperError from term...
Throw exception if invalid login details are used
Throw exception if invalid login details are used
Python
mit
MobileXLabs/hamper
--- +++ @@ -4,6 +4,9 @@ # or an error message on failure # from helpers.driver import HamperDriver +from helpers.error import HamperError + +from termcolor import colored class HamperAuthenticator(object): @@ -13,6 +16,8 @@ def sign_in(self, email=None, password=None): # Grab the HamperDriver singleton ...
15e9e3231386cb5a194e184e7b24fed8030f0d41
Server/server.py
Server/server.py
import serial import schedule import time from flask import Flask, request from threading import Thread from influxdb import InfluxDBClient COM_PORT = 2 BAUDRATE = 9600 READ_THREAD = 10 DB_HOST = 'localhost' DB_HOST_PORT = 8086 DB_NAME = 'awarehouse' DB_PASS = 'admin' DB_USER = 'admin' influxdb = InfluxDBClient(DB_HO...
import serial import schedule import time import json from flask import Flask, request from threading import Thread from influxdb import InfluxDBClient COM_PORT = 2 BAUDRATE = 9600 READ_SENSORS_TIMER = 1 DB_HOST = '192.168.1.73' DB_PORT = 8086 DB_NAME = 'awarehouse' DB_PASS = 'admin' DB_USER = 'admin' influxdb = Infl...
Add example points for InfluxDB
Add example points for InfluxDB
Python
mit
jpdias/aWareHouse,jpdias/aWareHouse,jpdias/aWareHouse,jpdias/aWareHouse
--- +++ @@ -1,20 +1,21 @@ import serial import schedule import time +import json from flask import Flask, request from threading import Thread from influxdb import InfluxDBClient COM_PORT = 2 BAUDRATE = 9600 -READ_THREAD = 10 -DB_HOST = 'localhost' -DB_HOST_PORT = 8086 +READ_SENSORS_TIMER = 1 +DB_HOST = '19...
4b93e5aa8c0ce90189fb852e75ee213d3be0d01a
flicks/base/urls.py
flicks/base/urls.py
from django.conf.urls.defaults import patterns, url from flicks.base import views urlpatterns = patterns('', url(r'^/?$', views.home, name='flicks.base.home'), url(r'^strings/?$', views.strings, name='flicks.base.strings'), )
from django.conf.urls.defaults import patterns, url from flicks.base import views urlpatterns = patterns('', url(r'^/?$', views.home, name='flicks.base.home'), url(r'^faq/?$', views.faq, name='flicks.base.faq'), url(r'^strings/?$', views.strings, name='flicks.base.strings'), )
Add back in FAQ url that was removed accidentally.
Add back in FAQ url that was removed accidentally.
Python
bsd-3-clause
mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks,mozilla/firefox-flicks
--- +++ @@ -4,5 +4,6 @@ urlpatterns = patterns('', url(r'^/?$', views.home, name='flicks.base.home'), + url(r'^faq/?$', views.faq, name='flicks.base.faq'), url(r'^strings/?$', views.strings, name='flicks.base.strings'), )
b236a7961dbc9930ed135602cbed783818bde16e
kolibri/utils/tests/test_cli_at_import.py
kolibri/utils/tests/test_cli_at_import.py
""" Tests for `kolibri.utils.cli` module. These tests deliberately omit `@pytest.mark.django_db` from the tests, so that any attempt to access the Django database during the running of these cli methods will result in an error and test failure. """ from __future__ import absolute_import from __future__ import print_fun...
""" Tests for `kolibri.utils.cli` module. These tests deliberately omit `@pytest.mark.django_db` from the tests, so that any attempt to access the Django database during the running of these cli methods will result in an error and test failure. """ from __future__ import absolute_import from __future__ import print_fun...
Add regression test against options evaluation during import in cli.
Add regression test against options evaluation during import in cli.
Python
mit
learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri
--- +++ @@ -36,3 +36,10 @@ except SystemExit: pass create_engine_mock.assert_not_called() + + +@patch("kolibri.utils.options.read_options_file") +def test_import_no_options_evaluation(read_options_mock): + from kolibri.utils import cli # noqa F401 + + read_options_mock.assert_not_called()
013277886a3c9f5d4ab99f11da6a447562fe9e46
benchexec/tools/cmaesfuzz.py
benchexec/tools/cmaesfuzz.py
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import re import benchexec.util as util import benchexec.tools.template class Tool(benc...
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import re import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2)...
Update module to version 2
Update module to version 2
Python
apache-2.0
sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec
--- +++ @@ -7,11 +7,9 @@ import re -import benchexec.util as util import benchexec.tools.template - -class Tool(benchexec.tools.template.BaseTool): +class Tool(benchexec.tools.template.BaseTool2): """ Fuzzing with stochastic optimization guided by CMA-ES @@ -27,8 +25,8 @@ "verifiers_real"...
cde8c1b4c89a2e0ef3765372b4838373d5729cdb
alg_topological_sort.py
alg_topological_sort.py
def topological_sort_recur(adjacency_dict, start_vertex, visited_set, finish_ls): """Topological Sorting by Recursion.""" visited_set.add(start_vertex) for neighbor_vertex in adjacency_dict[start_vertex]: if neighbor_vertex not in visited_set: topological_sort_recur( adjacency_dict, ...
def topological_sort_recur(adjacency_dict, start_vertex, visited_set, finish_ls): """Topological Sorting by Recursion.""" visited_set.add(start_vertex) for neighbor_vertex in adjacency_dict[start_vertex] - visited_set: topological_sort_recur( adjacency_dict, neighbor_vertex, ...
Revise for loop to find neighbor vertices
Revise for loop to find neighbor vertices
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -2,8 +2,7 @@ visited_set, finish_ls): """Topological Sorting by Recursion.""" visited_set.add(start_vertex) - for neighbor_vertex in adjacency_dict[start_vertex]: - if neighbor_vertex not in visited_set: + for neighbor_vertex in adjacency_dict[start_vertex] - visited_set: ...
5496f501ff7da677ee76c442b6a5b544d595ce1d
epages/__init__.py
epages/__init__.py
# coding: utf-8 from epages.client import * from epages.product_service import * from epages.shop_service import * from epages.shop import *
# coding: utf-8 from epages.client import * from epages.shop_service import * from epages.shop import *
Remove product_service from epages package
Remove product_service from epages package
Python
mit
ooz/epages-rest-python,ooz/epages-rest-python
--- +++ @@ -2,7 +2,6 @@ from epages.client import * -from epages.product_service import * from epages.shop_service import * from epages.shop import *
a52bf3cbd84a6e1c9b0a685d3267934ec0ec0036
misc/decode-mirax.py
misc/decode-mirax.py
#!/usr/bin/python import struct, sys f = open(sys.argv[1]) HEADER_OFFSET = 37 f.seek(HEADER_OFFSET) try: while True: n = struct.unpack("<i", f.read(4))[0] possible_lineno = (n - HEADER_OFFSET) / 4.0 if possible_lineno < 0 or int(possible_lineno) != possible_lineno: print "%1...
#!/usr/bin/python import struct, sys, os f = open(sys.argv[1]) HEADER_OFFSET = 37 f.seek(HEADER_OFFSET) filesize = os.stat(sys.argv[1]).st_size num_items = (filesize - HEADER_OFFSET) / 4 skipped = False i = 0 try: while True: n = struct.unpack("<i", f.read(4))[0] possible_lineno = (n - HEADER...
Update decode mirax a bit
Update decode mirax a bit
Python
lgpl-2.1
openslide/openslide,openslide/openslide,openslide/openslide,openslide/openslide
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/python -import struct, sys +import struct, sys, os f = open(sys.argv[1]) @@ -8,13 +8,34 @@ f.seek(HEADER_OFFSET) +filesize = os.stat(sys.argv[1]).st_size +num_items = (filesize - HEADER_OFFSET) / 4 + +skipped = False +i = 0 + try: while True: n = struct.u...
8dbf9d88be33537752f105cd8f8b60ec40de684a
docs/src/examples/over_play.py
docs/src/examples/over_play.py
import numpy as np from scikits.audiolab import play # output one second of stereo gaussian white noise at 48000 hz play(0.05 * np.random.randn(2, 48000), rate=48000)
import numpy as np from scikits.audiolab import play # output one second of stereo gaussian white noise at 48000 hz play(0.05 * np.random.randn(2, 48000))
Fix play example (thanks to Samuele CarCagno).
Fix play example (thanks to Samuele CarCagno).
Python
lgpl-2.1
cournape/audiolab,cournape/audiolab,cournape/audiolab
--- +++ @@ -2,4 +2,4 @@ from scikits.audiolab import play # output one second of stereo gaussian white noise at 48000 hz -play(0.05 * np.random.randn(2, 48000), rate=48000) +play(0.05 * np.random.randn(2, 48000))
e64d13486fe20c44dde0dea6a6fed5a95eddbbd1
awx/main/notifications/email_backend.py
awx/main/notifications/email_backend.py
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import json from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend from django.utils.translation import ugettext_lazy as _ class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host",...
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import json from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend from django.utils.translation import ugettext_lazy as _ class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host",...
Remove Tower reference from email backend
Remove Tower reference from email backend
Python
apache-2.0
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx
--- +++ @@ -25,7 +25,7 @@ if "body" in body: body_actual = body['body'] else: - body_actual = smart_text(_("{} #{} had status {} on Ansible Tower, view details at {}\n\n").format( + body_actual = smart_text(_("{} #{} had status {}, view details at {}\n\n").format( ...
fc25a6c4796ad008570974a682037bc575f15018
astroquery/lamda/tests/test_lamda.py
astroquery/lamda/tests/test_lamda.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from ... import lamda def test_query(): Q = lamda.core.LAMDAQuery() Q.lamda_query(mol='co', query_type='erg_levels') Q.lamda_query(mol='co', query_type='rad_trans') Q.lamda_query(mol='co', query_type='coll_rates')
# Licensed under a 3-clause BSD style license - see LICENSE.rst from ... import lamda def test_query(): lamda.print_mols() lamda.query(mol='co', query_type='erg_levels') lamda.query(mol='co', query_type='rad_trans') lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
Update tests for new style
Update tests for new style Also added test for printing molecule list and made the collisional rate test more complicated.
Python
bsd-3-clause
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
--- +++ @@ -2,8 +2,8 @@ from ... import lamda def test_query(): - Q = lamda.core.LAMDAQuery() - Q.lamda_query(mol='co', query_type='erg_levels') - Q.lamda_query(mol='co', query_type='rad_trans') - Q.lamda_query(mol='co', query_type='coll_rates') + lamda.print_mols() + lamda.query(mol='co', query...
0cfd376b02da6ebc70ad66c913e3ee4750a6a04c
functional_tests.py
functional_tests.py
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title
from selenium import webdriver import pytest @pytest.fixture(scope='function') def browser(request): browser_ = webdriver.Firefox() def fin(): browser_.quit() request.addfinalizer(fin) return browser_ def test_can_show_a_relevant_code_snippet(browser): browser.get('http://localhost:800...
Refactor FTs to setup/teardown with pytest.fixture
Refactor FTs to setup/teardown with pytest.fixture
Python
mit
jvanbrug/scout,jvanbrug/scout
--- +++ @@ -1,6 +1,19 @@ from selenium import webdriver +import pytest -browser = webdriver.Firefox() -browser.get('http://localhost:8000') -assert 'Django' in browser.title +@pytest.fixture(scope='function') +def browser(request): + browser_ = webdriver.Firefox() + + def fin(): + browser_.quit() + ...
09eb16e94052cbf45708b20e783a602342a2b85b
photutils/__init__.py
photutils/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Photutils is an Astropy affiliated package to provide tools for detecting and performing photometry of astronomical sources. It also has tools for background estimation, ePSF building, PSF matching, centroiding, and morphological measurements. """ im...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Photutils is an Astropy affiliated package to provide tools for detecting and performing photometry of astronomical sources. It also has tools for background estimation, ePSF building, PSF matching, centroiding, and morphological measurements. """ im...
Add __all__ in package init for the test runner
Add __all__ in package init for the test runner
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
--- +++ @@ -24,6 +24,8 @@ from .psf import * # noqa from .segmentation import * # noqa +__all__ = ['test'] # the test runner is defined in _astropy_init + # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex():
8fa1cae882c0ff020c0b9c3c2fac9e4248d46ce4
deploy/common/sqlite_wrapper.py
deploy/common/sqlite_wrapper.py
import sqlite3 class SQLiteWrapper: def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() self.cursor.execute("PRAGMA cache_size=-16000") self.cursor.execute("PRAGMA synchronous=OFF") self.conn.commit() def query(self, sql, params=None, iterator=False, fetch_one=False, m...
import sqlite3 class SQLiteWrapper: def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() self.cursor.execute("PRAGMA page_size=4096") self.cursor.execute("PRAGMA cache_size=-16000") self.cursor.execute("PRAGMA synchronous=NORMAL") self.conn.commit() def query(self, sq...
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
Python
mit
mikispag/bitiodine
--- +++ @@ -4,8 +4,9 @@ def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() + self.cursor.execute("PRAGMA page_size=4096") self.cursor.execute("PRAGMA cache_size=-16000") - self.cursor.execute("PRAGMA synchronous=OFF") + self.cursor.execute("PRAGMA synchronous=NORMAL...
b3f60cfd4c1a4241c44fcd6738cbc59b9780af70
Lib/test/outstanding_bugs.py
Lib/test/outstanding_bugs.py
# # This file is for everybody to add tests for bugs that aren't # fixed yet. Please add a test case and appropriate bug description. # # When you fix one of the bugs, please move the test to the correct # test_ module. # import unittest from test import test_support class TestBug1385040(unittest.TestCase): def t...
# # This file is for everybody to add tests for bugs that aren't # fixed yet. Please add a test case and appropriate bug description. # # When you fix one of the bugs, please move the test to the correct # test_ module. # import unittest from test import test_support # # No test cases for outstanding bugs at the mome...
Update outstanding bugs test file.
Update outstanding bugs test file.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -9,19 +9,14 @@ import unittest from test import test_support -class TestBug1385040(unittest.TestCase): - def testSyntaxError(self): - import compiler - - # The following snippet gives a SyntaxError in the interpreter - # - # If you compile and exec it, the call foo(7) ret...
e2fa4b150546be4b4f0ae59f18ef6ba2b6180d1a
accounts/serializers.py
accounts/serializers.py
"""Serializers for account models""" # pylint: disable=too-few-public-methods from rest_framework import serializers from accounts.models import User class UserSerializer(serializers.ModelSerializer): """Serializer for Users""" class Meta: """Model and field definitions""" model = User ...
"""Serializers for account models""" # pylint: disable=too-few-public-methods from rest_framework import serializers from accounts.models import User class UserSerializer(serializers.ModelSerializer): """Serializer for Users""" class Meta: """Model and field definitions""" model = User ...
Change avatar to avatar_url in the user API
Change avatar to avatar_url in the user API
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
--- +++ @@ -9,13 +9,14 @@ class Meta: """Model and field definitions""" + model = User fields = ( - 'id', - 'username', - 'email', - 'website', - 'avatar', - 'steamid', - 'is_staff', + "id", + ...
ce98707e94a772434eaca56791c1b4980da36bf0
node/trust/global.py
node/trust/global.py
import obelisk import sys from twisted.internet import reactor TESTNET = True def build_output_info_list(unspent_rows): unspent_infos = [] for row in unspent_rows: assert len(row) == 4 outpoint = obelisk.OutPoint() outpoint.hash = row[0] outpoint.index = row[1] value ...
Add algorithm for provably unspendable address generation
Add algorithm for provably unspendable address generation
Python
mit
saltduck/OpenBazaar,dionyziz/OpenBazaar,Renelvon/OpenBazaar,STRML/OpenBazaar,dionyziz/OpenBazaar,NolanZhao/OpenBazaar,mirrax/OpenBazaar,hoffmabc/OpenBazaar,atsuyim/OpenBazaar,bglassy/OpenBazaar,must-/OpenBazaar,NolanZhao/OpenBazaar,akhavr/OpenBazaar,rllola/OpenBazaar,im0rtel/OpenBazaar,hoffmabc/OpenBazaar,dlcorporation...
--- +++ @@ -0,0 +1,44 @@ +import obelisk + +import sys +from twisted.internet import reactor + + +TESTNET = True + +def build_output_info_list(unspent_rows): + unspent_infos = [] + for row in unspent_rows: + assert len(row) == 4 + outpoint = obelisk.OutPoint() + outpoint.hash = row[0] + ...
9699d573fa459cb7ee90237d7fa64f7014c96db4
scripts/update_centroid_reports.py
scripts/update_centroid_reports.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics()
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
Fix script default to actually save plots
Fix script default to actually save plots
Python
bsd-3-clause
sot/mica,sot/mica
--- +++ @@ -3,4 +3,4 @@ import mica.centroid_dashboard # Cheat. Needs entrypoint scripts -mica.centroid_dashboard.update_observed_metrics() +mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
2828bdaaf15f1358211ecac376beb0072c0ef7bf
sentry/contrib/logbook/__init__.py
sentry/contrib/logbook/__init__.py
import logbook import sys class SentryLogbookHandler(logbook.Handler): def emit(self, record): from sentry import capture # Avoid typical config issues by overriding loggers behavior if record.name == 'sentry.errors': print >> sys.stderr, "Recursive log message sent to SentryH...
import logbook from sentry import capture class SentryLogbookHandler(logbook.Handler): def emit(self, record): # TODO: level should be a string tags = (('level', record.level), ('logger', record.channel)) if record.exc_info: return capture('Exception', exc_info=record...
Clean up logbook handler to use correct params for capture()
Clean up logbook handler to use correct params for capture()
Python
bsd-3-clause
dcramer/sentry-old,dcramer/sentry-old,dcramer/sentry-old
--- +++ @@ -1,24 +1,14 @@ import logbook -import sys +from sentry import capture class SentryLogbookHandler(logbook.Handler): def emit(self, record): - from sentry import capture - # Avoid typical config issues by overriding loggers behavior - if record.name == 'sentry.errors': - ...
cc317eb3244edb0ef5424d45d333e255247c46cd
src/runApp.py
src/runApp.py
import sys from PyQt5 import QtWidgets from gui.mainWindow import MainWindow app = QtWidgets.QApplication(sys.argv) playerWindow = MainWindow() playerWindow.show() app.aboutToQuit.connect(playerWindow.exit) sys.exit(app.exec_())
import sys from PyQt5 import QtWidgets from gui.mainWindow import MainWindow app = QtWidgets.QApplication(sys.argv) playerWindow = MainWindow() playerWindow.show() app.aboutToQuit.connect(playerWindow.stop) sys.exit(app.exec_())
Revert "Do not write to the configuration file on each stop."
Revert "Do not write to the configuration file on each stop." This reverts commit 486d2c3e6062f370c7be499ddef10d816fc3f85c.
Python
mit
michael-stanin/Subtitles-Distributor
--- +++ @@ -8,5 +8,5 @@ app = QtWidgets.QApplication(sys.argv) playerWindow = MainWindow() playerWindow.show() -app.aboutToQuit.connect(playerWindow.exit) +app.aboutToQuit.connect(playerWindow.stop) sys.exit(app.exec_())
733306f0953b9c80ead49529ba3e65b26a031426
gaphor/diagram/classes/implementation.py
gaphor/diagram/classes/implementation.py
""" Implementation of interface. """ from gaphor import UML from gaphor.diagram.diagramline import DiagramLine class ImplementationItem(DiagramLine): __uml__ = UML.Implementation def __init__(self, id=None, model=None): DiagramLine.__init__(self, id, model) self._solid = False def draw...
""" Implementation of interface. """ from gaphor import UML from gaphor.UML.modelfactory import stereotypes_str from gaphor.diagram.presentation import LinePresentation from gaphor.diagram.shapes import Box, Text from gaphor.diagram.support import represents @represents(UML.Implementation) class ImplementationItem(L...
Use new line style for Implementation item
Use new line style for Implementation item
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
--- +++ @@ -3,16 +3,25 @@ """ from gaphor import UML -from gaphor.diagram.diagramline import DiagramLine +from gaphor.UML.modelfactory import stereotypes_str +from gaphor.diagram.presentation import LinePresentation +from gaphor.diagram.shapes import Box, Text +from gaphor.diagram.support import represents -c...
9ce26dfb42753570ad7a2c89e51638aa5d49df2b
fedora/__init__.py
fedora/__init__.py
# Copyright 2008 Red Hat, Inc. # This file is part of python-fedora # # python-fedora is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later ...
# Copyright 2008 Red Hat, Inc. # This file is part of python-fedora # # python-fedora is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later ...
Use kitchen.i18n to setup gettext. Setup b_() for exceptions.
Use kitchen.i18n to setup gettext. Setup b_() for exceptions.
Python
lgpl-2.1
fedora-infra/python-fedora
--- +++ @@ -23,13 +23,14 @@ Modules to communicate with and help implement Fedora Services. ''' -import gettext -translation = gettext.translation('python-fedora', '/usr/share/locale', - fallback=True) -_ = translation.ugettext +import kitchen +# Setup gettext for all of kitchen. +# Remember -- _() is for ...
d7fc29fb6e0c449617cf6aae1025fd5b718d8b70
modules/token.py
modules/token.py
class Token(object): def __init__( self, line ): entries = line.split('\t') self.form = entries[0].lower() self.gold_pos = entries[1] self.predicted_pos = entries [3] def createFeatureVector(self, featvec, currentToken, previousToken, nextToken): self.sparseFeatvec = {} #if previousToken: self.sparseF...
class Token(object): def __init__( self, line ): # Splits line tab-wise, writes the values in parameters entries = line.split('\t') if len(entries) == 4: self.form = entries[0].lower() self.gold_pos = entries[1] self.predicted_pos = entries [3] elif len(entries) > 4: print "\tInput file not in expe...
Handle wrong formatted input, added comments, some cosmetics
Handle wrong formatted input, added comments, some cosmetics
Python
mit
YNedderhoff/perceptron-pos-tagger,YNedderhoff/named-entity-recognizer,YNedderhoff/perceptron-pos-tagger,YNedderhoff/aspect-classifier,YNedderhoff/aspect-classifier,YNedderhoff/named-entity-recognizer
--- +++ @@ -1,23 +1,37 @@ class Token(object): def __init__( self, line ): + + # Splits line tab-wise, writes the values in parameters + entries = line.split('\t') - self.form = entries[0].lower() - self.gold_pos = entries[1] - self.predicted_pos = entries [3] + if len(entries) == 4: + self.form = entrie...
7d08a71874dd7b1ab7ba4bb1cd345161d9118266
src/extract.py
src/extract.py
import os import csv from parser import Parser class Extract: """ Extract data from .git repo and persist as a data set """ # repos name git: .git # destination absolute path def clone_repo(self, repo_name, destination): Repo.clone_from(repo_name, destination) # get parsed .diff file def get_parsed_diff(sel...
import os import csv from parser import Parser class Extract: """ Extract data from .git repo and persist as a data set """ # repos name git: .git # destination absolute path def clone_repo(self, repo_name, destination): Repo.clone_from(repo_name, destination) # get parsed .diff file def get_parsed_diff(sel...
Move repo name to arg
Move repo name to arg
Python
mit
rajikaimal/emma,rajikaimal/emma
--- +++ @@ -12,12 +12,12 @@ Repo.clone_from(repo_name, destination) # get parsed .diff file - def get_parsed_diff(self): + def get_parsed_diff(self, repo_path): prev_commiter = None parser = Parser() full_path = os.path.dirname( os.path.realpath(__file__)) - for diff_info in parser.parse...
8d04bb798648980a2fe29ee408bdcff099bfd2c1
tk/urls.py
tk/urls.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^material/', include('tk.material.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin from django.views.generic.base import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='base.html'), name='frontpage'), url(r'^material/', include('tk.material.urls')), url(r'^admin/', admin.s...
Add a frontpage rendering view
Add a frontpage rendering view
Python
agpl-3.0
GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa
--- +++ @@ -1,8 +1,11 @@ from django.conf.urls import url, include from django.contrib import admin +from django.views.generic.base import TemplateView urlpatterns = [ + url(r'^$', TemplateView.as_view(template_name='base.html'), name='frontpage'), + url(r'^material/', include('tk.material.urls...
09498335615b7e770f5976b9749d68050966501d
models/timeandplace.py
models/timeandplace.py
#!/usr/bin/env python3 from .base import Serializable from .locations import Platform from datetime import datetime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival ...
#!/usr/bin/env python3 from .base import Serializable from .locations import Platform from .realtime import RealtimeTime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival ...
Revert "TimeAndPlace no longer refers to realtime data"
Revert "TimeAndPlace no longer refers to realtime data" This reverts commit cf92e191e3748c67102f142b411937517c5051f4.
Python
apache-2.0
NoMoKeTo/choo,NoMoKeTo/transit
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python3 from .base import Serializable from .locations import Platform -from datetime import datetime +from .realtime import RealtimeTime class TimeAndPlace(Serializable): @@ -16,8 +16,8 @@ def _validate(cls): return { 'platform': (None, Platfo...
cd471449edad56ef6c3a69d025130f4fb8ea1fea
plumbium/artefacts.py
plumbium/artefacts.py
import os.path from utils import file_sha1sum class Artefact(object): def __init__(self, filename, extension): if not filename.endswith(extension): raise ValueError self._filename = filename self._ext_length = len(extension) self._abspath = os.path.abspath(filename) ...
import os.path from utils import file_sha1sum class Artefact(object): def __init__(self, filename, extension): if not filename.endswith(extension): raise ValueError self._filename = filename self._ext_length = len(extension) self._abspath = os.path.abspath(filename) ...
Use correct method to get classname of self
Use correct method to get classname of self
Python
mit
jstutters/Plumbium
--- +++ @@ -33,7 +33,7 @@ return self._filename def __repr__(self): - return 'Artefact({0!r})'.format(self.filename) + return '{0}({1!r})'.format(self.__class__.__name__, self.filename) class NiiGzImage(Artefact): @@ -41,7 +41,7 @@ super(NiiGzImage, self).__init__(filename,...
a5d61bee86c394cf6bc972020cbfe2f95463d1e2
huxley/www/views.py
huxley/www/views.py
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json from huxley.api.serializers import UserSerializer from huxley.utils.shortcuts import render_template def index(request): user_dict = {}; if request....
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json from huxley.api.serializers import UserSerializer from huxley.utils.shortcuts import render_template def index(request): user_dict = {}; if request....
Fix XSS vulnerability in current user bootstrapping.
Fix XSS vulnerability in current user bootstrapping.
Python
bsd-3-clause
bmun/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,bmun/huxley,bmun/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,bmun/huxley,nathanielparke/huxley
--- +++ @@ -12,5 +12,5 @@ if request.user.is_authenticated(): user_dict = UserSerializer(request.user).data - context = {'user_json': json.dumps(user_dict)} + context = {'user_json': json.dumps(user_dict).replace('</', '<\\/')} return render_template(request, 'www.html', context)
049e8c746b5f40b3e708dcd749052405e2246160
lc0084_largest_rectangle_in_histogram.py
lc0084_largest_rectangle_in_histogram.py
"""Leetcode 84. Largest Rectangle in Histogram Hard URL: https://leetcode.com/problems/largest-rectangle-in-histogram/ Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each ...
"""Leetcode 84. Largest Rectangle in Histogram Hard URL: https://leetcode.com/problems/largest-rectangle-in-histogram/ Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each ...
Complete increasing heights idx stack sol
Complete increasing heights idx stack sol
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -15,17 +15,40 @@ Output: 10 """ -class Solution(object): +class SolutionIncreasingHeightIdxStack(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ - pass + # Use stack to collect idx of buildings with in...
59bf9eca217ef8ef3011124d1ff9e1570e8ff76d
plugins/clue/clue.py
plugins/clue/clue.py
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] def process_message(data): outputs.append([data['channel'], "from repeat1 \"{}\" in channel {}".format( data['text'], data['channel'])] )
from __future__ import unicode_literals # don't convert to ascii in py2.7 when creating string to return crontable = [] outputs = [] def process_message(data): outputs.append([data['channel'], data['text']])
Simplify stony's response to exactly what the user sent
Simplify stony's response to exactly what the user sent Rather than providing the "from repeat1" and "in channel D???????" noise.
Python
mit
cworth-gh/stony
--- +++ @@ -6,6 +6,4 @@ def process_message(data): - outputs.append([data['channel'], "from repeat1 \"{}\" in channel {}".format( - data['text'], data['channel'])] - ) + outputs.append([data['channel'], data['text']])
6d76842d9f9394aa78cda55fff9c62a4db5da5c6
common.py
common.py
from __future__ import print_function import os, pyrax, sys import pyrax.exceptions as pexc from termcolor import colored import ConfigParser from subprocess import check_output path = os.path.dirname(os.path.realpath(__file__)) config_file = path + "/config.ini" def log(level, message): if level == 'OK': print...
from __future__ import print_function import os, pyrax, sys import pyrax.exceptions as pexc from termcolor import colored import ConfigParser import subprocess path = os.path.dirname(os.path.realpath(__file__)) config_file = path + "/config.ini" def log(level, message): if level == 'OK': print(colored('[ OK ]...
Fix for python 2.6 compatibility in subprocess
Fix for python 2.6 compatibility in subprocess
Python
apache-2.0
boxidau/rax-autoscaler,boxidau/rax-autoscaler,eljrax/rax-autoscaler,rackerlabs/rax-autoscaler
--- +++ @@ -3,7 +3,7 @@ import pyrax.exceptions as pexc from termcolor import colored import ConfigParser -from subprocess import check_output +import subprocess path = os.path.dirname(os.path.realpath(__file__)) config_file = path + "/config.ini" @@ -39,6 +39,6 @@ raise Exception('Unknown config section'...
9347f3bc4a9c37c7013e8666f86cceee1a7a17f9
genome_designer/main/startup.py
genome_designer/main/startup.py
"""Actions to run at server startup. """ from django.db import connection def run(): """Call this from manage.py or tests. """ _add_custom_mult_agg_function() def _add_custom_mult_agg_function(): """Make sure the Postgresql database has a custom function array_agg_mult. NOTE: Figured out the r...
"""Actions to run at server startup. """ from django.db import connection from django.db import transaction def run(): """Call this from manage.py or tests. """ _add_custom_mult_agg_function() def _add_custom_mult_agg_function(): """Make sure the Postgresql database has a custom function array_agg_...
Fix bug with array_agg_mult() function not actually being created.
Fix bug with array_agg_mult() function not actually being created.
Python
mit
churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,woodymit/millstone_accidental_source
--- +++ @@ -2,6 +2,7 @@ """ from django.db import connection +from django.db import transaction def run(): @@ -33,3 +34,4 @@ ' ,INITCOND = \'{}\'' ');' ) + transaction.commit_unless_managed()
3e2b06aa73488323600a5942588b556f2d78c2af
persons/tests.py
persons/tests.py
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ ...
from datetime import datetime from django.test import TestCase from unittest import skip from .models import Person from mks.models import Member class PersonTests(TestCase): @skip def test_member_person_sync(self): """ Test member/person sync on member save() """ birth = d...
Test case for Member/Person sync
Test case for Member/Person sync Skipped for now, to help with #4049
Python
bsd-3-clause
navotsil/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,DanaOshri/Open-Knesset,jspan/Open-Knesset,navotsil/Open-Knesset,MeirKriheli/Open-Knesset,jspan/Open-Knesset,Shrulik/Open-Knesset,ofri/Open-Knesset,habeanf/Open-Knesset,jspan/Open-Knesset,noamelf/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Knesset,navotsi...
--- +++ @@ -1,23 +1,38 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" +from datetime import datetime from django.test import TestCase +from uni...
8377f3e61441a7f465feefba905cd3c82586e1a5
geomdl/visualization/__init__.py
geomdl/visualization/__init__.py
""" NURBS-Python Visualization Component .. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com> """
""" NURBS-Python Visualization Component .. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com> """ __author__ = "Onur Rauf Bingol" __version__ = "1.0.0" __license__ = "MIT"
Add metadata to visualization module
Add metadata to visualization module
Python
mit
orbingol/NURBS-Python,orbingol/NURBS-Python
--- +++ @@ -3,3 +3,7 @@ .. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com> """ + +__author__ = "Onur Rauf Bingol" +__version__ = "1.0.0" +__license__ = "MIT"
3358d47cc9bdad5abaa1e8a9358d49539e6256b1
scuevals_api/resources/official_user_types.py
scuevals_api/resources/official_user_types.py
from flask_jwt_extended import current_user from flask_restful import Resource from marshmallow import fields, Schema from scuevals_api.auth import auth_required from scuevals_api.models import Permission, OfficialUserType, db from scuevals_api.utils import use_args class OfficialUserTypeSchema(Schema): email = ...
from flask_jwt_extended import current_user from flask_restful import Resource from marshmallow import fields, Schema from scuevals_api.auth import auth_required from scuevals_api.models import Permission, OfficialUserType, db from scuevals_api.utils import use_args class OfficialUserTypeSchema(Schema): email = ...
Make sure official user type emails are lower case
Make sure official user type emails are lower case
Python
agpl-3.0
SCUEvals/scuevals-api,SCUEvals/scuevals-api
--- +++ @@ -23,7 +23,7 @@ for out in args['official_user_types']: db.session.merge(OfficialUserType( - email=out['email'], + email=out['email'].lower(), type=out['type'], university_id=current_user.university_id ))
2fc3ee4edc4b7a1842fca369620c790244000f11
flask_apidoc/commands.py
flask_apidoc/commands.py
# Copyright 2015 Vinicius Chiele. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
# Copyright 2015 Vinicius Chiele. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
Set static/docs as the default folder to generate the apidoc's files
Set static/docs as the default folder to generate the apidoc's files
Python
mit
viniciuschiele/flask-apidoc
--- +++ @@ -28,7 +28,7 @@ def __init__(self, input_path=None, output_path=None, template_path=None): super().__init__() self.input_path = input_path - self.output_path = output_path + self.output_path = output_path or 'static/docs' self.template_path = template_path ...
98771f6a7a96ccedf56e3619433e2451d5c3251f
exception/test1.py
exception/test1.py
#!/usr/local/bin/python class MuffledCalculator: muffled=False def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print "Can't divide zero" else: raise a=MuffledCalculator() print a.calc('2/1') #print a.calc('1/0') a.muffled=True print a....
#!/usr/local/bin/python #class MuffledCalculator: # muffled=False # def calc(self,expr): # try: # return eval(expr) # except (ZeroDivisionError,TypeError): # if self.muffled: # print "There are errors." # else: # raise #a=MuffledCalculator() #print a.calc('2/1') ##print a.calc('2/"d...
Use finally and so on.
Use finally and so on.
Python
apache-2.0
Vayne-Lover/Python
--- +++ @@ -1,16 +1,56 @@ #!/usr/local/bin/python -class MuffledCalculator: - muffled=False - def calc(self,expr): - try: - return eval(expr) - except ZeroDivisionError: - if self.muffled: - print "Can't divide zero" - else: - raise -a=MuffledCalculator() -print a.calc('2/1') +#c...
661d42468359836c0ce9ee4e267241a4aaf7a021
lot/views.py
lot/views.py
import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models ...
import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models ...
Check for an empty user
Check for an empty user
Python
bsd-3-clause
ABASystems/django-lot
--- +++ @@ -18,8 +18,11 @@ lot.delete() return HttpResponseNotFound() - user = authenticate(lot_uuid=uuid) - login(request, user) + user = authenticate(request, lot_uuid=uuid) + if user is not None: + login(request, user) + else: + r...
6fd0c91fd1bbc6ae1a8fae46503464ab63603d38
pinry/api/api.py
pinry/api/api.py
from tastypie.resources import ModelResource from tastypie import fields from tastypie.authentication import BasicAuthentication from tastypie.authorization import DjangoAuthorization from django.contrib.auth.models import User from pinry.pins.models import Pin class PinResource(ModelResource): # pylint: disable-m...
from tastypie.resources import ModelResource from tastypie import fields from tastypie.authentication import BasicAuthentication from tastypie.authorization import DjangoAuthorization from django.contrib.auth.models import User from pinry.pins.models import Pin class PinResource(ModelResource): # pylint: disable-m...
Enable filtering over the published field
Enable filtering over the published field Tastypie requires that we define a list of fields that can be used for filtering; add the "published" to this list so we can query pinry for the list of images created after some date.
Python
bsd-2-clause
lapo-luchini/pinry,supervacuo/pinry,lapo-luchini/pinry,supervacuo/pinry,wangjun/pinry,QLGu/pinry,Stackato-Apps/pinry,dotcom900825/xishi,lapo-luchini/pinry,Stackato-Apps/pinry,MSylvia/pinry,pinry/pinry,MSylvia/pinry,pinry/pinry,pinry/pinry,Stackato-Apps/pinry,dotcom900825/xishi,QLGu/pinry,wangjun/pinry,QLGu/pinry,rafiro...
--- +++ @@ -15,6 +15,9 @@ queryset = Pin.objects.all() resource_name = 'pin' include_resource_uri = False + filtering = { + 'published': ['gt'], + } def dehydrate_thumbnail(self, bundle): pin = Pin.objects.only('image').get(pk=bundle.data['id'])
e23b146f613ed6e0090b0ef1f895ee1785e56f31
plugins/brian.py
plugins/brian.py
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" with open('plugins/brian_corpus/cache.json', 'r') as infile: cache = json.load(infile) with open('plugins/brian_corpus/phrases.json', 'r') as infile: phrases = json.load(infile) def gener...
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" with open('plugins/brian_corpus/cache.json', 'r') as infile: cache = json.load(infile) with open('plugins/brian_corpus/phrases.json', 'r') as infile: phrases = json.load(infile) def gener...
Use block quotes for Markov-chain plugin
Use block quotes for Markov-chain plugin
Python
mit
kvchen/keffbot-py,kvchen/keffbot
--- +++ @@ -30,6 +30,6 @@ def on_message(bot, channel, user, message): - return generate_phrase(phrases, cache) + return '> {}'.format(generate_phrase(phrases, cache))
11a21f4ce70cbd99b9a1b369f0ca6cada9934450
storage/utils.py
storage/utils.py
import hashlib def hash256(hash_data): return hashlib.sha256(hashlib.sha256(hash_data).digest()).digest()
import hashlib def hash256(hash_data: bytes): return hashlib.sha256(hashlib.sha256(hash_data).digest()).digest()
Move hash256 to separate function
Move hash256 to separate function
Python
mpl-2.0
DvA-leopold/CrAB,DvA-leopold/CrAB
--- +++ @@ -1,5 +1,5 @@ import hashlib -def hash256(hash_data): +def hash256(hash_data: bytes): return hashlib.sha256(hashlib.sha256(hash_data).digest()).digest()
4cef3788a19b9ad7059184a39accd2b551407de4
tests/test_benchmark.py
tests/test_benchmark.py
import os from subprocess import check_call import pytest def run(command, problem, so, shape, nbpml, *extra): args = ["python", "../benchmarks/user/benchmark.py", command] args.extend(["-P", str(problem)]) args.extend(["-so", str(so)]) args.extend(["-d"] + [str(i) for i in shape]) args.extend(["...
from subprocess import check_call def run_cmd(command, problem, so, shape, nbpml, *extra): args = ["python", "../benchmarks/user/benchmark.py", command] args.extend(["-P", str(problem)]) args.extend(["-so", str(so)]) args.extend(["-d"] + [str(i) for i in shape]) args.extend(["--nbpml", str(nbpml)]...
Check bench mode==run with fixed block shape
tests: Check bench mode==run with fixed block shape
Python
mit
opesci/devito,opesci/devito
--- +++ @@ -1,10 +1,7 @@ -import os from subprocess import check_call -import pytest - -def run(command, problem, so, shape, nbpml, *extra): +def run_cmd(command, problem, so, shape, nbpml, *extra): args = ["python", "../benchmarks/user/benchmark.py", command] args.extend(["-P", str(problem)]) arg...
9a14fec9a4bb931b41ab62988975e5688f16573d
cms/tests/test_permalinks.py
cms/tests/test_permalinks.py
from django.contrib.contenttypes.models import ContentType from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from ..permalinks import expand, resolve, PermalinkError class TestPermalinkModel(models.Model): d...
from django.contrib.contenttypes.models import ContentType from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from ..permalinks import expand, resolve, PermalinkError class TestPermalinkModel(models.Model): d...
Fix permalinks test which was breaking other tests.
Fix permalinks test which was breaking other tests.
Python
bsd-3-clause
lewiscollard/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,dan-gamble/cms,lewiscollard/cms,danielsamuels/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,jamesfoley/cms,jamesfoley/cms
--- +++ @@ -32,9 +32,12 @@ # A valid URL, but not a permalink. resolve('/admin/') + original_urlconf = urlresolvers.get_urlconf() with self.assertRaises(ImproperlyConfigured): urlresolvers.set_urlconf('cms.tests.urls') resolve('/r/') + + url...
24341ee3dabcbad751c849ef8007b669bdce5141
tests/test_bountyxml.py
tests/test_bountyxml.py
from hearthstone import bountyxml def test_bountyxml_load(): bounty_db, _ = bountyxml.load() assert bounty_db assert bounty_db[47].boss_name == "Cap'n Hogger" assert bounty_db[58].region_name == "The Barrens"
from hearthstone import bountyxml def test_bountyxml_load(): bounty_db, _ = bountyxml.load() assert bounty_db assert bounty_db[68].boss_name == "The Anointed Blades" assert bounty_db[58].region_name == "The Barrens"
Fix broken Mercenaries bountyxml test
Fix broken Mercenaries bountyxml test
Python
mit
HearthSim/python-hearthstone
--- +++ @@ -6,5 +6,5 @@ assert bounty_db - assert bounty_db[47].boss_name == "Cap'n Hogger" + assert bounty_db[68].boss_name == "The Anointed Blades" assert bounty_db[58].region_name == "The Barrens"
32efe7a0365738f982030f7c5be3b702dbac87c8
tests/test.py
tests/test.py
from devicehive import Handler from devicehive import DeviceHive class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(object): ""...
from devicehive import Handler from devicehive import DeviceHive import pytest class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(o...
Add only_http_implementation and only_websocket_implementation methods
Add only_http_implementation and only_websocket_implementation methods
Python
apache-2.0
devicehive/devicehive-python
--- +++ @@ -1,5 +1,6 @@ from devicehive import Handler from devicehive import DeviceHive +import pytest class TestHandler(Handler): @@ -30,6 +31,16 @@ def websocket_transport(self): return self._transport_name == 'websocket' + def only_http_implementation(self): + if self.http_transpo...
d1a43bb960d695ce74d38e9bd95218f655f057a0
forth-like/demo.py
forth-like/demo.py
#!/usr/bin/python """ demo.py -- Experimenting with expressing this forth-like pattern in Python. It appears it can be done with varargs and splatting. """ import sys import time def retry(*args): n = args[0] f = args[1] a = args[2:] for i in range(n): f(*a) def hello_sleep(*args): print 'hello' ...
#!/usr/bin/python """ demo.py -- Experimenting with expressing this forth-like pattern in Python. It appears it can be done with varargs and splatting. """ import sys import time def retry(n, f, *args): for i in range(n): f(*args) def hello_sleep(t): print 'hello' time.sleep(t) def retry_demo(): ret...
Remove manual indexing of args
Remove manual indexing of args
Python
apache-2.0
oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code
--- +++ @@ -9,29 +9,21 @@ import time -def retry(*args): - n = args[0] - f = args[1] - a = args[2:] - +def retry(n, f, *args): for i in range(n): - f(*a) + f(*args) -def hello_sleep(*args): +def hello_sleep(t): print 'hello' - time.sleep(args[0]) + time.sleep(t) def retry_demo(): ret...
0b15611eb0020bc2cdb4a4435756315b0bd97a21
seria/cli.py
seria/cli.py
# -*- coding: utf-8 -*- import click from .compat import StringIO import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--jso...
# -*- coding: utf-8 -*- import click from .compat import StringIO, str, builtin_str import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @c...
Fix errors with 2/3 FLO support
Fix errors with 2/3 FLO support
Python
mit
rtluckie/seria
--- +++ @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import click -from .compat import StringIO +from .compat import StringIO, str, builtin_str import seria @@ -12,8 +12,8 @@ @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_f...
b2d4bf11b293073c4410ca1be98f657a30c35762
python/triple-sum.py
python/triple-sum.py
# A special triplet is defined as: a <= b <= c for # a in list_a, b in list_b, and c in list_c def get_num_special_triplets(list_a, list_b, list_c): # remove duplicates and sort lists list_a = sorted(set(list_a)) list_b = sorted(set(list_b)) list_c = sorted(set(list_c)) num_special_triplets = 0 ...
def get_num_special_triplets(list_a, list_b, list_c): a_index = 0 c_index = 0 num_special_triplets = 0 for b in list_b: while a_index < len(list_a) and list_a[a_index] <= b: a_index += 1 while c_index < len(list_c) and list_c[c_index] <= b: c_index += 1 ...
Improve time complexity of solution
Improve time complexity of solution
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
--- +++ @@ -1,33 +1,27 @@ +def get_num_special_triplets(list_a, list_b, list_c): - -# A special triplet is defined as: a <= b <= c for -# a in list_a, b in list_b, and c in list_c -def get_num_special_triplets(list_a, list_b, list_c): - # remove duplicates and sort lists - list_a = sorted(set(list_a)) - li...
74feef6094d884b0116fef895885aa47233801c1
gitdir/__init__.py
gitdir/__init__.py
import os import pathlib GITDIR = pathlib.Path(os.environ.get('GITDIR', '/opt/git')) #TODO check permissions
import os import pathlib GLOBAL_GITDIR = pathlib.Path('/opt/git') LOCAL_GITDIR = pathlib.Path.home() / 'git' if 'GITDIR' in is.environ: GITDIR = pathlib.Path(os.environ['GITDIR']) elif LOCAL_GITDIR.exists() and not GLOBAL_GITDIR.exists(): #TODO check permissions GITDIR = LOCAL_GITDIR else: GITDIR = GLOBAL...
Fix GITDIR constant to use local gitdir if global doesn't exist
Fix GITDIR constant to use local gitdir if global doesn't exist
Python
mit
fenhl/gitdir
--- +++ @@ -1,4 +1,12 @@ import os import pathlib -GITDIR = pathlib.Path(os.environ.get('GITDIR', '/opt/git')) #TODO check permissions +GLOBAL_GITDIR = pathlib.Path('/opt/git') +LOCAL_GITDIR = pathlib.Path.home() / 'git' + +if 'GITDIR' in is.environ: + GITDIR = pathlib.Path(os.environ['GITDIR']) +elif LOCAL_GI...
4947ebf9460c2cf2ba8338de92601804dec2148a
src/svg_icons/templatetags/svg_icons.py
src/svg_icons/templatetags/svg_icons.py
import json from django.core.cache import cache from django.conf import settings from django.template import Library, TemplateSyntaxError register = Library() @register.inclusion_tag('svg_icons/icon.html') def icon(name, **kwargs): """Render a SVG icon defined in a json file to our template. ..:json exampl...
import json from importlib import import_module from django.core.cache import cache from django.conf import settings from django.template import Library, TemplateSyntaxError reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader') try: module, cls = reader_class.rspli...
Use the new reader classes in the template tag
Use the new reader classes in the template tag
Python
apache-2.0
mikedingjan/django-svg-icons,mikedingjan/django-svg-icons
--- +++ @@ -1,57 +1,34 @@ import json +from importlib import import_module from django.core.cache import cache from django.conf import settings from django.template import Library, TemplateSyntaxError +reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader') + +try...
bcc40b08c59ba8fcb8efc9044c2ea6e11ed9df12
tests/api/views/users/list_test.py
tests/api/views/users/list_test.py
from tests.data import add_fixtures, users def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John Doe', ...
from tests.data import add_fixtures, users, clubs def test_list_users(db_session, client): john = users.john() add_fixtures(db_session, john) res = client.get('/users/') assert res.status_code == 200 assert res.json == { u'users': [{ u'id': john.id, u'name': u'John...
Add more "GET /users" tests
tests/api: Add more "GET /users" tests
Python
agpl-3.0
RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Harry-R/skylines,shadowoneau/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Turbo87/skylines,skylines-project/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,shadowoneau/skylines,skyline...
--- +++ @@ -1,4 +1,4 @@ -from tests.data import add_fixtures, users +from tests.data import add_fixtures, users, clubs def test_list_users(db_session, client): @@ -14,3 +14,40 @@ u'club': None, }] } + + +def test_with_club(db_session, client): + john = users.john(club=clubs.lva()) +...
e593306092292f72009e13bafe1cbb83f85d7937
indra/bel/ndex_client.py
indra/bel/ndex_client.py
import requests import json import time ndex_base_url = 'http://services.bigmech.ndexbio.org' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code if ...
import requests import json import time ndex_base_url = 'http://services.bigmech.ndexbio.org' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code if ...
Fix messages in NDEx client
Fix messages in NDEx client
Python
bsd-2-clause
jmuhlich/indra,pvtodorov/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,...
--- +++ @@ -14,7 +14,7 @@ if status == 200: return res.text task_id = res.json()['task_id'] - print 'NDEx services task submitted...' % task_id + print 'NDEx task submitted...' time_used = 0 try: while status != 200: @@ -26,5 +26,5 @@ except KeyError: next ...
e57c2cefa9e8403aa9a2f27d791604a179c8b998
quickfileopen.py
quickfileopen.py
import sublime import sublime_plugin class QuickFileOpenCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') if type(files) == list: self.window.show_quick_panel(files, self.on_don...
import sublime import sublime_plugin class QuickFileOpenCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') if type(files) == list: self.window.show_quick_panel(files, self.on_don...
Handle the case where the user exits the panel
Handle the case where the user exits the panel
Python
mit
gsingh93/sublime-quick-file-open
--- +++ @@ -14,6 +14,9 @@ sublime.error_message('The \'files\' setting must be a list') def on_done(self, selected): + if selected == -1: + return + settings = sublime.load_settings('QuickFileOpen.sublime-settings') files = settings.get('files') fileNam...
d5ad324355e0abdf0a6bdcb41e1f07224742b537
src/main.py
src/main.py
#!/usr/bin/env python3 # card-fight-thingy - Simplistic battle card game... thingy # # The MIT License (MIT) # # Copyright (c) 2015 The Underscores # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the S...
#!/usr/bin/env python3 # card-fight-thingy - Simplistic battle card game... thingy # # The MIT License (MIT) # # Copyright (c) 2015 The Underscores # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the S...
Remove needless import of sys module
Remove needless import of sys module
Python
mit
TheUnderscores/card-fight-thingy
--- +++ @@ -24,8 +24,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -import sys - import game import menu
5bdfb968d6a05fcb727866bee063f996232bf9b8
tests/matchers/test_called.py
tests/matchers/test_called.py
from unittest.case import TestCase from mock import Mock from robber import expect from robber.matchers.called import Called class TestCalled(TestCase): def test_matches(self): mock = Mock() mock() expect(Called(mock).matches()) == True def test_failure_message(self): mock =...
from unittest import TestCase from mock import Mock from robber import expect from robber.matchers.called import Called class TestCalled(TestCase): def test_matches(self): mock = Mock() mock() expect(Called(mock).matches()) == True def test_failure_message(self): mock = Mock...
Make import compatible with python 2.6
[r] Make import compatible with python 2.6
Python
mit
vesln/robber.py
--- +++ @@ -1,4 +1,4 @@ -from unittest.case import TestCase +from unittest import TestCase from mock import Mock
d3b8b948dac6ccce68ccf21311397ce6792fddc6
tests/test_modules/os_test.py
tests/test_modules/os_test.py
from subprocess import call, check_output class TestOs: """ Contains test methods to test if the vagrant OS got installed properly """
from subprocess import call, check_output class TestOs: """ Contains test methods to test if the vagrant OS got installed properly """ def uname_kernel(self): """ returns output of uname -s """ output = check_output(["uname", "-s"]).decode("utf-8").lstrip().rstrip() return out...
Add tests for vagrant guest OS
Add tests for vagrant guest OS
Python
bsd-3-clause
DevBlend/DevBlend,DevBlend/zenias,byteknacker/fcc-python-vagrant,DevBlend/DevBlend,DevBlend/zenias,DevBlend/zenias,byteknacker/fcc-python-vagrant,DevBlend/DevBlend,DevBlend/zenias,DevBlend/zenias,DevBlend/DevBlend,DevBlend/DevBlend,DevBlend/zenias,DevBlend/DevBlend
--- +++ @@ -3,4 +3,22 @@ class TestOs: """ Contains test methods to test if the vagrant OS got installed properly """ + + def uname_kernel(self): + """ returns output of uname -s """ + output = check_output(["uname", "-s"]).decode("utf-8").lstrip().rstrip() + return output + ...
83fdf3051786806486f4ff9e4b05616603f7211a
thinc/about.py
thinc/about.py
# inspired from: # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __name__ = "thinc" __version__ = "8.0.0.dev0" __summary__ = "Practical Machine Learning for NLP" __uri__ = "https://github.com/explosion/thinc"...
# inspired from: # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __name__ = "thinc" __version__ = "7.4.0.dev2" __summary__ = "Practical Machine Learning for NLP" __uri__ = "https://github.com/explosion/thinc"...
Revert "Set version to v8.0.0.dev0"
Revert "Set version to v8.0.0.dev0" This reverts commit 69732c4f9f7ff1a89b85e9c211991154dcce59f4.
Python
mit
explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc
--- +++ @@ -4,7 +4,7 @@ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __name__ = "thinc" -__version__ = "8.0.0.dev0" +__version__ = "7.4.0.dev2" __summary__ = "Practical Machine Learning for NLP" __uri__ = "https://github.com/explosion/thinc" __author__ = "Matthew Honnibal"
1126c0e795d94e004fae03edda3e299b2d3b764c
todo/models.py
todo/models.py
from django.db import models from django.utils.text import slugify from common.models import TimeStampedModel class List(TimeStampedModel): name = models.CharField(max_length=50) slug = models.CharField(max_length=50, editable=False) def __unicode__(self): return self.name def save(self, *a...
from django.contrib.auth.models import User from django.db import models from django.utils.text import slugify from common.models import DeleteSafeTimeStampedMixin class List(DeleteSafeTimeStampedMixin): name = models.CharField(max_length=50) slug = models.CharField(max_length=50, editable=False) author ...
Attach user with List and Item
Attach user with List and Item
Python
mit
ajoyoommen/zerrenda,ajoyoommen/zerrenda
--- +++ @@ -1,12 +1,14 @@ +from django.contrib.auth.models import User from django.db import models from django.utils.text import slugify -from common.models import TimeStampedModel +from common.models import DeleteSafeTimeStampedMixin -class List(TimeStampedModel): +class List(DeleteSafeTimeStampedMixin): ...
5a6a96435b7cf45cbbc5f2b81a7be84cd986b456
haas/__main__.py
haas/__main__.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. import sys # pragma: no cover from .main import main # pragma: no cover if __name__ == '__main...
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. import sys # pragma: no cover from haas.main import main # pragma: no cover if __name__ == '__...
Use absolute import for main entry point.
Use absolute import for main entry point.
Python
bsd-3-clause
itziakos/haas,sjagoe/haas,scalative/haas,sjagoe/haas,itziakos/haas,scalative/haas
--- +++ @@ -6,7 +6,7 @@ # of the 3-clause BSD license. See the LICENSE.txt file for details. import sys # pragma: no cover -from .main import main # pragma: no cover +from haas.main import main # pragma: no cover if __name__ == '__main__':
e84d6dc5be2e2ac2d95b81e4df18bc0ad939916a
__init__.py
__init__.py
import os from flask import Flask, redirect, request, render_template from flask_mail import Mail, Message app = Flask (__name__) ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg']) mail = Mail(app) @app.route("/") def index(): return render_template('in-development.html.j2') if __name__ == "__main__": a...
import os from flask import Flask, redirect, request, render_template from flask_mail import Mail, Message app = Flask (__name__) ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg']) mail = Mail(app) @app.route("/") def index(): return render_template('index.html.j2') if __name__ == "__main__": app.run()
Split into new branch for development of the main site
Split into new branch for development of the main site
Python
mit
JonathanPeterCole/Tech-Support-Site,JonathanPeterCole/Tech-Support-Site
--- +++ @@ -8,7 +8,7 @@ @app.route("/") def index(): - return render_template('in-development.html.j2') + return render_template('index.html.j2') if __name__ == "__main__": - app.run(host='0.0.0.0') + app.run()
30609236e703123c464c2e3927417ae677f37c4e
nimp/base_commands/__init__.py
nimp/base_commands/__init__.py
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use,...
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use,...
Remove run_hook from list of imported commands.
Remove run_hook from list of imported commands.
Python
mit
dontnod/nimp
--- +++ @@ -32,7 +32,6 @@ 'p4', 'package', 'run', - 'run_hook', 'symbol_server', 'update_symbol_server', 'upload',
1cff28b9612c156363ed87cdde1718ee83b65776
real_estate_agency/resale/serializers.py
real_estate_agency/resale/serializers.py
from rest_framework import serializers from .models import ResaleApartment, ResaleApartmentImage class ResaleApartmentImageSerializer(serializers.ModelSerializer): class Meta: model = ResaleApartmentImage fields = '__all__' class ResaleApartmentSerializer(serializers.ModelSerializer): # ima...
from rest_framework import serializers from .models import ResaleApartment, ResaleApartmentImage class ResaleApartmentImageSerializer(serializers.ModelSerializer): class Meta: model = ResaleApartmentImage fields = '__all__' class ResaleApartmentSerializer(serializers.ModelSerializer): # ima...
Make ResaleApartmentSerializer return Decoration.name on decoration field.
Make ResaleApartmentSerializer return Decoration.name on decoration field. It allows to show readable value at resale detailed page.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
--- +++ @@ -14,6 +14,7 @@ get_building_type_display = serializers.ReadOnlyField() price_per_square_meter = serializers.ReadOnlyField() neighbourhood = serializers.StringRelatedField() + decoration = serializers.ReadOnlyField(source='decoration.name') class Meta: model = ResaleApartme...
1e513d901dfef9135a62c8f99633b10d3900ecb8
orator/schema/mysql_builder.py
orator/schema/mysql_builder.py
# -*- coding: utf-8 -*- from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile...
# -*- coding: utf-8 -*- from .builder import SchemaBuilder class MySQLSchemaBuilder(SchemaBuilder): def has_table(self, table): """ Determine if the given table exists. :param table: The table :type table: str :rtype: bool """ sql = self._grammar.compile_...
Fix case when processing column names for MySQL
Fix case when processing column names for MySQL
Python
mit
sdispater/orator
--- +++ @@ -4,7 +4,6 @@ class MySQLSchemaBuilder(SchemaBuilder): - def has_table(self, table): """ Determine if the given table exists. @@ -33,6 +32,12 @@ database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table - result...
0a6078f5d0537cea9f36894b736fa274c3fa3e47
molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py
molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_data_file(self): file = self.cleaned_data['data_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise form...
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_zip_file(self): file = self.cleaned_data['zip_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms....
Fix upload form to only accept .zip files
Fix upload form to only accept .zip files
Python
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
--- +++ @@ -4,20 +4,11 @@ class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") - def clean_data_file(self): - file = self.cleaned_data['data_file'] + def clean_zip_file(self): + file = self.cleaned_data['zip_file'] if file: extension = ...
8a55e9fac0885c5b6eb21cd8f3da54a105de8010
sktracker/__init__.py
sktracker/__init__.py
"""Object detection and tracking for cell biology `scikit-learn` is bla bla bla. Subpackages ----------- color Color space conversion. Utility Functions ----------------- img_as_float Convert an image to floating point format, with values in [0, 1]. """ try: from .version import __version__ except Imp...
"""Object detection and tracking for cell biology `scikit-learn` is bla bla bla. Subpackages ----------- color Color space conversion. """ try: from .version import __version__ except ImportError: __version__ = "dev" import utils
Fix utils module import mechanism
Fix utils module import mechanism
Python
bsd-3-clause
bnoi/scikit-tracker,bnoi/scikit-tracker,bnoi/scikit-tracker
--- +++ @@ -7,15 +7,11 @@ color Color space conversion. - -Utility Functions ------------------ -img_as_float - Convert an image to floating point format, with values in [0, 1]. - """ try: from .version import __version__ except ImportError: __version__ = "dev" + +import utils
e92fa763729ce68e86da3664ae1a1ed37e3200a5
ynr/apps/uk_results/serializers.py
ynr/apps/uk_results/serializers.py
from __future__ import unicode_literals from rest_framework import serializers from candidates.serializers import MembershipSerializer from .models import CandidateResult, ResultSet class CandidateResultSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CandidateResult fiel...
from __future__ import unicode_literals from rest_framework import serializers from candidates.serializers import MembershipSerializer from .models import CandidateResult, ResultSet class CandidateResultSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CandidateResult fiel...
Add ballot paper ID to API
Add ballot paper ID to API
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
--- +++ @@ -25,14 +25,19 @@ class Meta: model = ResultSet fields = ( - 'id', 'url', + 'id', + 'url', 'candidate_results', 'ip_address', - 'num_turnout_reported', 'num_spoilt_ballots', - # 'post_result', - ...
3c8b3a24978cf757fb3a8cc8660eb4554f183e0f
social_auth/fields.py
social_auth/fields.py
from django.core.exceptions import ValidationError from django.db import models from django.utils import simplejson class JSONField(models.TextField): """Simple JSON field that stores python structures as JSON strings on database. """ __metaclass__ = models.SubfieldBase def to_python(self, value...
from django.core.exceptions import ValidationError from django.db import models from django.utils import simplejson class JSONField(models.TextField): """Simple JSON field that stores python structures as JSON strings on database. """ __metaclass__ = models.SubfieldBase def to_python(self, value...
Use get_db_prep_value instead of get_db_prep_save. Closes gh-42
Use get_db_prep_value instead of get_db_prep_save. Closes gh-42
Python
bsd-3-clause
WW-Digital/django-social-auth,1st/django-social-auth,vxvinh1511/django-social-auth,limdauto/django-social-auth,michael-borisov/django-social-auth,caktus/django-social-auth,thesealion/django-social-auth,lovehhf/django-social-auth,dongguangming/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,du...
--- +++ @@ -34,10 +34,9 @@ except Exception, e: raise ValidationError(str(e)) - def get_db_prep_save(self, value): + def get_db_prep_value(self, value, connection, prepared=False): """Convert value to JSON string before save""" try: - value = simplejson.dumps...
49b3fe4e334e25c6afaa9ccace72f5c985e761cb
wcontrol/src/models.py
wcontrol/src/models.py
from app import db from flask_login import UserMixin class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) name = db.Column(db.String(64), index=True) email = db.Column(db.String(64), index=...
from app import db from flask_login import UserMixin class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) name = db.Column(db.String(64), index=True) email = db.Column(db.String(64), index...
Modify to fit with PEP8 standard
Modify to fit with PEP8 standard
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
--- +++ @@ -1,5 +1,6 @@ from app import db from flask_login import UserMixin + class User(UserMixin, db.Model): __tablename__ = 'users' @@ -28,9 +29,9 @@ def get_id(self): try: - return unicode(self.id) # python2 + return unicode(self.id) except NameError: - ...
b54a6353a746d54869a7cadca1bdcfb1e1cd3d51
moviemanager/models.py
moviemanager/models.py
from django.db import models class Movie(models.Model): tmdb_id = models.IntegerField()
from django.contrib.auth.models import User from django.db import models class Movie(models.Model): tmdb_id = models.IntegerField() score = models.IntegerField() submitter = models.ForeignKey(User)
Add some extra fields to movie model
Add some extra fields to movie model
Python
mit
simon-andrews/movieman2,simon-andrews/movieman2
--- +++ @@ -1,5 +1,8 @@ +from django.contrib.auth.models import User from django.db import models class Movie(models.Model): tmdb_id = models.IntegerField() + score = models.IntegerField() + submitter = models.ForeignKey(User)
43b077050cd0e914fbe7398f9077e787c496afe4
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django_pandas', 'django_pandas.tests', ), DATABASES={ ...
#!/usr/bin/env python import os import sys import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django_pandas', 'django_pandas.tests', ), DATABASES={ ...
Add support for django 1.8 by using test runner
Add support for django 1.8 by using test runner
Python
bsd-3-clause
sternb0t/django-pandas,perpetua1/django-pandas,arcticshores/django-pandas,chrisdev/django-pandas
--- +++ @@ -34,15 +34,22 @@ def runtests(*test_args): if not test_args: - test_args = ['tests'] + test_args = ['django_pandas'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) - from django.test.simple import DjangoTestSuiteRunner - failures = D...
894086bda2545fc7d094def6f925b96905920992
isso/utils/http.py
isso/utils/http.py
# -*- encoding: utf-8 -*- import socket try: import httplib except ImportError: import http.client as httplib from isso.wsgi import urlsplit class curl(object): """Easy to use wrapper around :module:`httplib`. Use as context-manager so we can close the response properly. .. code-block:: pytho...
# -*- encoding: utf-8 -*- import socket try: import httplib except ImportError: import http.client as httplib from isso.wsgi import urlsplit class curl(object): """Easy to use wrapper around :module:`httplib`. Use as context-manager so we can close the response properly. .. code-block:: pytho...
Fix catch socket timeout and error exceptions
Fix catch socket timeout and error exceptions
Python
mit
jiumx60rus/isso,janusnic/isso,WQuanfeng/isso,mathstuf/isso,janusnic/isso,Mushiyo/isso,posativ/isso,xuhdev/isso,jelmer/isso,princesuke/isso,mathstuf/isso,princesuke/isso,WQuanfeng/isso,jelmer/isso,jelmer/isso,xuhdev/isso,posativ/isso,Mushiyo/isso,jelmer/isso,xuhdev/isso,princesuke/isso,posativ/isso,jiumx60rus/isso,maths...
--- +++ @@ -39,7 +39,10 @@ except (httplib.HTTPException, socket.error): return None - return self.con.getresponse() + try: + return self.con.getresponse() + except (socket.timeout, socket.error): + return None def __exit__(self, exc_type, exc_...
6913ef43184eda1166541b2c59e0a82c3981d643
spreadflow_pdf/test/test_savepdfpages.py
spreadflow_pdf/test/test_savepdfpages.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import copy from twisted.internet import defer from mock import Mock from testtools import ExpectedException, TestCase, run_test_with from testtools.twistedsupport import AsynchronousDeferredRunTest from s...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import copy import pdfrw from twisted.internet import defer from mock import Mock, patch, mock_open, call from testtools import ExpectedException, TestCase, run_test_with from testtools.twistedsupport impor...
Add test coverage for save pages (happy path)
Add test coverage for save pages (happy path)
Python
mit
znerol/spreadflow-pdf
--- +++ @@ -3,10 +3,11 @@ from __future__ import unicode_literals import copy +import pdfrw from twisted.internet import defer -from mock import Mock +from mock import Mock, patch, mock_open, call from testtools import ExpectedException, TestCase, run_test_with from testtools.twistedsupport import Asynchro...
0eb20c8025a838d93a5854442640550d5bf05b0b
settings.py
settings.py
#!/usr/bin/env python """settings.py Udacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8m...
#!/usr/bin/env python """settings.py Udacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8m...
Add android and ios client IDs
Add android and ios client IDs
Python
apache-2.0
elbernante/conference-central,elbernante/conference-central,elbernante/conference-central
--- +++ @@ -13,6 +13,6 @@ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' -ANDROID_CLIENT_ID = 'replace with Android client ID' -IOS_CLIENT_ID = 'replace with iOS client ID' +...
0b56e5d8b1da9c5b76a39cead7f4642384750c0a
utils/http.py
utils/http.py
# Universal Subtitles, universalsubtitles.org # # Copyright (C) 2012 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, ...
# Universal Subtitles, universalsubtitles.org # # Copyright (C) 2012 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, ...
Remove the unnecessary and never-used basic auth hack.
Remove the unnecessary and never-used basic auth hack.
Python
agpl-3.0
ReachingOut/unisubs,ofer43211/unisubs,ReachingOut/unisubs,ujdhesa/unisubs,eloquence/unisubs,pculture/unisubs,ujdhesa/unisubs,wevoice/wesub,ReachingOut/unisubs,wevoice/wesub,pculture/unisubs,eloquence/unisubs,norayr/unisubs,norayr/unisubs,eloquence/unisubs,pculture/unisubs,wevoice/wesub,ReachingOut/unisubs,pculture/unis...
--- +++ @@ -17,26 +17,15 @@ # http://www.gnu.org/licenses/agpl-3.0.html. import requests -from django.conf import settings - - -AUTH = getattr(settings, 'BASIC_AUTH_DOMAINS', None) def url_exists(url): """Check that a url (when following redirection) exists. - This is needed because Django's validato...
5dc69c3e88ab4df897c9a1d632a47de42e5bc9c0
app.py
app.py
"""Module containing factory function for the application""" from flask import Flask, redirect from flask_restplus import Api from config import app_config from api_v1 import Blueprint_apiV1 from api_v1.models import db Api_V1 = Api( app=Blueprint_apiV1, title="Shopping List Api", description="An API for...
"""Module containing factory function for the application""" from flask import Flask, redirect from flask_restplus import Api from flask_cors import CORS from config import app_config from api_v1 import Blueprint_apiV1 from api_v1.models import db Api_V1 = Api( app=Blueprint_apiV1, title="Shopping List Api",...
Enable Cross Origin Resource Sharing
[Update] Enable Cross Origin Resource Sharing
Python
mit
machariamarigi/shopping_list_api
--- +++ @@ -1,6 +1,7 @@ """Module containing factory function for the application""" from flask import Flask, redirect from flask_restplus import Api +from flask_cors import CORS from config import app_config from api_v1 import Blueprint_apiV1 @@ -20,6 +21,7 @@ app = Flask(__name__) app.config.from_o...
2adc021a520baa356c46ad1316893c1cd96f3147
knights/lexer.py
knights/lexer.py
from enum import Enum import re Token = Enum('Token', 'load comment text var block',) tag_re = re.compile( '|'.join([ r'{\!\s*(?P<load>.+?)\s*\!}', r'{%\s*(?P<tag>.+?)\s*%}', r'{{\s*(?P<var>.+?)\s*}}', r'{#\s*(?P<comment>.+?)\s*#}' ]), re.DOTALL ) def tokenise(template): ...
from enum import Enum import re TokenType = Enum('Token', 'load comment text var block',) tag_re = re.compile( '|'.join([ r'{\!\s*(?P<load>.+?)\s*\!}', r'{%\s*(?P<tag>.+?)\s*%}', r'{{\s*(?P<var>.+?)\s*}}', r'{#\s*(?P<comment>.+?)\s*#}' ]), re.DOTALL ) class Token: de...
Rework Lexer to use Token object
Rework Lexer to use Token object
Python
mit
funkybob/knights-templater,funkybob/knights-templater
--- +++ @@ -1,7 +1,8 @@ from enum import Enum import re -Token = Enum('Token', 'load comment text var block',) +TokenType = Enum('Token', 'load comment text var block',) + tag_re = re.compile( '|'.join([ @@ -14,23 +15,31 @@ ) +class Token: + def __init__(self, mode, token, lineno=None): + s...
890860f89e353e6afb45dec06e3617f0f70e1ad7
examples/basic_datalogger.py
examples/basic_datalogger.py
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscil...
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscil...
Remove time.sleep from example, no longer required
Datalogger: Remove time.sleep from example, no longer required
Python
mit
liquidinstruments/pymoku,benizl/pymoku
--- +++ @@ -16,7 +16,6 @@ i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() - time.sleep(0.8) i.datalogger_stop() i.datalogger_start(start=0, duration=10, use_sd=True, ch1=True, ch2=True, filetype='bin')
5bb6e416cf7c59b7a5f85b1b0b037df7667d5d88
staticbuilder/conf.py
staticbuilder/conf.py
from appconf import AppConf class StaticBuilderConf(AppConf): BUILD_COMMANDS = [] COLLECT_BUILT = True INCLUDE_FILES = ['*.css', '*.js'] class Meta: required = [ 'BUILT_ROOT', ]
from appconf import AppConf class StaticBuilderConf(AppConf): BUILD_COMMANDS = [] COLLECT_BUILT = True INCLUDE_FILES = ['*'] class Meta: required = [ 'BUILT_ROOT', ]
Include all static files in build by default
Include all static files in build by default
Python
mit
hzdg/django-ecstatic,hzdg/django-staticbuilder
--- +++ @@ -4,7 +4,7 @@ class StaticBuilderConf(AppConf): BUILD_COMMANDS = [] COLLECT_BUILT = True - INCLUDE_FILES = ['*.css', '*.js'] + INCLUDE_FILES = ['*'] class Meta: required = [
a97b557146edfb340ad83fd95838dc2a627ce32f
src/urls.py
src/urls.py
__author__ = "Individual contributors (see AUTHORS file)" __date__ = "$DATE$" __rev__ = "$REV$" __license__ = "AGPL v.3" __copyright__ = """ This file is part of ArgCache. Copyright (c) 2015 by the individual contributors (see AUTHORS file) This program is free software: you can redistribute it and/...
__author__ = "Individual contributors (see AUTHORS file)" __date__ = "$DATE$" __rev__ = "$REV$" __license__ = "AGPL v.3" __copyright__ = """ This file is part of ArgCache. Copyright (c) 2015 by the individual contributors (see AUTHORS file) This program is free software: you can redistribute it and/...
Fix urlconf to avoid string view arguments to url()
Fix urlconf to avoid string view arguments to url()
Python
agpl-3.0
luac/django-argcache,luac/django-argcache
--- +++ @@ -22,9 +22,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. """ -from django.conf.urls import * +from django.conf.urls import url + +from .views import view_all, flush urlpatterns = [ - url(r'^view_all/?$', 'argcache.views.view_all', name='view_all'), - url(r'^flush/(...
1ea6a0b43e4b05bdb743b0e2be86174062581d03
errors.py
errors.py
class Errors: '''enum-like values to use as exit codes''' USAGE_ERROR = 1 DEPENDENCY_NOT_FOUND = 2 VERSION_ERROR = 3 GIT_CONFIG_ERROR = 4 STRANGE_ENVIRONMENT = 5 EATING_WITH_STAGED_CHANGES = 6 BAD_GIT_DIRECTORY = 7 BRANCH_EXISTS_ON_INIT = 8 NO_SUCH_BRANCH = 9 REPOSITORY_NOT_I...
class Errors: '''enum-like values to use as exit codes''' USAGE_ERROR = 1 DEPENDENCY_NOT_FOUND = 2 VERSION_ERROR = 3 GIT_CONFIG_ERROR = 4 STRANGE_ENVIRONMENT = 5 EATING_WITH_STAGED_CHANGES = 6 BAD_GIT_DIRECTORY = 7 BRANCH_EXISTS_ON_INIT = 8 NO_SUCH_BRANCH = 9 REPOSITORY_NOT_I...
Add a new error code
Add a new error code
Python
lgpl-2.1
mhl/gib,mhl/gib
--- +++ @@ -14,3 +14,4 @@ FINDING_HEAD = 12 BAD_TREE = 13 GIT_DIRECTORY_MISSING = 14 + DIRECTORY_TO_BACKUP_MISSING = 15
c29f55196f97ef3fa70124628fd94c78b90162ea
python/getmonotime.py
python/getmonotime.py
import getopt, sys if __name__ == '__main__': sippy_path = None try: opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b') except getopt.GetoptError: usage() for o, a in opts: if o == '-S': sippy_path = a.strip() continue if sippy_path != None: ...
import getopt, sys if __name__ == '__main__': sippy_path = None try: opts, args = getopt.getopt(sys.argv[1:], 'rS:') except getopt.GetoptError: usage() out_realtime = False for o, a in opts: if o == '-S': sippy_path = a.strip() continue if o...
Add an option to output both realtime and monotime.
Add an option to output both realtime and monotime.
Python
bsd-2-clause
synety-jdebp/rtpproxy,dsanders11/rtpproxy,synety-jdebp/rtpproxy,jevonearth/rtpproxy,jevonearth/rtpproxy,synety-jdebp/rtpproxy,sippy/rtpproxy,dsanders11/rtpproxy,jevonearth/rtpproxy,jevonearth/rtpproxy,dsanders11/rtpproxy,sippy/rtpproxy,synety-jdebp/rtpproxy,sippy/rtpproxy
--- +++ @@ -4,18 +4,24 @@ sippy_path = None try: - opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b') + opts, args = getopt.getopt(sys.argv[1:], 'rS:') except getopt.GetoptError: usage() + out_realtime = False for o, a in opts: if o == '-S': s...
75dbd6cea16b6d8c59ae3f26691a22419f2a8269
winthrop/books/views.py
winthrop/books/views.py
from dal import autocomplete from .models import Publisher class PublisherAutocomplete(autocomplete.Select2QuerySetView): # basic publisher autocomplete lookup, based on # django-autocomplete-light tutorial # restricted to staff only in url config def get_queryset(self): return Publisher.obj...
from dal import autocomplete from .models import Publisher class PublisherAutocomplete(autocomplete.Select2QuerySetView): # basic publisher autocomplete lookup, based on # django-autocomplete-light tutorial # restricted to staff only in url config def get_queryset(self): return Publisher.obj...
Fix publisher autocomplete so searches is case-insensitive
Fix publisher autocomplete so searches is case-insensitive
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
--- +++ @@ -9,4 +9,4 @@ # restricted to staff only in url config def get_queryset(self): - return Publisher.objects.filter(name__contains=self.q) + return Publisher.objects.filter(name__icontains=self.q)
ca2789ad15cba31449e4946494122ab271a83c92
inspirationforge/settings/production.py
inspirationforge/settings/production.py
from .base import * DEBUG = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ # TODO: Add MEDIA_ROOT setting. #MEDIA_ROOT = get_secret("MEDIA_ROOT") # Security-related settings ALLOWED_HOSTS = ["*"] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'...
from .base import * DEBUG = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Security-related settings ALLOWED_HOSTS = ["*"] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_COOKIE_HTTPONLY = T...
Set MEDIA_ROOT setting for Production.
Set MEDIA_ROOT setting for Production.
Python
mit
FarmCodeGary/InspirationForge,FarmCodeGary/InspirationForge,FarmCodeGary/InspirationForge
--- +++ @@ -5,8 +5,7 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ -# TODO: Add MEDIA_ROOT setting. -#MEDIA_ROOT = get_secret("MEDIA_ROOT") +MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Security-related settings ALLOWED_HOSTS = ["*"]
3f2ab5710fb07a78c5b7f67afb785e9aab5e7695
evergreen/core/threadpool.py
evergreen/core/threadpool.py
# # This file is part of Evergreen. See the NOTICE for more information. # import pyuv import sys from evergreen.event import Event from evergreen.futures import Future __all__ = ('ThreadPool') """Internal thread pool which uses the pyuv work queuing capability. This module is for internal use of Evergreen. """ c...
# # This file is part of Evergreen. See the NOTICE for more information. # import pyuv import sys from evergreen.event import Event from evergreen.futures import Future __all__ = ('ThreadPool') """Internal thread pool which uses the pyuv work queuing capability. This module is for internal use of Evergreen. """ c...
Break potential cycle because we are storing the traceback
Break potential cycle because we are storing the traceback
Python
mit
saghul/evergreen,saghul/evergreen
--- +++ @@ -30,6 +30,7 @@ self.result = self.func(*self.args, **self.kwargs) except BaseException: self.exc = sys.exc_info() + self = None class ThreadPool(object):
56cdcde184b613dabdcc3f999b90915f75e03726
tests/backends/__init__.py
tests/backends/__init__.py
from mopidy.models import Track class BaseCurrentPlaylistControllerTest(object): uris = [] backend_class = None def setUp(self): self.backend = self.backend_class() def test_add(self): playlist = self.backend.current_playlist for uri in self.uris: playlist.add(uri...
from mopidy.models import Track class BaseCurrentPlaylistControllerTest(object): uris = [] backend_class = None def setUp(self): self.backend = self.backend_class() def test_add(self): playlist = self.backend.current_playlist for uri in self.uris: playlist.add(uri...
Update test to check basic case for playback without current track
Update test to check basic case for playback without current track
Python
apache-2.0
hkariti/mopidy,mopidy/mopidy,abarisain/mopidy,quartz55/mopidy,ZenithDK/mopidy,quartz55/mopidy,priestd09/mopidy,diandiankan/mopidy,dbrgn/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,adamcik/mopidy,rawdlite/mopidy,liamw9534/mopidy,pacificIT/mopidy,jcass77/mopidy,bencevans/mopidy,mokieyue/mopidy,swak/mopidy,bacontext/mopi...
--- +++ @@ -29,14 +29,15 @@ def setUp(self): self.backend = self.backend_class() - def test_play(self): + def test_play_with_no_current_track(self): playback = self.backend.playback self.assertEqual(playback.state, playback.STOPPED) - playback.play() + result ...
7ebda7fca01372ae49a8c66812c958fc8200f4b0
apps/events/filters.py
apps/events/filters.py
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return su...
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return su...
Change Django field filter kwarg from name to field_name for Django 2 support
Change Django field filter kwarg from name to field_name for Django 2 support
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -12,11 +12,11 @@ class EventDateFilter(django_filters.FilterSet): - event_start__gte = django_filters.DateTimeFilter(name='event_start', lookup_expr='gte') - event_start__lte = django_filters.DateTimeFilter(name='event_start', lookup_expr='lte') - event_end__gte = django_filters.DateTimeFilte...
d6a1e13ed6fc1db1d2087ba56fc9130f9ab641f9
tests/__init__.py
tests/__init__.py
from __future__ import unicode_literals import os import sys def path_to_data_dir(name): if not isinstance(name, bytes): name = name.encode(sys.getfilesystemencoding()) path = os.path.dirname(__file__) path = os.path.join(path, b'data') path = os.path.abspath(path) return os.path.join(pat...
from __future__ import unicode_literals import os def path_to_data_dir(name): if not isinstance(name, bytes): name = name.encode('utf-8') path = os.path.dirname(__file__) path = os.path.join(path, b'data') path = os.path.abspath(path) return os.path.join(path, name) class IsA(object): ...
Use utf-8 when encoding our test data paths to bytes
tests: Use utf-8 when encoding our test data paths to bytes
Python
apache-2.0
rawdlite/mopidy,jcass77/mopidy,SuperStarPL/mopidy,jcass77/mopidy,bencevans/mopidy,jmarsik/mopidy,vrs01/mopidy,jcass77/mopidy,ali/mopidy,pacificIT/mopidy,tkem/mopidy,jodal/mopidy,diandiankan/mopidy,tkem/mopidy,adamcik/mopidy,vrs01/mopidy,mokieyue/mopidy,adamcik/mopidy,bencevans/mopidy,swak/mopidy,swak/mopidy,ali/mopidy,...
--- +++ @@ -1,12 +1,11 @@ from __future__ import unicode_literals import os -import sys def path_to_data_dir(name): if not isinstance(name, bytes): - name = name.encode(sys.getfilesystemencoding()) + name = name.encode('utf-8') path = os.path.dirname(__file__) path = os.path.join...
fbd99212c7af806137f996ac3c1d6c018f9402a7
puffin/core/compose.py
puffin/core/compose.py
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(ma...
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(ma...
Add Let's Encrypt env var
Add Let's Encrypt env var
Python
agpl-3.0
puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin,loomchild/puffin,loomchild/jenca-puffin
--- +++ @@ -22,7 +22,8 @@ args += arguments domain = get_application_domain(user, application) - env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) + env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, + LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(...
abfc91a687b33dda2659025af254bc9f50c077b5
publishers/migrations/0008_fix_name_indices.py
publishers/migrations/0008_fix_name_indices.py
# Generated by Django 2.1.7 on 2019-05-12 16:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('publishers', '0007_publisher_romeo_parent_id'), ] operations = [ migrations.AlterField( model_name='journal', name='...
# Generated by Django 2.1.7 on 2019-05-12 16:08 from django.db import migrations, models class Migration(migrations.Migration): atomic = False dependencies = [ ('publishers', '0007_publisher_romeo_parent_id'), ] operations = [ migrations.AlterField( model_name='journal',...
Mark index migration as non atomic
Mark index migration as non atomic
Python
agpl-3.0
dissemin/dissemin,wetneb/dissemin,wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin
--- +++ @@ -4,6 +4,7 @@ class Migration(migrations.Migration): + atomic = False dependencies = [ ('publishers', '0007_publisher_romeo_parent_id'), @@ -26,7 +27,7 @@ """, reverse_sql=""" DROP INDEX CONCURRENTLY papers_journal_title_upper; - """ ...
95c7037a4a1e9c3921c3b4584046824ed469ae7f
osfclient/tests/test_session.py
osfclient/tests/test_session.py
from osfclient.models import OSFSession def test_basic_auth(): session = OSFSession() session.basic_auth('joe@example.com', 'secret_password') assert session.auth == ('joe@example.com', 'secret_password') assert 'Authorization' not in session.headers def test_basic_build_url(): session = OSFSess...
from unittest.mock import patch from unittest.mock import MagicMock import pytest from osfclient.models import OSFSession from osfclient.exceptions import UnauthorizedException def test_basic_auth(): session = OSFSession() session.basic_auth('joe@example.com', 'secret_password') assert session.auth == (...
Add test for osfclient's session object
Add test for osfclient's session object Check that exceptions are raised on unauthed HTTP put/get
Python
bsd-3-clause
betatim/osf-cli,betatim/osf-cli
--- +++ @@ -1,4 +1,10 @@ +from unittest.mock import patch +from unittest.mock import MagicMock + +import pytest + from osfclient.models import OSFSession +from osfclient.exceptions import UnauthorizedException def test_basic_auth(): @@ -13,3 +19,71 @@ url = session.build_url("some", "path") assert url...
8febff1065c67db1599f6b9bccd27f843981dd95
main/management/commands/poll_rss.py
main/management/commands/poll_rss.py
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url i...
from datetime import datetime from time import mktime from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from mezzanine.generic.models import Rating from ...models import Link...
Add an initial rating to new links in the rss seeder.
Add an initial rating to new links in the rss seeder.
Python
bsd-2-clause
tsybulevskij/drum,j00bar/drum,j00bar/drum,yodermk/drum,skybluejamie/wikipeace,yodermk/drum,renyi/drum,sing1ee/drum,yodermk/drum,renyi/drum,tsybulevskij/drum,stephenmcd/drum,sing1ee/drum,j00bar/drum,stephenmcd/drum,abendig/drum,tsybulevskij/drum,renyi/drum,skybluejamie/wikipeace,abendig/drum,sing1ee/drum,abendig/drum
--- +++ @@ -2,9 +2,12 @@ from datetime import datetime from time import mktime +from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse + +from mezzanine.generic.models import...
9499721aa6a3ae6c01b94594f6a9e595560c2c7e
geocoder/opencage_reverse.py
geocoder/opencage_reverse.py
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.opencage import OpenCageResult, OpenCageQuery from geocoder.location import Location class OpenCageReverseResult(OpenCageResult): @property def ok(self): return bool(self.address) class OpenCageR...
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.opencage import OpenCageResult, OpenCageQuery from geocoder.location import Location class OpenCageReverseResult(OpenCageResult): @property def ok(self): return bool(self.address) class OpenCageR...
Fix opencage reverse issue where it was using self.lcoation instead of just location
Fix opencage reverse issue where it was using self.lcoation instead of just location
Python
mit
DenisCarriere/geocoder
--- +++ @@ -39,7 +39,7 @@ def _build_params(self, location, provider_key, **kwargs): location = Location(location) return { - 'query': self.location, + 'query': location, 'key': provider_key, }
a3d404a7f7352fd85a821b445ebeb8d7ca9b21c9
sigma_core/serializers/group.py
sigma_core/serializers/group.py
from rest_framework import serializers from sigma_core.models.group import Group class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group
from rest_framework import serializers from sigma_core.models.group import Group class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group visibility = serializers.SerializerMethodField() membership_policy = serializers.SerializerMethodField() validation_policy = seri...
Change GroupSerializer to display attributes as strings
Change GroupSerializer to display attributes as strings
Python
agpl-3.0
ProjetSigma/backend,ProjetSigma/backend
--- +++ @@ -6,3 +6,20 @@ class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group + + visibility = serializers.SerializerMethodField() + membership_policy = serializers.SerializerMethodField() + validation_policy = serializers.SerializerMethodField() + type = serial...
ab25537b67b14a8574028280c1e16637faa8037c
gunicorn/workers/gtornado.py
gunicorn/workers/gtornado.py
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import os import sys from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn import __version__...
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import os import sys import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn...
Fix assumption that tornado.web was imported.
Fix assumption that tornado.web was imported.
Python
mit
mvaled/gunicorn,wong2/gunicorn,prezi/gunicorn,elelianghh/gunicorn,wong2/gunicorn,WSDC-NITWarangal/gunicorn,MrKiven/gunicorn,mvaled/gunicorn,alex/gunicorn,1stvamp/gunicorn,z-fork/gunicorn,1stvamp/gunicorn,ephes/gunicorn,prezi/gunicorn,gtrdotmcs/gunicorn,tejasmanohar/gunicorn,urbaniak/gunicorn,gtrdotmcs/gunicorn,prezi/gu...
--- +++ @@ -6,6 +6,7 @@ import os import sys +import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback
dd5774c30f950c8a52b977a5529300e8edce4bc7
migrations/versions/2c240cb3edd1_.py
migrations/versions/2c240cb3edd1_.py
"""Add movie metadata (imdb rating, number of votes, metascore) and relevancy Revision ID: 2c240cb3edd1 Revises: 588336e02ca Create Date: 2014-02-09 13:46:18.630000 """ # revision identifiers, used by Alembic. revision = '2c240cb3edd1' down_revision = '588336e02ca' from alembic import op import sqlalchemy as sa d...
"""Add movie metadata (imdb rating, number of votes, metascore) and relevancy Revision ID: 2c240cb3edd1 Revises: 588336e02ca Create Date: 2014-02-09 13:46:18.630000 """ # revision identifiers, used by Alembic. revision = '2c240cb3edd1' down_revision = '588336e02ca' from alembic import op import sqlalchemy as sa d...
Fix proper default values for metadata migration
Fix proper default values for metadata migration
Python
mit
streamr/marvin,streamr/marvin,streamr/marvin
--- +++ @@ -16,10 +16,10 @@ def upgrade(): ### commands auto generated by Alembic - please adjust! ### - op.add_column('movie', sa.Column('imdb_rating', sa.Float(), nullable=False, default=0)) - op.add_column('movie', sa.Column('metascore', sa.Integer(), nullable=False, default=0)) - op.add_column('m...