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 |
|---|---|---|---|---|---|---|---|---|---|---|
c88efde14ea79419a69a3459b5ba9ba19332fffd | python/algorithms/sorting/quicksort.py | python/algorithms/sorting/quicksort.py | import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
c... | import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
c... | Move redundant check to first point of contact | Move redundant check to first point of contact
| Python | mit | vilisimo/ads,vilisimo/ads | ---
+++
@@ -27,6 +27,9 @@
def quicksort(items):
""" In-place quicksort with random pivot """
+ if len(items) < 2:
+ return
+
if items is None:
raise TypeError("Collection cannot be of type None")
@@ -35,9 +38,6 @@
def _quicksort(items, first, last):
if first >= last:
- ... |
c90a934366d81e759094f94469774abcf2e8f098 | qllr/blueprints/submission/__init__.py | qllr/blueprints/submission/__init__.py | # -*- coding: utf-8 -*-
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from qllr.app import App
from qllr.settings import RUN_POST_PROCESS
from qllr.submission import submit_match # TODO: перенеси в этот блупринт
bp = App()
bp.json_... | # -*- coding: utf-8 -*-
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from qllr.app import App
from qllr.settings import RUN_POST_PROCESS
from qllr.submission import submit_match # TODO: перенеси в этот блупринт
bp = App()
bp.json_... | Remove result checking in http_stats_submit, as submit_match raises exception on fail | Remove result checking in http_stats_submit, as submit_match raises exception on fail
| Python | agpl-3.0 | em92/quakelive-local-ratings,em92/pickup-rating,em92/quakelive-local-ratings,em92/pickup-rating,em92/quakelive-local-ratings,em92/quakelive-local-ratings,em92/pickup-rating,em92/quakelive-local-ratings | ---
+++
@@ -28,10 +28,7 @@
match_report = await request.body()
result = await submit_match(match_report.decode("utf-8"))
- if result["ok"] == False:
- raise HTTPException(422, result["message"])
- else:
- if RUN_POST_PROCESS is False:
- raise HTTPException(202, result["messa... |
f9c654a60501ef734de178e7e2e7e89955eb39e0 | jesusmtnez/python/koans/koans/about_list_assignments.py | jesusmtnez/python/koans/koans/about_list_assignments.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(__, names)
def test_parallel_assignments(self):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assi... | Complete 'About Lists Assignments' koans | [Python] Complete 'About Lists Assignments' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge | ---
+++
@@ -10,28 +10,27 @@
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
- self.assertEqual(__, names)
+ self.assertEqual(["John", "Smith"], names)
def test_parallel_assignments(self):
first_name, last_name = ["John", ... |
7d1c3ca61fb11aae181fb15d4ab825dfe9c2e710 | runtime/__init__.py | runtime/__init__.py | import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, ... | import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, ... | Add support for ... (`Ellipsis`). | Add support for ... (`Ellipsis`).
Note that it is still considered an operator, so stuff like `a ... b` means "call ... with a and b".
| Python | mit | pyos/dg | ---
+++
@@ -42,4 +42,5 @@
, 'import': importlib.import_module
, 'foldl': functools.reduce
, '~:': functools.partial
+ , '...': Ellipsis
}) |
ad16e07cce92c0ed23e5e82c60a00f04dabce2a3 | rna-transcription/rna_transcription.py | rna-transcription/rna_transcription.py | DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
| TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"... | Add an exception based version | Add an exception based version
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,9 +1,20 @@
-DNA = {"A", "C", "T", "G"}
-
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
+ try:
+ return "".join([TRANS[n] for n in dna])
+ except KeyError:
+ return ""
+
+
+# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
+
... |
81aa35961ba9552701eecbdb4d8e91448835aba0 | django_autologin/utils.py | django_autologin/utils.py | import urllib
import urlparse
from . import app_settings
def strip_token(url):
bits = urlparse.urlparse(url)
original_query = urlparse.parse_qsl(bits.query)
query = {}
for k, v in original_query:
if k != app_settings.KEY:
query[k] = v
query = urllib.urlencode(query)
retu... | import urllib
import urlparse
from django.conf import settings
from django.contrib import auth
from . import app_settings
def strip_token(url):
bits = urlparse.urlparse(url)
original_query = urlparse.parse_qsl(bits.query)
query = {}
for k, v in original_query:
if k != app_settings.KEY:
... | Make login a utility so it can be re-used elsewhere. | Make login a utility so it can be re-used elsewhere.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
| Python | bsd-3-clause | playfire/django-autologin | ---
+++
@@ -1,5 +1,8 @@
import urllib
import urlparse
+
+from django.conf import settings
+from django.contrib import auth
from . import app_settings
@@ -17,3 +20,7 @@
return urlparse.urlunparse(
(bits[0], bits[1], bits[2], bits[3], query, bits[5]),
)
+
+def login(request, user):
+ user.b... |
ac30d4e6434c6c8bbcb949465a3e314088b3fc12 | jsonfield/utils.py | jsonfield/utils.py | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.... | import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder,... | Revert changes: freezegun has been updated. | Revert changes: freezegun has been updated.
| Python | bsd-3-clause | SideStudios/django-jsonfield | ---
+++
@@ -3,21 +3,9 @@
from django.core.serializers.json import DjangoJSONEncoder
-DATETIME = (datetime.datetime,)
-DATE = (datetime.date,)
-TIME = (datetime.time,)
-
-try:
- import freezegun.api
-except ImportError:
- pass
-else:
- DATETIME += (freezegun.api.FakeDatetime,)
- DATE += (freezegun.api... |
a0c0499c3da95e53e99d6386f7970079a2669141 | app/twitter/views.py | app/twitter/views.py | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeo... | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeout... | Add exception handling in twitter view | Add exception handling in twitter view
| Python | mit | griimick/feature-mlsite,griimick/feature-mlsite,griimick/feature-mlsite | ---
+++
@@ -2,7 +2,6 @@
from ..load import processing_results, api
import string
import tweepy
-
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
@@ -10,24 +9,26 @@
ascii_chars.remove(' ')
ascii_chars.add('...')
-
def takeout_non_ascii(s):
return list... |
d26b2fd19b048d3720d757ba850d88b683d4b367 | st2common/st2common/runners/__init__.py | st2common/st2common/runners/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Add functions for retrieving a list of dynamically registered runners. | Add functions for retrieving a list of dynamically registered runners.
Those functions match same functions exposed by the auth backend loading
functionality.
| Python | apache-2.0 | StackStorm/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2 | ---
+++
@@ -13,8 +13,32 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from stevedore.driver import DriverManager
+from stevedore.extension import ExtensionManager
+
__all__ = [
- 'BACKENDS_NAMESPACE'
+ 'BACKENDS_NAMESPACE',
+
+ 'get_available_... |
1c35bf9c4831babcdaabd9feb291a757ad298657 | src/dbbrankingparser/__init__.py | src/dbbrankingparser/__init__.py | """
DBB Ranking Parser
~~~~~~~~~~~~~~~~~~
Extract league rankings from the DBB (Deutscher Basketball Bund e.V.)
website.
The resulting data is structured as a list of dictionaries.
Please note that rankings are usually only available for the current
season, but not those of the past.
:Copyright: 2006-2021 Jochen Ku... | """
DBB Ranking Parser
~~~~~~~~~~~~~~~~~~
Extract league rankings from the DBB (Deutscher Basketball Bund e.V.)
website.
The resulting data is structured as a list of dictionaries.
Please note that rankings are usually only available for the current
season, but not those of the past.
:Copyright: 2006-2021 Jochen Ku... | Remove type annotation from `VERSION` as setuptools can't handle it | Remove type annotation from `VERSION` as setuptools can't handle it
| Python | mit | homeworkprod/dbb-ranking-parser | ---
+++
@@ -17,4 +17,4 @@
from .main import load_ranking_for_league, load_ranking_from_url
-VERSION: str = '0.4-dev'
+VERSION = '0.4-dev' |
b3ae8ed9c17ed9371a80d14d97062136da225a92 | src/chicago_flow.py | src/chicago_flow.py | #!/usr/bin/env python
import csv
import sys
import figs
def load_counts(filename):
counts = {}
with open(filename) as stream:
stream.readline()
reader = csv.reader(stream)
for row in reader:
year, count = map(int, row)
counts[year] = count
return counts
# ... | #!/usr/bin/env python
import csv
import sys
import figs
def load_counts(filename):
counts = {}
with open(filename) as stream:
stream.readline()
reader = csv.reader(stream)
for row in reader:
year, count = map(int, row)
counts[year] = count
return counts
# ... | Revert year range end back to 2015 (2016 is not over) | Revert year range end back to 2015 (2016 is not over)
| Python | unlicense | datascopeanalytics/chicago-new-business,datascopeanalytics/chicago-new-business | ---
+++
@@ -18,7 +18,7 @@
# read in the data
new_counts = load_counts(sys.argv[1])
old_counts = load_counts(sys.argv[2])
-year_range = range(2004, 2016)
+year_range = range(2004, 2015)
new_counts = [new_counts[year] for year in year_range]
old_counts = [-old_counts[year] for year in year_range]
|
b4d3fbb0535074f2153b2b9bad53fdf654ddedd1 | src/python/borg/tools/bench_bellman.py | src/python/borg/tools/bench_bellman.py | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
if __name__ == "__main__":
from borg.tools.bench_bellman import main
raise SystemExit(main())
def main():
"""
Benchmark the Bellman plan computation code.
"""
# need a place to dump profiling results
from tempfile import NamedTempor... | """
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
if __name__ == "__main__":
from borg.tools.bench_bellman import main
raise SystemExit(main())
def main():
"""
Benchmark the Bellman plan computation code.
"""
from borg.portfolio.bellman import compute_bellman_plan
from bo... | Clean up the Bellman benchmarking code. | Clean up the Bellman benchmarking code.
| Python | mit | borg-project/borg | ---
+++
@@ -12,24 +12,12 @@
Benchmark the Bellman plan computation code.
"""
- # need a place to dump profiling results
- from tempfile import NamedTemporaryFile
+ from borg.portfolio.bellman import compute_bellman_plan
+ from borg.portfolio.test.test_bellman import build_real_model
... |
37eeecd3d4d1e6d2972565961b5c31731ae55ec7 | tests/tester.py | tests/tester.py | import os
from unittest import TestCase
from servequnit.factory import ServerFactory
from servequnit.tester import QunitSeleniumTester, TestFailedError
class QunitSeleniumTesterTestCase(TestCase):
def _make_tester(self, server, suffix=None):
suffix = suffix or "oneshot/"
url = server.url + suffix
... | import os
from unittest import TestCase
from servequnit.factory import ServerFactory
from servequnit.tester import QunitSeleniumTester, TestFailedError
class QunitSeleniumTesterTestCase(TestCase):
def _make_tester(self, server, suffix=None):
suffix = suffix or "oneshot/"
url = server.url + suffix
... | Test the an empty document results in a test failure. | Test the an empty document results in a test failure.
| Python | mit | bnkr/servequnit,bnkr/servequnit,bnkr/servequnit,bnkr/selenit,bnkr/selenit | ---
+++
@@ -12,17 +12,21 @@
return tester
def test_passing_test_passes(self):
- passing = os.path.join(os.path.dirname(__file__), "data", "passes.js")
- factory = ServerFactory()
- factory.bind_script("test", passing)
+ test_file = os.path.join(os.path.dirname(__file__), "d... |
4027cccb929308528666e1232eeebfc1988e0ab1 | tests/iam/test_iam_valid_json.py | tests/iam/test_iam_valid_json.py | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as proper JSON."""
jinjaenv = jinja2.Environment(loader=jinja2.F... | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE... | Use generator for IAM template names | test: Use generator for IAM template names
See also: #208
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -5,18 +5,19 @@
from foremast.utils.templates import LOCAL_TEMPLATES
-def test_all_iam_templates():
- """Verify all IAM templates render as proper JSON."""
+def iam_templates():
+ """Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLA... |
8f0caecc4accf8258e2cae664181680973e1add6 | hftools/dataset/tests/test_helper.py | hftools/dataset/tests/test_helper.py | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | Fix to remove DeprecationWarning message from test log | Fix to remove DeprecationWarning message from test log
| Python | bsd-3-clause | hftools/hftools | ---
+++
@@ -32,8 +32,8 @@
def test_1(self):
helper.add_var_guess("R", "Ohm")
- self.assertDictContainsSubset(dict(R="Ohm"),
- helper._varname_unit_guess_db)
+ self.assertIn("R", helper._varname_unit_guess_db)
+ self.assertEqual("Ohm", helper._v... |
f5983348940e3acf937c7ddfded73f08d767c5a1 | j1a/verilator/setup.py | j1a/verilator/setup.py | from distutils.core import setup
from distutils.extension import Extension
from os import system
setup(name='vsimj1a',
ext_modules=[
Extension('vsimj1a',
['vsim.cpp'],
depends=["obj_dir/Vv3__ALL.a"],
extra_objects=["obj_dir/verilated.o", "obj_dir/Vj1a__ALL.a"],
... | from distutils.core import setup
from distutils.extension import Extension
from os import system
setup(name='vsimj1a',
ext_modules=[
Extension('vsimj1a',
['vsim.cpp'],
depends=["obj_dir/Vv3__ALL.a"],
extra_objects=["obj_dir/verilated.o", "obj_dir/Vj1a__ALL.a"],
... | Add vltstd to include path | Add vltstd to include path
| Python | bsd-3-clause | jamesbowman/swapforth,zuloloxi/swapforth,uho/swapforth,uho/swapforth,zuloloxi/swapforth,GuzTech/swapforth,jamesbowman/swapforth,jamesbowman/swapforth,GuzTech/swapforth,uho/swapforth,RGD2/swapforth,zuloloxi/swapforth,RGD2/swapforth,GuzTech/swapforth,zuloloxi/swapforth,GuzTech/swapforth,uho/swapforth,RGD2/swapforth,james... | ---
+++
@@ -9,7 +9,11 @@
['vsim.cpp'],
depends=["obj_dir/Vv3__ALL.a"],
extra_objects=["obj_dir/verilated.o", "obj_dir/Vj1a__ALL.a"],
- include_dirs=["obj_dir", "/usr/local/share/verilator/include/", "/usr/share/verilator/include/"],
+ include_dirs... |
0f7732d3ceb67ecd445bb4fe2fee1edf4ce8a2f4 | rock/utils.py | rock/utils.py | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... | from __future__ import unicode_literals
import os
try:
from io import StringIO
except ImportError: # pragma: no cover
from StringIO import StringIO
from rock.exceptions import ConfigError
ROCK_SHELL = (os.environ.get('ROCK_SHELL') or '/bin/bash -c').split()
ROCK_SHELL.insert(1, os.path.basename(ROCK_SHELL[0]... | Tweak raw text parameter name | Tweak raw text parameter name
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock | ---
+++
@@ -25,8 +25,8 @@
return isinstance(s, str)
-def raw(value):
- return value.replace('\\', '\\\\')
+def raw(text):
+ return text.replace('\\', '\\\\')
class Shell(object): |
c7b684ebf85e2a80e0acdd44ea91171bc1aa6388 | jarbas/chamber_of_deputies/fields.py | jarbas/chamber_of_deputies/fields.py | from datetime import date
from rows import fields
class IntegerField(fields.IntegerField):
@classmethod
def deserialize(cls, value, *args, **kwargs):
try: # Rows cannot convert values such as '2011.0' to integer
value = int(float(value))
except:
pass
return s... | from rows import fields
class IntegerField(fields.IntegerField):
@classmethod
def deserialize(cls, value, *args, **kwargs):
try: # Rows cannot convert values such as '2011.0' to integer
value = int(float(value))
except:
pass
return super(IntegerField, cls).des... | Make date imports more flexible | Make date imports more flexible
Now ut works with `YYYY-MM-DD HH:MM:SS` and with `YYYY-MM-DDTHH:MM:SS`.
| Python | mit | datasciencebr/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor | ---
+++
@@ -1,5 +1,3 @@
-from datetime import date
-
from rows import fields
@@ -15,11 +13,10 @@
class DateAsStringField(fields.DateField):
- INPUT_FORMAT = '%Y-%m-%dT%H:%M:%S'
+ INPUT_FORMAT = '%Y-%m-%d %H:%M:%S'
OUTPUT_FORMAT = '%Y-%m-%d'
@classmethod
def deserialize(cls, value, *ar... |
158e11dc1c11e606621a729b3b220cecf5ca700a | awx/api/management/commands/uses_mongo.py | awx/api/management/commands/uses_mongo.py | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
import sys
from django.core.management.base import BaseCommand
from awx.main.task_engine import TaskSerializer
class Command(BaseCommand):
"""Return a exit status of 0 if MongoDB should be active, and an
exit status of 1 otherwise.
This script i... | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
import sys
from django.core.management.base import BaseCommand
from awx.main.task_engine import TaskSerializer
class Command(BaseCommand):
"""Return a exit status of 0 if MongoDB should be active, and an
exit status of 1 otherwise.
This script i... | Set noqa to silence flake8. | Set noqa to silence flake8.
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx | ---
+++
@@ -29,7 +29,7 @@
# rules here will grow more complicated over time.
# FIXME: Most likely this should be False if HA is active
# (not just enabled by license, but actually in use).
- uses_mongo = system_tracking
+ uses_mongo = system_tracking # noqa
... |
7f79e575b9a2b5dc15ed304e2c1cb123ab39b91b | iscc_bench/metaid/shortnorm.py | iscc_bench/metaid/shortnorm.py | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... | # -*- coding: utf-8 -*-
import unicodedata
def shortest_normalization_form():
"""
Find unicode normalization that generates shortest utf8 encoded text.
Result NFKC
"""
s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky   things'
nfc = unicodedata.normalize('NFC', s)
nfd = unico... | Add NFD_NFC to unicode normalization comparison. | Add NFD_NFC to unicode normalization comparison.
| Python | bsd-2-clause | coblo/isccbench | ---
+++
@@ -14,6 +14,7 @@
nfkc = unicodedata.normalize('NFKC', s)
nfkd = unicodedata.normalize('NFKD', s)
nfd_nfkc = unicodedata.normalize('NFKC', nfd)
+ nfd_nfc = unicodedata.normalize('NFC', nfd)
print('UTF-8 length of normalized strings:\n')
print(f'NFC: {len(nfc.encode("utf8"))}')
@@... |
ab079e05cb0a242235c1f506cb710279bf233ba0 | opps/channels/context_processors.py | opps/channels/context_processors.py | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects... | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects... | Fix order on opps menu | Fix order on opps menu
| Python | mit | YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps | ---
+++
@@ -13,7 +13,7 @@
opps_menu = Channel.objects.filter(site=site,
date_available__lte=timezone.now(),
published=True,
- show_in_menu=True)
+ show_in_me... |
e07d6d0db7dfed8013f6b1b058167aa16070fc35 | messente/verigator/routes.py | messente/verigator/routes.py | URL = "https://api.dev.verigator.com"
CREATE_SERVICE = "v1/service/service"
GET_SERVICE = "v1/service/service/{}"
DELETE_SERVICE = "v1/service/service/{}"
GET_USERS = "v1/service/service/{}/users"
GET_USER = "v1/service/service/{}/users/{}"
CREATE_USER = "v1/service/service/{}/users"
DELETE_USER = "v1/service/service/... | URL = "https://api.verigator.com"
CREATE_SERVICE = "v1/service/service"
GET_SERVICE = "v1/service/service/{}"
DELETE_SERVICE = "v1/service/service/{}"
GET_USERS = "v1/service/service/{}/users"
GET_USER = "v1/service/service/{}/users/{}"
CREATE_USER = "v1/service/service/{}/users"
DELETE_USER = "v1/service/service/{}/u... | Update server endpoint from dev to production | Update server endpoint from dev to production
| Python | apache-2.0 | messente/verigator-python | ---
+++
@@ -1,4 +1,4 @@
-URL = "https://api.dev.verigator.com"
+URL = "https://api.verigator.com"
CREATE_SERVICE = "v1/service/service"
GET_SERVICE = "v1/service/service/{}" |
6281da3b846bfea26ea68e3fe480c738a5181506 | runtests.py | runtests.py | #!/usr/bin/env python
import optparse
import sys
import unittest
from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner... | #!/usr/bin/env python
import optparse
import os
import sys
import unittest
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.Text... | Add test-runner option to run zpop* tests. | Add test-runner option to run zpop* tests.
| Python | mit | coleifer/walrus | ---
+++
@@ -1,10 +1,9 @@
#!/usr/bin/env python
import optparse
+import os
import sys
import unittest
-
-from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
@@ -31,7 +30,14 @@
dest='verbose', help='Verbose output.')
parser.add_option('-f... |
cf0110f2b1adc8fbf4b8305841961d67da33f8c7 | pybo/bayesopt/policies/thompson.py | pybo/bayesopt/policies/thompson.py | """
Acquisition functions based on (GP) UCB.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collections import deque
# local imports
from ..util... | """
Implementation of Thompson sampling for continuous spaces.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from collections import deque
from ..utils import params
__all__ = ['Thompson']
@params('n')
def Thompson(model, n=100, rng=None):
"""
... | Fix Thompson to pay attention to the RNG. | Fix Thompson to pay attention to the RNG.
| Python | bsd-2-clause | mwhoffman/pybo,jhartford/pybo | ---
+++
@@ -1,29 +1,23 @@
"""
-Acquisition functions based on (GP) UCB.
+Implementation of Thompson sampling for continuous spaces.
"""
-# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
-# use this to simplify (slightly) the Thompso... |
c96a2f636b48b065e8404af6d67fbae5986fd34a | tests/basics/subclass_native2_tuple.py | tests/basics/subclass_native2_tuple.py | class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
| class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
a = tuple([1,... | Expand test cases for equality of subclasses. | tests/basics: Expand test cases for equality of subclasses.
| Python | mit | pramasoul/micropython,adafruit/circuitpython,henriknelson/micropython,MrSurly/micropython,bvernoux/micropython,tobbad/micropython,kerneltask/micropython,kerneltask/micropython,tobbad/micropython,tobbad/micropython,pramasoul/micropython,selste/micropython,adafruit/circuitpython,henriknelson/micropython,pozetroninc/micro... | ---
+++
@@ -19,3 +19,11 @@
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
+
+a = tuple([1,2,3])
+b = Ctuple1([1,2,3])
+c = Ctuple2([1,2,3])
+
+print(a == b)
+print(b == c)
+print(c == a) |
4d3a0dc3b3b8a11a066f52bc78b1160e194ad64f | wmtexe/cmd/script.py | wmtexe/cmd/script.py | """Launch a WMT simulation using `bash` or `qsub`."""
from __future__ import print_function
import sys
import os
from ..launcher import BashLauncher, QsubLauncher
_LAUNCHERS = {
'bash': BashLauncher,
'qsub': QsubLauncher,
}
def main():
import argparse
parser = argparse.ArgumentParser(description=... | """Launch a WMT simulation using `bash` or `qsub`."""
from __future__ import print_function
import sys
import os
from ..launcher import BashLauncher, QsubLauncher
_LAUNCHERS = {
'bash': BashLauncher,
'qsub': QsubLauncher,
}
def main():
import argparse
parser = argparse.ArgumentParser(description=... | Add 'server-url' command line argument | Add 'server-url' command line argument
Its value is passed to the server_url parameter of the Launcher class.
| Python | mit | csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe | ---
+++
@@ -22,6 +22,8 @@
help='Unique identifier for simulation')
parser.add_argument('--extra-args', default='',
help='Extra arguments for wmt-slave command')
+ parser.add_argument('--server-url', default='',
+ help='WMT API server URL... |
f5408c02202a07a1b45019eefb505eb8a0d21852 | swagger2markdown.py | swagger2markdown.py | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... | import argparse, json, os.path
import jinja2, requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input",
default="swagger.json",
help="path to or URL of the Swagger JSON file (default: swagger.json)",
metavar="SWAGGER_LOCATION"
)
par... | Fix crash when URL is provided. | Fix crash when URL is provided.
| Python | mit | moigagoo/swagger2markdown | ---
+++
@@ -31,7 +31,7 @@
try:
swagger_data = json.load(open(args.input, encoding="utf8"))
- except FileNotFoundError:
+ except (FileNotFoundError, OSError):
swagger_data = requests.get(args.input).json()
template = jinja2.Template(open(args.template, encoding="utf8").read()) |
75ae022a615d51850e5c8766b1a300207489559d | django_jinja/__init__.py | django_jinja/__init__.py | # -*- coding: utf-8 -*-
__version__ = (0, 2, 0, 'final', 0)
| # -*- coding: utf-8 -*-
__version__ = (0, 3, 0, 'final', 0)
| Increment version number to 0.3 | Increment version number to 0.3
| Python | bsd-3-clause | akx/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,akx/django-jinja,glogiotatidis/django-jinja,akx/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,niwinz/django-jinja,glogiotatidis/django-jinja,akx/django-jinja | ---
+++
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
-__version__ = (0, 2, 0, 'final', 0)
+__version__ = (0, 3, 0, 'final', 0) |
69595a9617ce83e04c5de5f4d8cd6185765f3697 | django_jobvite/models.py | django_jobvite/models.py | from django.db import models
class Position(models.Model):
job_id = models.CharField(max_length=25, unique=True)
title = models.CharField(max_length=100)
requisition_id = models.PositiveIntegerField()
category = models.CharField(max_length=35)
job_type = models.CharField(max_length=10)
locatio... | from django.db import models
class Position(models.Model):
job_id = models.CharField(max_length=25, unique=True)
title = models.CharField(max_length=100)
requisition_id = models.PositiveIntegerField()
category = models.CharField(max_length=50)
job_type = models.CharField(max_length=10)
locatio... | Increase size of category field. | Increase size of category field.
| Python | bsd-3-clause | mozilla/django-jobvite | ---
+++
@@ -5,7 +5,7 @@
job_id = models.CharField(max_length=25, unique=True)
title = models.CharField(max_length=100)
requisition_id = models.PositiveIntegerField()
- category = models.CharField(max_length=35)
+ category = models.CharField(max_length=50)
job_type = models.CharField(max_leng... |
2715c9accc8e8abaad72cd9afcec914dda0c6b46 | pokediadb/utils.py | pokediadb/utils.py | import sqlite3
def max_sql_variables():
"""Get the maximum number of arguments allowed in a query by the current
sqlite3 implementation.
Returns:
int: SQLITE_MAX_VARIABLE_NUMBER
"""
db = sqlite3.connect(':memory:')
cur = db.cursor()
cur.execute('CREATE TABLE t (test)')
low, h... | import sqlite3
def max_sql_variables():
"""Get the maximum number of arguments allowed in a query by the current
sqlite3 implementation.
Returns:
int: SQLITE_MAX_VARIABLE_NUMBER
"""
db = sqlite3.connect(':memory:')
cur = db.cursor()
cur.execute('CREATE TABLE t (test)')
low, h... | Fix travis error with SQLITE_LIMIT_VARIABLE_NUMBER | Fix travis error with SQLITE_LIMIT_VARIABLE_NUMBER
| Python | mit | Kynarth/pokediadb | ---
+++
@@ -25,7 +25,7 @@
if "too many SQL variables" in str(e):
high = guess
else:
- raise
+ return 999
else:
low = guess
|
da0478a48329ac79092a4603f4026434af26f032 | scanblog/scanning/management/commands/fixuploadperms.py | scanblog/scanning/management/commands/fixuploadperms.py | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLO... | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLO... | Use multi arg option too | Use multi arg option too
| Python | agpl-3.0 | yourcelf/btb,yourcelf/btb,yourcelf/btb,yourcelf/btb,yourcelf/btb | ---
+++
@@ -18,4 +18,4 @@
os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
- os.system('sudo find "%s" -type d -exec sudo chmod g+s {} \\;' % dirname)
+ os.system('su... |
5a653d0a6f0c97109254b043e9697675b5863218 | pyquil/__init__.py | pyquil/__init__.py | __version__ = "2.0.0b1"
from pyquil.quil import Program
from pyquil.api import list_quantum_computers, get_qc
| __version__ = "2.0.0b2.dev0"
from pyquil.quil import Program
from pyquil.api import list_quantum_computers, get_qc
| Set version back to dev | Set version back to dev
| Python | apache-2.0 | rigetticomputing/pyquil | ---
+++
@@ -1,4 +1,4 @@
-__version__ = "2.0.0b1"
+__version__ = "2.0.0b2.dev0"
from pyquil.quil import Program
from pyquil.api import list_quantum_computers, get_qc |
42326a18132381f0488b587329fe6b9aaea47c87 | normandy/selfrepair/views.py | normandy/selfrepair/views.py | from django.shortcuts import render
from normandy.base.decorators import short_circuit_middlewares
@short_circuit_middlewares
def repair(request, locale):
return render(request, 'selfrepair/repair.html', {
'locale': locale,
})
| from django.conf import settings
from django.shortcuts import render
from django.views.decorators.cache import cache_control
from normandy.base.decorators import short_circuit_middlewares
@short_circuit_middlewares
@cache_control(public=True, max_age=settings.API_CACHE_TIME)
def repair(request, locale):
return r... | Add cache headers to self-repair page | Add cache headers to self-repair page
| Python | mpl-2.0 | Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy | ---
+++
@@ -1,9 +1,12 @@
+from django.conf import settings
from django.shortcuts import render
+from django.views.decorators.cache import cache_control
from normandy.base.decorators import short_circuit_middlewares
@short_circuit_middlewares
+@cache_control(public=True, max_age=settings.API_CACHE_TIME)
def ... |
9d541eeebe789d61d915dbbc7fd5792e244bd93f | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -14,5 +14,8 @@
import ibmcnx.functions
-t1 = ibmcnx.functions.getDSId( db )
-AdminConfig.list( t1 )
+dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
+
+for db in dbs:
+ t1 = ibmcnx.functions.getDSId( db )
+ AdminConfig.list( t1 ) |
8fa72cea635171e94f0fb5538bc82197c6890b36 | tests/issues/test_issue0619.py | tests/issues/test_issue0619.py | # -*- coding: UTF-8 -*-
"""
https://github.com/behave/behave/issues/619
When trying to do something like::
foo = getattr(context, '_foo', 'bar')
Behave fails with::
File "[...]/behave/runner.py", line 208, in __getattr__
return self.__dict__[attr]
KeyError: '_foo'
I think this is because the __ge... | # -*- coding: UTF-8 -*-
"""
https://github.com/behave/behave/issues/619
When trying to do something like::
foo = getattr(context, '_foo', 'bar')
Behave fails with::
File "[...]/behave/runner.py", line 208, in __getattr__
return self.__dict__[attr]
KeyError: '_foo'
I think this is because the __ge... | FIX problem after reorganizing test. | FIX problem after reorganizing test.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave | ---
+++
@@ -22,7 +22,7 @@
from mock import Mock
-def test_issue__getattr_with_protected_unknown_context_attribute_raises_no_error(self):
+def test_issue__getattr_with_protected_unknown_context_attribute_raises_no_error():
context = Context(runner=Mock())
with scoped_context_layer(context): # CALLS-HER... |
0a522863dce6e42bf66c66a56078c00901c64f52 | redash/__init__.py | redash/__init__.py | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | Use database number from redis url if available. | Use database number from redis url if available.
| Python | bsd-2-clause | denisov-vlad/redash,EverlyWell/redash,44px/redash,rockwotj/redash,M32Media/redash,guaguadev/redash,stefanseifert/redash,hudl/redash,easytaxibr/redash,denisov-vlad/redash,ninneko/redash,jmvasquez/redashtest,crowdworks/redash,easytaxibr/redash,getredash/redash,pubnative/redash,rockwotj/redash,crowdworks/redash,stefanseif... | ---
+++
@@ -33,7 +33,11 @@
redis_url = urlparse.urlparse(settings.REDIS_URL)
-redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
+if redis_url.path:
+ redis_db = redis_url.path[1]
+else:
+ redis_db = 0
+redis_connection = redis.StrictRedis(... |
86418b48ca9bef5d0cd7cbf8468abfad633b56ed | write_csv.py | write_csv.py | """Export all responses from yesterday and save them to a CSV file."""
import sqlite3
import csv
from datetime import datetime, timedelta
import os
today = str(datetime.now().strftime('%Y-%m-%d'))
yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
export_directory = 'export'
export_filename ... | """Export all responses from yesterday and save them to a .csv file."""
import sqlite3
import csv
from datetime import datetime, timedelta
import os
today = str(datetime.now().strftime('%Y-%m-%d'))
yesterday = str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
export_directory = 'export'
export_filename... | Add try/except in case select function fails | Add try/except in case select function fails
| Python | mit | andrewlrogers/srvy | ---
+++
@@ -1,4 +1,4 @@
-"""Export all responses from yesterday and save them to a CSV file."""
+"""Export all responses from yesterday and save them to a .csv file."""
import sqlite3
import csv
@@ -27,11 +27,13 @@
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
-c.execute("SELEC... |
35a046a61d0acc1d6b7a1c084077bdf9ed7ff720 | tests/utils/parse_worksheet.py | tests/utils/parse_worksheet.py | import unittest
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_sheet should be defined.')
def test_get_data_function_is_defined(self):
... | import unittest
from unittest.mock import patch
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
self.fail('__open_worksheet should be defined.')
def test_g... | Remove testing of private methods (other than that they exist) | Remove testing of private methods (other than that they exist)
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend | ---
+++
@@ -1,11 +1,12 @@
import unittest
+from unittest.mock import patch
from utils import parse_worksheet
class TestParseWorksheet(unittest.TestCase):
def test_open_worksheet_function_is_defined(self):
if not hasattr(parse_worksheet, '__open_worksheet'):
- self.fail('__open_sheet sho... |
fa7228e26791987e43fdcb216f98658b45a8b220 | slave/skia_slave_scripts/run_gm.py | slave/skia_slave_scripts/run_gm.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia GM executable. """
from build_step import BuildStep
import os
import sys
JSON_SUMMARY_FILENAME = 'actual-result... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia GM executable. """
from build_step import BuildStep
import os
import sys
JSON_SUMMARY_FILENAME = 'actual-result... | Fix buildbot flag to GM | Fix buildbot flag to GM
Unreviewed
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8282 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Ti... | ---
+++
@@ -22,7 +22,7 @@
] + self._gm_args
# msaa16 is flaky on Macs (driver bug?) so we skip the test for now
if sys.platform == 'darwin':
- cmd.extend(['--exclude-config', 'msaa16'])
+ cmd.extend(['--excludeConfig', 'msaa16'])
self.RunFlavoredCmd('gm', cmd)
|
e5940200612b293b1cecff4c6a683ecefa684345 | dirMonitor.py | dirMonitor.py | #!/usr/bin/env python
import os, sys, time
folders = sys.argv[1:]
currSize = dict((x, 0) for x in folders)
totalSize = dict((x, 0) for x in folders)
maxSize = dict((x, 0) for x in folders)
fmts = "%*s %13s %13s %13s"
fmtd = "%*s %13d %13d %13d"
n = 0
while True:
print fmts % (15, "dir", "size", "avg", "m... | #!/usr/bin/env python
import os, sys, time
folders = sys.argv[1:]
nameWidth = max([len(f) for f in folders])
currSize = dict((x, 0) for x in folders)
totalSize = dict((x, 0) for x in folders)
maxSize = dict((x, 0) for x in folders)
fmts = "%*s %13s%s %13s%s %13s%s"
n = 0
while True:
print fmts % (nameWidth,... | Add formatting to directory monitor. | Add formatting to directory monitor.
| Python | apache-2.0 | jskora/scratch-nifi,jskora/scratch-nifi,jskora/scratch-nifi | ---
+++
@@ -3,24 +3,32 @@
import os, sys, time
folders = sys.argv[1:]
+nameWidth = max([len(f) for f in folders])
currSize = dict((x, 0) for x in folders)
totalSize = dict((x, 0) for x in folders)
maxSize = dict((x, 0) for x in folders)
-fmts = "%*s %13s %13s %13s"
-fmtd = "%*s %13d %13d %13d"
+fmts ... |
e188e324f1c7b8afab3b65b9e7337a0b1c3981f0 | docs/conf.py | docs/conf.py | #!/usr/bin/env python
import alabaster
from sprockets.mixins import cors
project = 'sprockets.mixins.cors'
copyright = '2015, AWeber Communication, Inc.'
version = cors.__version__
release = '.'.join(str(v) for v in cors.version_info[0:2])
needs_sphinx = '1.0'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext... | #!/usr/bin/env python
import alabaster
from sprockets.mixins import cors
project = 'sprockets.mixins.cors'
copyright = '2015, AWeber Communication, Inc.'
version = cors.__version__
release = '.'.join(str(v) for v in cors.version_info[0:2])
needs_sphinx = '1.0'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext... | Correct inter sphinx path to Tornado docs. | Correct inter sphinx path to Tornado docs.
| Python | bsd-3-clause | sprockets/sprockets.mixins.cors | ---
+++
@@ -38,5 +38,5 @@
intersphinx_mapping = {
'python': ('https://docs.python.org/', None),
- 'tornado': ('https://tornadoweb.org/en/latest/', None),
+ 'tornado': ('http://www.tornadoweb.org/en/latest/', None),
} |
b13baaa37133b7d4fe46682dbce7ed94d46ecaf4 | docs/conf.py | docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx'
]
source_suffix = '.rst'
master_doc = 'index'
project = 'Javelin'
copyright = '2017, Ross Whitfield'
author = 'Ross Whitfield'
version = '0.1.0'
release = '0.1.0'
exclude_patt... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode'
]
source_suffix = '.rst'
master_doc = 'index'
project = 'Javelin'
copyright = '2017, Ross Whitfield'
author = 'Ross Whitfield'
version = '0.1.0'
release = '0.1.0'
exclude... | Add viewcode to sphinx docs | Add viewcode to sphinx docs
| Python | mit | rosswhitfield/javelin | ---
+++
@@ -1,12 +1,10 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
-import os
-import sys
-
extensions = [
'sphinx.ext.autodoc',
- 'sphinx.ext.intersphinx'
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.viewcode'
]
source_suffix = '.rst' |
88f02fbea11390ec8866c29912ed8beadc31e736 | admin/common_auth/forms.py | admin/common_auth/forms.py | from __future__ import absolute_import
from django import forms
from django.contrib.auth.models import Group
from osf.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.Pas... | from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from osf.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Pass... | Exclude preprints from queryset from account/register in the admin app. | Exclude preprints from queryset from account/register in the admin app.
| Python | apache-2.0 | adlius/osf.io,mfraezz/osf.io,cslzchen/osf.io,mfraezz/osf.io,baylee-d/osf.io,felliott/osf.io,mfraezz/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,pattisdr/osf.io,aaxelb/osf.io,adlius/osf.io,adlius/osf.io,felli... | ---
+++
@@ -1,6 +1,7 @@
from __future__ import absolute_import
from django import forms
+from django.db.models import Q
from django.contrib.auth.models import Group
from osf.models import AdminProfile
@@ -23,7 +24,7 @@
# TODO: Moving to guardian, find a better way to distinguish "admin-like" groups fro... |
d12fecd2eb012862b8d7654c879dccf5ccce833f | jose/backends/__init__.py | jose/backends/__init__.py |
try:
from jose.backends.pycrypto_backend import RSAKey
except ImportError:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey a... |
try:
from jose.backends.pycrypto_backend import RSAKey
except ImportError:
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
except ImportError:
from jose.backends.rsa_backend import RSAKey
try:
from jose.backends.cryptography_backend import CryptographyE... | Enable Python RSA backend as a fallback. | Enable Python RSA backend as a fallback.
| Python | mit | mpdavis/python-jose | ---
+++
@@ -2,7 +2,10 @@
try:
from jose.backends.pycrypto_backend import RSAKey
except ImportError:
- from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
+ try:
+ from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
+ except ImportError:
+ f... |
69e8798137ca63b78adf0c41582e89973d2ea129 | create.py | create.py | import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.cre... | import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.cre... | Work on model file handling | Work on model file handling
| Python | agpl-3.0 | edx/ease,edx/ease | ---
+++
@@ -22,12 +22,15 @@
feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set)
except:
results['errors'].append("feature extraction and model creation failed.")
- try:
- util_functions.create_directory(model_path)
- model_creator.dump_model_to_fi... |
cb97f453284658da56d12ab696ef6b7d7991c727 | dipy/io/tests/test_csareader.py | dipy/io/tests/test_csareader.py | """ Testing Siemens CSA header reader
"""
import os
from os.path import join as pjoin
import numpy as np
import dipy.io.csareader as csa
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing imp... | """ Testing Siemens CSA header reader
"""
import os
from os.path import join as pjoin
import numpy as np
import dipy.io.csareader as csa
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing imp... | TEST - add test for value | TEST - add test for value
| Python | bsd-3-clause | jyeatman/dipy,beni55/dipy,samuelstjean/dipy,FrancoisRheaultUS/dipy,demianw/dipy,demianw/dipy,nilgoyyou/dipy,jyeatman/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,Messaoud-Boudjada/dipy,StongeEtienne/dipy,villalonreina/dipy,JohnGriffiths/dipy,rfdougherty/dipy,villalonreina/dipy,sinkpoint/dipy,JohnGriffiths/dipy,Franc... | ---
+++
@@ -28,4 +28,5 @@
yield assert_equal(csa_info['n_tags'], 83)
tags = csa_info['tags']
yield assert_equal(len(tags), 83)
- print csa_info
+ yield assert_equal(tags['NumberOfImagesInMosaic']['value'],
+ '48') |
63ca4ab4fc7237a9b32d82d73160b7f02c3ac133 | settings.py | settings.py | # coding: utf-8
import os.path
import yaml
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml')
with open(CONFIG_PATH, 'r') as fh:
config = yaml.load(fh)
# Jira settings
JIRA_URL = config['jira']['url']
JIRA_USER = config['jira']['user']
JIRA_PASS = config['jira']['pass']
JIRA_PROJECT = confi... | # coding: utf-8
import os.path
import yaml
import logging
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml')
logger = logging.getLogger(__name__)
try:
with open(CONFIG_PATH, 'r') as fh:
config = yaml.load(fh)
except FileNotFoundError:
logging.error('Config file was not found: s... | Add "config file was not fount" error handler | Add "config file was not fount" error handler
| Python | mit | vv-p/jira-reports,vv-p/jira-reports | ---
+++
@@ -2,12 +2,21 @@
import os.path
import yaml
+import logging
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml')
-with open(CONFIG_PATH, 'r') as fh:
- config = yaml.load(fh)
+logger = logging.getLogger(__name__)
+
+
+try:
+ with open(CONFIG_PATH, 'r') as fh:
+ config... |
0ad6cb338bbf10c48049d5649b5cd41eab0ed8d1 | prawcore/sessions.py | prawcore/sessions.py | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self):
"""Preprare the connection to reddit's API."""
self._session = requests.Session()
def __enter__(s... | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self, authorizer=None):
"""Preprare the connection to reddit's API.
:param authorizer: An instance of :class... | Add optional authorizer parameter to session class and function. | Add optional authorizer parameter to session class and function.
| Python | bsd-2-clause | praw-dev/prawcore | ---
+++
@@ -6,8 +6,13 @@
class Session(object):
"""The low-level connection interface to reddit's API."""
- def __init__(self):
- """Preprare the connection to reddit's API."""
+ def __init__(self, authorizer=None):
+ """Preprare the connection to reddit's API.
+
+ :param authorizer... |
4fa8f7cb8a0592ed1d37efa20fd4a23d12e88713 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
#
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an inte... | Update regexp due to changes in stylint | Update regexp due to changes in stylint
| Python | mit | jackbrewer/SublimeLinter-contrib-stylint | ---
+++
@@ -6,7 +6,6 @@
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
-#
"""This module exports the Stylint plugin class."""
@@ -21,17 +20,13 @@
syntax = 'stylus'
cmd = 'stylint @ *'
executable = 'stylint'
- version_requirement = '>= 0.9.3'
+ version_requirement = '>= 1.5.6, < 1.6.0'
... |
266e0976ee41e4dd1a9c543c84d422a8fba61230 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the Tlec plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class Tlec(Linter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the Tlec plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class Tlec(Linter):
"""Provides an in... | Check if epages6 settings are configured | Check if epages6 settings are configured
| Python | mit | ePages-rnd/SublimeLinter-contrib-tlec | ---
+++
@@ -18,7 +18,10 @@
"""Provides an interface to tlec."""
def cmd(self):
- return [self.executable_path, sublime.packages_path() + '/Epages6/ep6-tools.py', '--vm', self.view.settings().get('ep6vm')['vm'], '--lint', '--file', self.view.file_name(), '--user', 'root', '--password', 'qwert6', '-... |
fe35867409af3bdf9898b68ce356ef00b865ff29 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.1",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
... | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.2",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
... | Change version to 1.0.2 (stable) | Change version to 1.0.2 (stable)
| Python | agpl-3.0 | xcgd/account_credit_transfer | ---
+++
@@ -2,7 +2,7 @@
{
"name": "Account Credit Transfer",
- "version": "1.0.1",
+ "version": "1.0.2",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting', |
563f2e153437e7f78e05ed9dade1bd1690bef6a5 | karspexet/ticket/admin.py | karspexet/ticket/admin.py | from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'tickets')
list_filter = ('finalized', 'show')
class TicketAdmin(admin.ModelAd... | from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'session_timeout', 'tickets')
list_filter = ('finalized', 'show')
class Ticket... | Add session_timeout to ReservationAdmin list_display | Add session_timeout to ReservationAdmin list_display
| Python | mit | Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet | ---
+++
@@ -4,7 +4,7 @@
class ReservationAdmin(admin.ModelAdmin):
- list_display = ('show', 'total', 'finalized', 'reservation_code', 'tickets')
+ list_display = ('show', 'total', 'finalized', 'reservation_code', 'session_timeout', 'tickets')
list_filter = ('finalized', 'show')
|
24f1f686c5cdc9a2272adbea7d1c2e1eb481dc8d | tests/unit/fakes.py | tests/unit/fakes.py | # Copyright 2012 Intel Inc, OpenStack Foundation.
# 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
#
# ... | # Copyright 2012 Intel Inc, OpenStack Foundation.
# 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
#
# ... | Make vertical white space after license header consistent | Trivial: Make vertical white space after license header consistent
Vertical white space between license header and the actual code is not consistent
across files. It looks like majority of the files leaves a single blank line
after license header. So make it consistent except for those exceptional cases
where the actu... | Python | apache-2.0 | varunarya10/oslo.i18n,openstack/oslo.i18n | ---
+++
@@ -12,6 +12,7 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
+
"""
Fakes For filter and weight tests.
""" |
aad92644d01994685d20121def511da2765adfad | src/data.py | src/data.py | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | Add neighbrhood property to row | Add neighbrhood property to row
| Python | unlicense | datascopeanalytics/chicago-new-business,datascopeanalytics/chicago-new-business | ---
+++
@@ -37,6 +37,10 @@
def account_number(self):
return self['ACCOUNT NUMBER']
+ @property
+ def neighborhood(self):
+ return self['NEIGHBORHOOD']
+
class RawReader(csv.DictReader):
|
7535bd611b26fa81944058c49e7238bd67a5f577 | forms_builder/wrapper/forms.py | forms_builder/wrapper/forms.py | from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
# A form set t... | from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
exclude... | Exclude unnecessary fields for Enjaz | Exclude unnecessary fields for Enjaz
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz | ---
+++
@@ -9,6 +9,8 @@
"""
class Meta:
model = Form
+ exclude = ('sites', 'redirect_url', 'login_required', 'send_email', 'email_from',
+ 'email_copies', 'email_subject', 'email_message')
# A form set to manage adding, modifying, or deleting fields of a form
FieldFormS... |
eaec82bb0a4a11f683c34550bdc23b3c6b0c48d2 | examples/M1/M1_export.py | examples/M1/M1_export.py | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExport(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1') # create and export network to NeuroML 2 | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1',
connections=True,
stimulations=True) #... | Update script to export to nml2 of m1 | Update script to export to nml2 of m1
| Python | mit | Neurosim-lab/netpyne,thekerrlab/netpyne,Neurosim-lab/netpyne | ---
+++
@@ -1,6 +1,8 @@
import M1 # import parameters file
from netpyne import sim # import netpyne sim module
-sim.createAndExport(netParams = M1.netParams,
+sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
- reference = 'M1') # cr... |
565c95ce9a8ff96d177196c6dbf8d8f88cdfa029 | poyo/exceptions.py | poyo/exceptions.py | # -*- coding: utf-8 -*-
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no p... | # -*- coding: utf-8 -*-
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no p... | Add an error class for string data that is ignored by the parser | Add an error class for string data that is ignored by the parser
| Python | mit | hackebrot/poyo | ---
+++
@@ -20,3 +20,9 @@
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
+
+
+class IgnoredMatchException(PoyoException):
+ """Raised when a match does result in a Python representation such as a
+ comment or a blank line.
+ """ |
fb02617b29cab97a70a1a11b0d3b7b62b834aa3b | server.py | server.py | from flask import Flask
from flask import request
import flask
import hashlib
import json
import gzip
app = Flask(__name__)
stored_files = {}
@app.route('/profile/<type>', methods=['GET'])
def get_dummy_files(type):
if type == 'lawyer':
pass
elif type == 'doctor:':
pass
elif type == 'fema... | from flask import Flask
from flask import request
import flask
import hashlib
import json
import gzip
app = Flask(__name__)
stored_files = {}
@app.route('/profile/<type>', methods=['GET'])
def get_dummy_files(type):
if type == 'lawyer':
gzip_address = './zipfiles/doc.tar.gz'
elif type == 'doctor:':
... | Structure for sending dummy files | Structure for sending dummy files
| Python | mit | rotemh/soteria | ---
+++
@@ -12,17 +12,18 @@
@app.route('/profile/<type>', methods=['GET'])
def get_dummy_files(type):
if type == 'lawyer':
- pass
+ gzip_address = './zipfiles/doc.tar.gz'
elif type == 'doctor:':
- pass
+ gzip_address = './zipfiles/doc.tar.gz'
elif type == 'female':
- ... |
24fc06d17303868ef4ea057cd001ec6cb49ab18f | flask_app.py | flask_app.py | import os
from flask import Flask, render_template
from jinja2 import Template
app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..')
app.config.from_pyfile('settings.py')
BASE = '/%s' % app.config['REPO_NAME']
@app.route('/')
def home():
with open('talk.md', 'r') as f:
templa... | import os
from flask import Flask, render_template
from jinja2 import Template
app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..')
app.config.from_pyfile('settings.py')
BASE = '/%s' % app.config['REPO_NAME']
@app.route('/')
def home():
with open('talk.md', 'r') as f:
templa... | Fix utf-8 problem with åäö and friends. | Fix utf-8 problem with åäö and friends.
| Python | bsd-3-clause | sknippen/refreeze,sknippen/refreeze,sknippen/refreeze | ---
+++
@@ -10,7 +10,7 @@
@app.route('/')
def home():
with open('talk.md', 'r') as f:
- template = Template(f.read())
+ template = Template(f.read().decode('utf-8'))
markdown = template.render(base=BASE)
js_file = 'talk.js'
if os.path.isfile(js_file): |
37d8fadd25ebf06207e046007097b06ecb9f33ac | numba/cuda/tests/cudapy/test_alignment.py | numba/cuda/tests/cudapy/test_alignment.py | import numpy as np
from numba import from_dtype, cuda
from numba import unittest_support as unittest
class TestAlignment(unittest.TestCase):
def test_record_alignment(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True)
rec = from_dtype(rec_dtype)
@cuda.jit((rec[:],... | import numpy as np
from numba import from_dtype, cuda
from numba import unittest_support as unittest
class TestAlignment(unittest.TestCase):
def test_record_alignment(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True)
rec = from_dtype(rec_dtype)
@cuda.jit((rec[:],... | Use Numpy dtype when creating Numpy array | Use Numpy dtype when creating Numpy array
(as opposed to the Numba dtype)
| Python | bsd-2-clause | sklam/numba,pombredanne/numba,IntelLabs/numba,GaZ3ll3/numba,stonebig/numba,stuartarchibald/numba,IntelLabs/numba,jriehl/numba,IntelLabs/numba,ssarangi/numba,stonebig/numba,stonebig/numba,seibert/numba,seibert/numba,jriehl/numba,GaZ3ll3/numba,jriehl/numba,sklam/numba,stonebig/numba,gmarkall/numba,numba/numba,gmarkall/nu... | ---
+++
@@ -13,7 +13,7 @@
i = cuda.grid(1)
a[i].a = a[i].b
- a_recarray = np.recarray(3, dtype=rec)
+ a_recarray = np.recarray(3, dtype=rec_dtype)
for i in range(a_recarray.size):
a_rec = a_recarray[i]
a_rec.a = 0 |
ba408df025136563c0eafe00551f23e44e9c2731 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
A ... | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.1",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
... | Change version to 1.0.1 unstable | Change version to 1.0.1 unstable
| Python | agpl-3.0 | xcgd/account_credit_transfer | ---
+++
@@ -2,7 +2,7 @@
{
"name": "Account Credit Transfer",
- "version": "1.0",
+ "version": "1.0.1",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting', |
38a9f75bc87dbfb698b852145b7d62e9913602b4 | tcldis.py | tcldis.py | from __future__ import print_function
def _tcldis_init():
import sys
import _tcldis
mod = sys.modules[__name__]
for key, value in _tcldis.__dict__.iteritems():
if not callable(value):
continue
mod.__dict__[key] = value
_tcldis_init()
| from __future__ import print_function
import _tcldis
printbc = _tcldis.printbc
getbc = _tcldis.getbc
inst_table = _tcldis.inst_table
| Stop trying to be overly clever | Stop trying to be overly clever
| Python | bsd-3-clause | tolysz/tcldis,tolysz/tcldis,tolysz/tcldis,tolysz/tcldis | ---
+++
@@ -1,12 +1,6 @@
from __future__ import print_function
-def _tcldis_init():
- import sys
- import _tcldis
- mod = sys.modules[__name__]
- for key, value in _tcldis.__dict__.iteritems():
- if not callable(value):
- continue
- mod.__dict__[key] = value
-
-_tcldis_init()
+... |
0c8739457150e4ae6e47ffb42d43a560f607a141 | tests/run.py | tests/run.py | from spec import eq_, skip, Spec, raises, ok_
from invoke.run import run
from invoke.exceptions import Failure
class Run(Spec):
"""run()"""
def return_code_in_result(self):
r = run("echo 'foo'")
eq_(r.stdout, "foo\n")
eq_(r.return_code, 0)
eq_(r.exited, 0)
def nonzero_ret... | from spec import eq_, skip, Spec, raises, ok_, trap
from invoke.run import run
from invoke.exceptions import Failure
class Run(Spec):
"""run()"""
def return_code_in_result(self):
r = run("echo 'foo'")
eq_(r.stdout, "foo\n")
eq_(r.return_code, 0)
eq_(r.exited, 0)
def nonze... | Add test re: hide kwarg | Add test re: hide kwarg
| Python | bsd-2-clause | frol/invoke,sophacles/invoke,mkusz/invoke,alex/invoke,mkusz/invoke,frol/invoke,pyinvoke/invoke,kejbaly2/invoke,mattrobenolt/invoke,mattrobenolt/invoke,pfmoore/invoke,tyewang/invoke,kejbaly2/invoke,pfmoore/invoke,singingwolfboy/invoke,pyinvoke/invoke | ---
+++
@@ -1,4 +1,4 @@
-from spec import eq_, skip, Spec, raises, ok_
+from spec import eq_, skip, Spec, raises, ok_, trap
from invoke.run import run
from invoke.exceptions import Failure
@@ -27,7 +27,12 @@
ok_(run("true"))
def non_one_return_codes_still_act_as_False(self):
- ok_(not run("... |
7fe3776a59de7a133c5e396cb43d9b4bcc476f7d | protocols/views.py | protocols/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from members.models import User
from .models import Protocol, Topic
from .forms import ProtocolForm, TopicForm, InstitutionForm
@login_required
def add(request):
data = request.POST ... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from members.models import User
from .models import Protocol, Topic
from .forms import ProtocolForm, TopicForm, InstitutionForm
@login_required
def add(request):
data = request.POST ... | Fix the check if form is submitted | Fix the check if form is submitted
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -9,10 +9,8 @@
@login_required
def add(request):
- data = request.POST if request else None
+ data = request.POST if request.POST else None
form = ProtocolForm(data)
-
- #import ipdb; ipdb.set_trace()
if form.is_valid():
form.save() |
7d1a903845db60186318575db11a712cd62d884d | win-installer/gaphor-script.py | win-installer/gaphor-script.py | if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.actionmanager import ActionManager
from gaphor.plugins.alignment import Alignment
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gapho... | if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gaphor.services.copyservice import CopyService
from gaphor.plugins.diagramlayout import DiagramLayout
from g... | Fix mypy import errors due to removed services | Fix mypy import errors due to removed services
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -1,25 +1,19 @@
if __name__ == "__main__":
import gaphor
from gaphor import core
- from gaphor.services.actionmanager import ActionManager
- from gaphor.plugins.alignment import Alignment
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow ... |
5aca39cef15ea4381b30127b8ded31ec37ffd273 | script/notification/ifttt.py | script/notification/ifttt.py | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.ev... | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.ev... | Add image to ifff request | Add image to ifff request
| Python | mit | niqdev/packtpub-crawler,niqdev/packtpub-crawler,niqdev/packtpub-crawler | ---
+++
@@ -13,7 +13,11 @@
)
def send(self):
- r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')})
+ r = requests.post(self.__url, data = {
+ 'value1':self.__packpub_info['ti... |
392aeb99891ff9949c9e9e205743937d8e9cb632 | bot/api/telegram.py | bot/api/telegram.py | import requests
class TelegramBotApi:
"""This is a threading-safe API. Avoid breaking it by adding state."""
def __init__(self, auth_token, debug: bool):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
self.debug = debug
def __getattr__(self, item):
return self.... | import threading
import requests
class TelegramBotApi:
"""This is a threading-safe API. Avoid breaking it by adding state."""
def __init__(self, auth_token, debug: bool):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
self.debug = debug
self.local = threading.local... | Use threading.local() to store a requests.Session object per-thread and use it to perform the requests, allowing connections to be reused, speeding bot replies a lot | Use threading.local() to store a requests.Session object per-thread and use it to perform the requests, allowing connections to be reused, speeding bot replies a lot
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -1,3 +1,5 @@
+import threading
+
import requests
@@ -7,6 +9,7 @@
def __init__(self, auth_token, debug: bool):
self.base_url = "https://api.telegram.org/bot" + auth_token + "/"
self.debug = debug
+ self.local = threading.local()
def __getattr__(self, item):
... |
91141713b672f56a8c45f0250b7e9216a69237f8 | features/support/splinter_client.py | features/support/splinter_client.py | import logging
from pymongo import MongoClient
from splinter import Browser
from features.support.http_test_client import HTTPTestClient
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api =... | import logging
from pymongo import MongoClient
from splinter import Browser
from features.support.http_test_client import HTTPTestClient
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api =... | Increase splinter wait time to 15 seconds | Increase splinter wait time to 15 seconds
@gtrogers
@maxfliri
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -17,7 +17,7 @@
return MongoClient('localhost', 27017)[self.database_name]
def before_scenario(self):
- self.browser = Browser('phantomjs')
+ self.browser = Browser('phantomjs', wait_time=15)
def after_scenario(self):
self.browser.quit() |
9516115f722fb3f95882553d8077bf1ab4a670ef | examples/web_demo/exifutil.py | examples/web_demo/exifutil.py | """
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7... | """
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7... | FIX web_demo upload was not processing grayscale correctly | FIX web_demo upload was not processing grayscale correctly
| Python | bsd-2-clause | wangg12/caffe,longjon/caffe,gnina/gnina,gogartom/caffe-textmaps,wangg12/caffe,tackgeun/caffe,longjon/caffe,wangg12/caffe,tackgeun/caffe,tackgeun/caffe,gogartom/caffe-textmaps,gnina/gnina,tackgeun/caffe,gnina/gnina,CZCV/s-dilation-caffe,gnina/gnina,wangg12/caffe,longjon/caffe,gnina/gnina,gogartom/caffe-textmaps,CZCV/s-d... | ---
+++
@@ -23,7 +23,13 @@
if exif is not None and 274 in exif:
orientation = exif[274]
im = apply_orientation(im, orientation)
- return np.asarray(im).astype(np.float32) / 255.
+ img = np.asarray(im).astype(np.float32) / 255.
+ if img.ndim == 2:
+ img = img[:, :, np... |
cb4c0cb2c35d97e0364a4c010715cdf15d261e4c | basehandler.py | basehandler.py | # -*- conding: utf-8 -*-
import os
import jinja2
import webapp2
import utils
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True)
class BaseHandler(webapp2.RequestHandler):
def render(self, template, **kw):
"""Method render t... | # -*- conding: utf-8 -*-
import os
import jinja2
import webapp2
import utils
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True)
class BaseHandler(webapp2.RequestHandler):
def render(self, template, **kw):
"""Method render t... | Add a method to get username if users have valid cookie | Add a method to get username if users have valid cookie
| Python | mit | lttviet/udacity-final | ---
+++
@@ -31,3 +31,11 @@
"""Set user cookie to empty in headers."""
self.response.headers.add_header('Set-Cookie',
'user=;Path=/')
+
+ def get_username(self):
+ """Check if user has a valid cookie.
+ Returns username if cookie is valid."""... |
d33d7e5bf29d8c135c68eb5f1206d2f7df6f42ed | froide/foirequest/search_indexes.py | froide/foirequest/search_indexes.py | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
status = indexes.CharField(model_attr='status')
fir... | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | Add URL and description to search index of FoiRequest | Add URL and description to search index of FoiRequest | Python | mit | catcosmo/froide,fin/froide,catcosmo/froide,fin/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,okfse/froide,ryankanno/froide,ryankanno/froide,CodeforHawaii/froide,LilithWittmann/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,LilithWittmann/froide,okfse/froide,fin/froide,okfse/froide,Cod... | ---
+++
@@ -7,10 +7,11 @@
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
+ description = indexes.CharField(model_attr='description')
status = indexes.CharField(model_attr='status')
first_... |
4c646128cfcb6d59445890c257447f01ed77a706 | core/management/update_email_forwards.py | core/management/update_email_forwards.py | # Virtual alias file syntax:
# email, space, email, (space, email, space, email,) newline, (repeat)
# Example:
# groep@arenbergorkest.be jef@gmail.com jos@hotmail.com
# jef@arenbergokest.be jef@gmail.com
# Catchall alias email = '@arenbergorkest.be'
from email_aliases import aliases
c = '' # New content of postfi... | # Virtual alias file syntax:
# email, space, email, (space, email, space, email,) newline, (repeat)
# Example:
# groep@arenbergorkest.be jef@gmail.com jos@hotmail.com
# jef@arenbergokest.be jef@gmail.com
# Catchall alias email = '@arenbergorkest.be'
from email_aliases import aliases
c = '' # New content of postfi... | Fix python syntax bug in update email fwd's script | Fix python syntax bug in update email fwd's script
| Python | mit | tfiers/arenberg-online,tfiers/arenberg-online,tfiers/arenberg-online | ---
+++
@@ -10,7 +10,7 @@
c = '' # New content of postfix virtual aliases file
for alias in aliases:
- c += '{} {}\n'.format(alias.email+'@arenbergorkest.be', ' '.join(alias.destinations))
+ c += '{} {}\n'.format(alias['email']+'@arenbergorkest.be', ' '.join(alias['destinations']))
from subprocess import cal... |
f7611e37ef1e0dfaa568515be365d50b3edbd11c | ccdproc/conftest.py | ccdproc/conftest.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... | Fix plugin import for astropy 2.x | Fix plugin import for astropy 2.x
| Python | bsd-3-clause | astropy/ccdproc,mwcraig/ccdproc | ---
+++
@@ -15,6 +15,14 @@
from astropy.tests.pytest_plugins import (pytest_report_header,
PYTEST_HEADER_MODULES,
TESTED_VERSIONS)
+
+try:
+ # This is the way to get plugins in astropy 2.x
+ from astropy.tests.pyt... |
08aa5214a1b1a5fc6872de76b12cf97f5ceb03c9 | pymatgen/ext/tests/test_jhu.py | pymatgen/ext/tests/test_jhu.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import requests
from pymatgen.ext.jhu import get_kpoints
from pymatgen.io.vasp.inputs import Incar
from pymatgen.io.vasp.sets import MPRelaxSet
from pymatgen.util.testing import PymatgenTest
... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import requests
from pymatgen.ext.jhu import get_kpoints
from pymatgen.io.vasp.inputs import Incar
from pymatgen.io.vasp.sets import MPRelaxSet
from pymatgen.util.testing import PymatgenTest
... | Disable JHU kpoint generationt test. | Disable JHU kpoint generationt test.
| Python | mit | gmatteo/pymatgen,vorwerkc/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,gVallverdu/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,davidwaroquiers/pymatgen,gmatteo/pymatgen,davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,gVallverdu/pymatgen,vorwerkc/pymatgen,vorwerkc/pymatge... | ---
+++
@@ -21,7 +21,7 @@
website_is_up = requests.get("http://muellergroup.jhu.edu:8080").status_code == 200
-@unittest.skipIf(not website_is_up, "http://muellergroup.jhu.edu:8080 is down.")
+@unittest.skipIf(True, "This code is way too buggy to be tested.")
class JhuTest(PymatgenTest):
_multiprocess_shar... |
89d9787fc5aa595f6d93d49565313212c2f95b6b | helper_servers/flask_upload.py | helper_servers/flask_upload.py | from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import datetime
import os
def timestamp():
return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/uploads'
@app.route('/', methods=['GET'])
def i... | from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import datetime
import os
def timestamp():
return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/uploads'
@app.route('/', methods=['GET'])
def i... | Add simple form to flask upload server | Add simple form to flask upload server
| Python | bsd-3-clause | stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff | ---
+++
@@ -33,6 +33,13 @@
return redirect(url_for('upload_file'))
return '''
<!doctype html>
- <title>Hi</title>
- Hi
+ <title>Upload</title>
+ <form enctype="multipart/form-data" action="/ul" method="POST">
+ <input type="file" id="file" name="file">
+ <input type="submit">
... |
9f1134174c594564519a88cbfafe443b2be782e2 | python/render/render_tracks.py | python/render/render_tracks.py | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_lab... | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}'.format(metadata['protein'], metadata['serial_number'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = metadata['protein']
d['l... | Update track_name, short_label, and long_label per discussions on 2016-09-09 | Update track_name, short_label, and long_label per discussions on 2016-09-09
| Python | mit | Duke-GCB/TrackHubGenerator,Duke-GCB/TrackHubGenerator | ---
+++
@@ -6,10 +6,10 @@
def generate_track_dict(metadata):
d = dict()
- d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
+ d['track_name'] = '{}_{}'.format(metadata['protein'], metadata['serial_number'])
d['bigbed_url'] = metadata... |
fa5bb37159d09c5bff53b83a4821e3f154892d1d | numba/cuda/device_init.py | numba/cuda/device_init.py | from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudad... | from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudad... | Fix issue with test discovery and broken CUDA drivers. | Fix issue with test discovery and broken CUDA drivers.
This patch allows the test discovery mechanism to work even in the
case of a broken/misconfigured CUDA driver.
Fixes #2841
| Python | bsd-2-clause | sklam/numba,cpcloud/numba,sklam/numba,numba/numba,seibert/numba,jriehl/numba,numba/numba,stuartarchibald/numba,jriehl/numba,IntelLabs/numba,cpcloud/numba,stuartarchibald/numba,gmarkall/numba,IntelLabs/numba,jriehl/numba,seibert/numba,numba/numba,jriehl/numba,gmarkall/numba,numba/numba,sklam/numba,seibert/numba,stuartar... | ---
+++
@@ -23,8 +23,18 @@
This will initialize the driver if it hasn't been initialized.
"""
- return driver.driver.is_available and nvvm.is_available()
+ # whilst `driver.is_available` will init the driver itself,
+ # the driver initialization may raise and as a result break
+ # test discove... |
bf73e73c93c323a6b7395b3a1d40dd55dea4b65a | indra/sources/dgi/__init__.py | indra/sources/dgi/__init__.py | # -*- coding: utf-8 -*-
"""A processor for the `Drug Gene Interaction Database (DGI-DB) <http://www.dgidb.org>`_.
* `Integration of the Drug–Gene Interaction Database (DGIdb 4.0) with open crowdsource efforts
<https://doi.org/10.1093/nar/gkaa1084>`_. Freshour, *et al*. Nucleic Acids Research. 2020 Nov 25.
Interac... | Update init file with descriptions | Update init file with descriptions
| Python | bsd-2-clause | bgyori/indra,johnbachman/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,sorgerlab/indra | ---
+++
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+
+"""A processor for the `Drug Gene Interaction Database (DGI-DB) <http://www.dgidb.org>`_.
+
+* `Integration of the Drug–Gene Interaction Database (DGIdb 4.0) with open crowdsource efforts
+ <https://doi.org/10.1093/nar/gkaa1084>`_. Freshour, *et al*. Nucleic Acid... | |
64a78085fffe8dc525596b870c8e150d9171f271 | resources/site-packages/pulsar/monitor.py | resources/site-packages/pulsar/monitor.py | import xbmc
import urllib2
import threading
from pulsar.config import PULSARD_HOST
class PulsarMonitor(xbmc.Monitor):
def __init__(self):
self._closing = threading.Event()
@property
def closing(self):
return self._closing
def onAbortRequested(self):
self._closing.set()
d... | import xbmc
import urllib2
import threading
from pulsar.config import PULSARD_HOST
class PulsarMonitor(xbmc.Monitor):
def __init__(self):
self._closing = threading.Event()
@property
def closing(self):
return self._closing
def onAbortRequested(self):
# Only when closing Kodi
... | Fix issue where Pulsar would enter a restart loop when cancelling a buffering | Fix issue where Pulsar would enter a restart loop when cancelling a buffering
Signed-off-by: Steeve Morin <7f3ba7bbc079b62d3fe54555c2b0ce0ddda2bb7c@gmail.com>
| Python | bsd-3-clause | likeitneverwentaway/plugin.video.quasar,komakino/plugin.video.pulsar,johnnyslt/plugin.video.quasar,elrosti/plugin.video.pulsar,Zopieux/plugin.video.pulsar,pmphxs/plugin.video.pulsar,johnnyslt/plugin.video.quasar,steeve/plugin.video.pulsar,peer23peer/plugin.video.quasar,peer23peer/plugin.video.quasar,likeitneverwentaway... | ---
+++
@@ -13,7 +13,10 @@
return self._closing
def onAbortRequested(self):
- self._closing.set()
+ # Only when closing Kodi
+ if xbmc.abortRequested:
+ self._closing.set()
+ self._closing.clear()
def onSettingsChanged(self):
try: |
67c98ba67f99d5de5022b32fdb3eb9cd0d96908f | scripts/tappedout.py | scripts/tappedout.py | from binascii import unhexlify
def request(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):
def response(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):... | from binascii import unhexlify
#This can be replace by using the "decode" function on the reponse
def request(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):
flow.request.headers['Accept-Encoding'] = ['']
def response(context, flow):... | Add missing line on the script and some comment | Add missing line on the script and some comment
| Python | apache-2.0 | jstuyck/MitmProxyScripts | ---
+++
@@ -1,10 +1,13 @@
from binascii import unhexlify
+#This can be replace by using the "decode" function on the reponse
def request(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):
-
+ flow.request.headers['Accept-Encod... |
151a5f75a240c875fc591390c208c933e8d0e782 | indra/sources/eidos/eidos_reader.py | indra/sources/eidos/eidos_reader.py | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
in... | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
in... | Update name of Eidos reading class | Update name of Eidos reading class
| Python | bsd-2-clause | johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,pvtodorov/indra | ---
+++
@@ -31,7 +31,7 @@
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
- eidos = autoclass('org.clulab.wm.AgroSystem')
+ eidos = autoclass('org.clulab.wm.EidosSystem')
self.eidos_reader = eidos(autoclass('java.lang.O... |
09ed0e911e530e9b907ac92f2892248b6af245fa | vcr/errors.py | vcr/errors.py | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCassetteException, self).__init__(message)
def _get_message(self, cassette, failed_request):
... | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
self.cassette = kwargs["cassette"]
self.failed_request = kwargs["failed_request"]
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCas... | Add cassette and failed request as properties of thrown CannotOverwriteCassetteException | Add cassette and failed request as properties of thrown CannotOverwriteCassetteException
| Python | mit | kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy | ---
+++
@@ -1,5 +1,7 @@
class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
+ self.cassette = kwargs["cassette"]
+ self.failed_request = kwargs["failed_request"]
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
... |
392f209791eede86d65f018a9b873b33cb7ccb02 | test/test_uniprot_retrieval_data.py | test/test_uniprot_retrieval_data.py | import numpy as np
import pandas as pa
import unittest
import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data
test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/'
class uniprot_retrieval_data_test(unittest.TestCase):
def test_extract_information_from_uniprot(self):
... | import numpy as np
import pandas as pa
import unittest
import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data
test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/'
class uniprot_retrieval_data_test(unittest.TestCase):
def test_extract_information_from_uniprot(self):
... | Fix issue with GO term (unsorted). | Fix issue with GO term (unsorted). | Python | agpl-3.0 | ArnaudBelcour/Workflow_GeneList_Analysis,ArnaudBelcour/Workflow_GeneList_Analysis | ---
+++
@@ -16,5 +16,5 @@
df_result_truth = pa.read_csv(test_data_directory_uniprot + 'result.tsv', sep='\t')
- np.testing.assert_array_equal(df_result['GOs'].tolist(), df_result_truth['GOs'].tolist())
+ np.testing.assert_array_equal(df_result['GOs'].tolist().sort(), df_result_truth['GOs'].... |
e17fe26503e9a72b43c1b9b662dd4319ccff1fd7 | server/__init__.py | server/__init__.py | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import genRESTEndPointsForSlicerCLIsInDocker
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHt... | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import genRESTEndPointsForSlicerCLIsInDocker
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHt... | Use an immutable tagged version of the Docker CLI container | Use an immutable tagged version of the Docker CLI container
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | ---
+++
@@ -20,5 +20,5 @@
info['serverRoot'].girder = girderRoot
genRESTEndPointsForSlicerCLIsInDocker(
- info, 'HistomicsTK', 'dsarchive/histomicstk'
+ info, 'HistomicsTK', 'dsarchive/histomicstk:v0.1.0'
) |
b60fb0db2cc1ab3605f34e9b604e920279434c36 | vterm_test.py | vterm_test.py | #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.F... | #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.F... | Disable mouse handling in vterm example. | Disable mouse handling in vterm example.
| Python | lgpl-2.1 | westurner/urwid,wardi/urwid,zyga/urwid,douglas-larocca/urwid,harlowja/urwid,drestebon/urwid,hkoof/urwid,bk2204/urwid,urwid/urwid,drestebon/urwid,inducer/urwid,hkoof/urwid,hkoof/urwid,bk2204/urwid,rndusr/urwid,rndusr/urwid,zyga/urwid,westurner/urwid,inducer/urwid,rndusr/urwid,mountainstorm/urwid,foreni-packages/urwid,fo... | ---
+++
@@ -31,6 +31,7 @@
loop = urwid.MainLoop(
mainframe,
+ handle_mouse=False,
unhandled_input=quit,
event_loop=event_loop
).run() |
e1fc818b8d563c00c77060cd74d2781b287c0b5d | xnuplot/__init__.py | xnuplot/__init__.py | from .plot import Plot, SPlot
__all__ = ["gnuplot", "numplot"]
| from .plot import Plot, SPlot
__all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
| Include Plot, SPlot in xnuplot.__all__. | Include Plot, SPlot in xnuplot.__all__.
| Python | mit | marktsuchida/Xnuplot | ---
+++
@@ -1,2 +1,2 @@
from .plot import Plot, SPlot
-__all__ = ["gnuplot", "numplot"]
+__all__ = ["Plot", "SPlot", "gnuplot", "numplot"] |
7c37d4f95897ddbc061ec0a84185a19899b85b89 | compile_for_dist.py | compile_for_dist.py | #!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
... | #!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
def main(args=None):... | Update shebang to use /usr/bin/env. | Update shebang to use /usr/bin/env.
Remove the /ms/dist reference.
| Python | apache-2.0 | quattor/aquilon-protocols,quattor/aquilon-protocols | ---
+++
@@ -1,4 +1,4 @@
-#!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
+#!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
# |
6aa8db30afba817ff9b5653480d6f735f09d9c3a | ladder.py | ladder.py | #! /usr/bin/env python3
class Player:
def __init__(self, name, rank):
self.name = name
self.rank = rank
def __repr__(self):
return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank)
def __str__(self):
rank_str = ''
if self.rank ... | #! /usr/bin/env python3
class Player:
def __init__(self, name, rank):
self.name = name
self.rank = rank
def __repr__(self):
return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank)
def __str__(self):
rank_str = ''
if self.rank <... | Add players, match_valid to Ladder | Add players, match_valid to Ladder
-Add rudimentary players() method that creates a set
-Add match_valid() method that *only* checks that players are in
the ladder standings
| Python | agpl-3.0 | massgo/mgaladder,hndrewaall/mgaladder,massgo/mgaladder,massgo/mgaladder,hndrewaall/mgaladder,hndrewaall/mgaladder | ---
+++
@@ -10,14 +10,12 @@
def __repr__(self):
return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank)
-
def __str__(self):
rank_str = ''
if self.rank < 0:
rank_str = '{:d}K'.format(-self.rank)
else:
rank_st... |
17ddd05e35f7cff90530cdb2df0c4971b97e7302 | cmcb/utils.py | cmcb/utils.py | import sys
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwarg... | import sys
import inspect
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function... | Update logging to log async functions properly | Update logging to log async functions properly
| Python | mit | festinuz/cmcb,festinuz/cmcb | ---
+++
@@ -1,4 +1,5 @@
import sys
+import inspect
from functools import wraps, _make_key
import redis
@@ -11,14 +12,29 @@
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
- if log:
- print('calling', function.__name__, args, kwargs, ... |
564bca1e051f6b1cc068d1dd53de55fcf4dc7c6f | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Josh Hagins
# Copyright (c) 2014 Josh Hagins
#
# License: MIT
#
"""This module exports the Scalac plugin class."""
from SublimeLinter.lint import Linter, util
class Scalac(Linter):
"""Provides an interface to... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Josh Hagins
# Copyright (c) 2014 Josh Hagins
#
# License: MIT
#
"""This module exports the Scalac plugin class."""
from SublimeLinter.lint import Linter, util
class Scalac(Linter):
"""Provides an interface to... | Use SublimeLinter-javac as a base | Use SublimeLinter-javac as a base
| Python | mit | jawshooah/SublimeLinter-contrib-scalac | ---
+++
@@ -17,20 +17,60 @@
"""Provides an interface to scalac."""
- syntax = ''
- cmd = 'scalac'
- executable = None
- version_args = '--version'
+ syntax = 'scala'
+ executable = 'scalac'
+ version_args = '-version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
- version_requireme... |
628d65a15b5c51cb7d4a68e1e6babc01a712a538 | src/redevbazaar.py | src/redevbazaar.py | import pyforms
from pyforms import BaseWidget
from pyforms.Controls import ControlText
class WelcomeScreen(BaseWidget):
def __init__(self):
super(WelcomeScreen, self).__init__("TEST1")
self.testText = ControlText("WHERE IS THIS")
if __name__ == "__main__":
pyforms.startApp(WelcomeScreen) | import pyforms
from pyforms import BaseWidget
from pyforms.Controls import ControlText
class WelcomeScreen(BaseWidget):
def __init__(self):
super(WelcomeScreen, self).__init__("TEST1")
self.testText = ControlText("WHERE IS THIS")
self.mainmenu = [
{ 'Home': [
{'My Listings': self.__getlistingsEv... | Add initial file for GUI | Add initial file for GUI
| Python | mit | cgsheeh/SFWR3XA3_Redevelopment,cgsheeh/SFWR3XA3_Redevelopment | ---
+++
@@ -8,5 +8,40 @@
self.testText = ControlText("WHERE IS THIS")
+ self.mainmenu = [
+ { 'Home': [
+ {'My Listings': self.__getlistingsEvent},
+ '-',
+ {'My Orders': self.__getordersEvent},
+ {'Settings': self.__getsettingsEvent}
+ ]
+ },
+ { 'Messages': [
+ {'Inbox': s... |
13b602c50f3be62b2a3a8b267ba00b685fc0c7fe | python/ecep/portal/migrations/0011_auto_20160518_1211.py | python/ecep/portal/migrations/0011_auto_20160518_1211.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_enrollment_info(apps, schema_editor):
"""
Populate the Enrollment info based on static text
"""
Location = apps.get_model('portal', 'Location')
for loc in Location.objects.all():... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_enrollment_info(apps, schema_editor):
"""
Populate the Enrollment info based on static text
"""
Location = apps.get_model('portal', 'Location')
for loc in Location.objects.all():... | Update data migration with new CPS description | Update data migration with new CPS description
| Python | mit | smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning | ---
+++
@@ -12,7 +12,7 @@
for loc in Location.objects.all():
if loc.is_cps_based:
- loc.enrollment_en = """<p>Visit a child-friendly location near you:</p><ul><li><strong>Loop</strong> 42 W. Madison Street Hours: 9:00 AM - 5:00 PM</li><li><strong>Colman</strong> 4655 S. Dearborn Street Hour... |
b286e03f96cce8518dd60b74ff8dac6d7b7c5a97 | octohatrack/helpers.py | octohatrack/helpers.py | #!/usr/bin/env python
import sys
def display_results(repo_name, contributors, api_len):
"""
Fancy display.
"""
print("\n")
print("All Contributors:")
# Sort and consolidate on Name
seen = []
for user in sorted(contributors, key=lambda k: k['name'].lower()):
if user["name"] ... | #!/usr/bin/env python
import sys
def _sort_by_name(contributor):
if contributor.get('name'):
return contributor['name'].lower()
return contributor['user_name']
def display_results(repo_name, contributors, api_len):
"""
Fancy display.
"""
print("\n")
print("All Contributors:")... | Support users with no name | display_results: Support users with no name
A user without a name causes an exception, and
the dedup algorithm also merged users without
a name as all of their names were `None`.
Fixes https://github.com/LABHR/octohatrack/issues/103
| Python | bsd-3-clause | LABHR/octohatrack,glasnt/octohat | ---
+++
@@ -1,6 +1,13 @@
#!/usr/bin/env python
import sys
+
+
+def _sort_by_name(contributor):
+ if contributor.get('name'):
+ return contributor['name'].lower()
+
+ return contributor['user_name']
def display_results(repo_name, contributors, api_len):
@@ -13,10 +20,14 @@
# Sort and conso... |
866f95cfb0db14da0596efe41a128baf2a3a1cfe | django_basic_tinymce_flatpages/admin.py | django_basic_tinymce_flatpages/admin.py | from django.conf import settings
from django.contrib import admin
from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.module_loading import import_string
FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.Tin... | from django.conf import settings
from django.contrib import admin
from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.module_loading import import_string
FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.Tin... | Fix form PageForm needs updating. | Fix form PageForm needs updating.
| Python | bsd-3-clause | ad-m/django-basic-tinymce-flatpages | ---
+++
@@ -17,6 +17,7 @@
widgets = {
'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS),
}
+ fields = '__all__'
class PageAdmin(FlatPageAdmin): |
d1008437dcf618700bce53913f3450aceda8a23f | djangoautoconf/auto_conf_admin_utils.py | djangoautoconf/auto_conf_admin_utils.py | from guardian.admin import GuardedModelAdmin
#from django.contrib import admin
import xadmin as admin
def register_to_sys(class_inst, admin_class = None):
if admin_class is None:
admin_class = type(class_inst.__name__+"Admin", (GuardedModelAdmin, ), {})
try:
admin.site.register(class_inst, ad... | from guardian.admin import GuardedModelAdmin
from django.contrib import admin
#The following not work with guardian?
#import xadmin as admin
def register_to_sys(class_inst, admin_class=None):
if admin_class is None:
admin_class = type(class_inst.__name__ + "Admin", (GuardedModelAdmin, ), {})
try:
... | Remove xadmin as it will not work with guardian. | Remove xadmin as it will not work with guardian.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -1,22 +1,27 @@
from guardian.admin import GuardedModelAdmin
-#from django.contrib import admin
-import xadmin as admin
+from django.contrib import admin
+#The following not work with guardian?
+#import xadmin as admin
-def register_to_sys(class_inst, admin_class = None):
+def register_to_sys(class_i... |
7bfa9d24f7af811746bbb0336b5e75a592cff186 | aws_eis/lib/checks.py | aws_eis/lib/checks.py | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.... | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.... | Fix KeyError: 'version' due to 403 Forbidden error | Fix KeyError: 'version' due to 403 Forbidden error
| Python | mit | jpdoria/aws_eis | ---
+++
@@ -19,13 +19,14 @@
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
- es_version = get_version(endpoint)
- if r.status_code == 200:
- print('ESVersion: {}'.format(es_version))
- print('Connection: OK')
- print('Status: {}\n'.format(r.status_code))
+... |
cd006f8d3885005e867255e63819fc8a5c7430bf | redactor/TextEditor.py | redactor/TextEditor.py | from tkinter import *
class TextEditor():
def __init__(self):
self.root = Tk()
self.root.wm_title("BrickText")
self.text_panel = Text(self.root)
self.text_panel.pack(fill=BOTH, expand=YES)
def start(self):
self.root.mainloop()
def get_root(self):
return se... | from tkinter import *
class TextEditor():
def __init__(self):
self.root = Tk()
self.root.wm_title("BrickText")
self.text_panel = Text(self.root)
self.text_panel.pack(fill=BOTH, expand=YES)
def start(self):
self.root.mainloop()
def get_root(self):
return se... | Add getter for text widget | Add getter for text widget | Python | mit | BrickText/BrickText | ---
+++
@@ -13,6 +13,9 @@
def get_root(self):
return self.root
+
+ def get_text_widget(self):
+ return self.editor
def get_text_panel(self):
return self.text_panel |
7c02a79a5eb2dd6b9b49b2eefbdde1064a73de17 | redpanal/core/forms.py | redpanal/core/forms.py | from django import forms
from django.utils.translation import ugettext as _
from taggit.utils import parse_tags, edit_string_for_tags
class TagParseError(Exception):
pass
def tags_to_editable_string(tags):
return u' '.join([u"#%s" % t for t in tags])
def parse_tags(string):
tags = string.split()
for... | from django import forms
from django.utils.translation import ugettext as _
from taggit.utils import parse_tags, edit_string_for_tags
class TagParseError(Exception):
pass
def tags_to_editable_string(tags):
return u' '.join([u"#%s" % t for t in tags])
def parse_tags(string):
tags = string.split()
for... | Fix exception handling in TagField | Fix exception handling in TagField
| Python | agpl-3.0 | RedPanal/redpanal,RedPanal/redpanal,RedPanal/redpanal | ---
+++
@@ -31,5 +31,5 @@
try:
return parse_tags(value)
except TagParseError as e:
- raise forms.ValidationError(e.msg)
+ raise forms.ValidationError(str(e))
|
ae11251f7669e4ddde6f0491ff1fe0afdfd54a7a | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jsl
# License: MIT
#
"""This module exports the JSL plugin linter class."""
from SublimeLi... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jsl
# License: MIT
#
"""This module exports the JSL plugin linter class."""
from SublimeLi... | Change 'language' to 'syntax', that is more precise terminology. | Change 'language' to 'syntax', that is more precise terminology.
| Python | mit | SublimeLinter/SublimeLinter-jsl | ---
+++
@@ -18,7 +18,7 @@
"""Provides an interface to the jsl executable."""
- language = ('javascript', 'html')
+ syntax = ('javascript', 'html')
cmd = 'jsl -stdin -nologo -nosummary'
regex = r'''(?xi)
# First line is (lineno): type: error message |
8b889c10abf043f6612409973458e8a0f0ed952e | bonus_level.py | bonus_level.py | #!/usr/bin/env python
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
for i... | #!/usr/bin/env python
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
log_c... | Initialize the log counter to 0xFF | Initialize the log counter to 0xFF
| Python | mit | japesinator/Bad-Crypto,japesinator/Bad-Crypto | ---
+++
@@ -9,6 +9,7 @@
secret = input("Please enter your plaintext: ")
for char in secret:
+ log_counter = 0xFF
for i in range(ord(char)):
sleep(0.01)
log_counter ^= i |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.