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 |
|---|---|---|---|---|---|---|---|---|---|---|
0c22d14992427aae0cafb8525cbd11b44761dfd7 | pontoon/administration/management/commands/update_projects.py | pontoon/administration/management/commands/update_projects.py |
import os
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.views import _update_from_repository
from pontoon.base.models import Project
class Command(BaseCommand):
help = 'Update all projects from their repositories an... |
import os
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.views import _update_from_repository
from pontoon.base.models import Project
class Command(BaseCommand):
help = 'Update all projects from their repositories an... | Use project slug as folder name instead of project name | Use project slug as folder name instead of project name
| Python | bsd-3-clause | sudheesh001/pontoon,m8ttyB/pontoon,jotes/pontoon,vivekanand1101/pontoon,Osmose/pontoon,Jobava/mirror-pontoon,mastizada/pontoon,mastizada/pontoon,Jobava/mirror-pontoon,participedia/pontoon,vivekanand1101/pontoon,mathjazz/pontoon,mathjazz/pontoon,Jobava/mirror-pontoon,jotes/pontoon,m8ttyB/pontoon,sudheesh001/pontoon,part... | ---
+++
@@ -18,7 +18,7 @@
repository_type = project.repository_type
repository_url = project.repository_url
repository_path_master = os.path.join(
- settings.MEDIA_ROOT, repository_type, project.name)
+ settings.MEDIA_ROOT, repos... |
08cbb4ebd44b5dca26d55a0e177c03930a2beb57 | stopspam/forms/widgets.py | stopspam/forms/widgets.py | from django import forms
from django.utils.translation import ugettext as _, get_language
from django.utils.safestring import mark_safe
# RECAPTCHA widgets
class RecaptchaResponse(forms.Widget):
def render(self, *args, **kwargs):
from recaptcha.client import captcha as recaptcha
recaptcha_options... | from django import forms
from django.utils.translation import ugettext as _, get_language
from django.utils.safestring import mark_safe
# RECAPTCHA widgets
class RecaptchaResponse(forms.Widget):
is_hidden = True
def render(self, *args, **kwargs):
from recaptcha.client import captcha as recaptcha
... | Fix skipping of recaptcha field widget HTML by marking it is_hidden | Fix skipping of recaptcha field widget HTML by marking it is_hidden
| Python | bsd-3-clause | pombredanne/glamkit-stopspam | ---
+++
@@ -5,10 +5,11 @@
# RECAPTCHA widgets
class RecaptchaResponse(forms.Widget):
+ is_hidden = True
def render(self, *args, **kwargs):
from recaptcha.client import captcha as recaptcha
- recaptcha_options = "<script> var RecaptchaOptions = { theme: '" + self.theme + \
+ recapt... |
3d385898592b07249b478b37854d179d27a27bbb | OmniMarkupLib/Renderers/MarkdownRenderer.py | OmniMarkupLib/Renderers/MarkdownRenderer.py | from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self).load_settings(renderer_options, globa... | from base_renderer import *
import re
import markdown
@renderer
class MarkdownRenderer(MarkupRenderer):
FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')
def load_settings(self, renderer_options, global_setting):
super(MarkdownRenderer, self).load_settings(renderer_opti... | Add litcoffee to Markdown extensions | Add litcoffee to Markdown extensions
| Python | mit | timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer | ---
+++
@@ -5,7 +5,7 @@
@renderer
class MarkdownRenderer(MarkupRenderer):
- FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$')
+ FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')
def load_settings(self, renderer_options, global_setting):
sup... |
2216caf836c1f2864103e8930f60713c226a8464 | src/sql/parse.py | src/sql/parse.py | from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
parser = ConfigParser()
... | from ConfigParser import ConfigParser
from sqlalchemy.engine.url import URL
def parse(cell, config):
parts = [part.strip() for part in cell.split(None, 1)]
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
section = parts[0].lstrip('... | Allow DNS file to be less specific | Allow DNS file to be less specific
| Python | mit | catherinedevlin/ipython-sql,catherinedevlin/ipython-sql | ---
+++
@@ -7,14 +7,12 @@
if not parts:
return {'connection': '', 'sql': ''}
if parts[0].startswith('[') and parts[0].endswith(']'):
+ section = parts[0].lstrip('[').rstrip(']')
parser = ConfigParser()
parser.read(config.dsn_filename)
- section = parts[0].lstrip('[')... |
86bd0e7717596affceb1c40031855635b798e67b | benches/benchmark_rust.py | benches/benchmark_rust.py | import numpy as np
from pypolyline.util import encode_coordinates
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
num_coords = 100
coords = zip(
np.random.uniform(S, N, [num_coords]),
np.random.uniform(W, E, [num_coords])
)
if __name__ ==... | import numpy as np
from pypolyline.cutil import encode_coordinates
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
num_coords = 100
coords = zip(
np.random.uniform(S, N, [num_coords]),
np.random.uniform(W, E, [num_coords])
)
if __name__ =... | Use Cython functions in benchmarks | Use Cython functions in benchmarks
| Python | mit | urschrei/pypolyline,urschrei/pypolyline,urschrei/pypolyline | ---
+++
@@ -1,5 +1,5 @@
import numpy as np
-from pypolyline.util import encode_coordinates
+from pypolyline.cutil import encode_coordinates
# London bounding box
N = 51.691874116909894 |
4522de348aab4cc99904b0bc210c223b2477b4b7 | tests/config.py | tests/config.py | # our constants.
import os
local_path = os.path.dirname(__file__)
xml_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.xml'))
csv_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.csv'))
bathy_raster = os.path.abspath(os.path.join(local_path, 'data', 'bathy5m_cl... | # our constants.
import os
local_path = os.path.dirname(__file__)
xml_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.xml'))
csv_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.csv'))
bathy_raster = os.path.abspath(os.path.join(local_path, 'data', 'bathy5m_cl... | Use pyt file instead of stand-alone tbx for testing. | Use pyt file instead of stand-alone tbx for testing.
| Python | mpl-2.0 | EsriOceans/btm | ---
+++
@@ -8,4 +8,4 @@
csv_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.csv'))
bathy_raster = os.path.abspath(os.path.join(local_path, 'data', 'bathy5m_clip.tif'))
-tbx_file = os.path.abspath(os.path.join(local_path, '..', 'Install', 'toolbox', 'btm_model.tbx'))
+pyt_file = os.path.ab... |
492827e2fc5244c313af4d25b563ad0f69425249 | src/test.py | src/test.py | #!/usr/bin/env python
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
def main():
koeffs = [.3, 1.2, .1, 7]
p = np.poly1d(koeffs)
x = np.linspace(-5, 5, 100)
y = p(x) + 2 * np.random.randn(100) - 1
# fit
fit = np.polyfit(x, y, 3)
p_fit = np.poly1... | #!/usr/bin/env python
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt
def main():
koeffs = [0.3, 1.2, 0.1, 7]
p = np.poly1d(koeffs)
x = np.linspace(-5, 5, 100)
y = p(x) + 2 * np.random.randn(100) - 1
# fit
fit = np.polyfit(x, y, 3)
p_fit = np.pol... | Test change for closing an issue. | Test change for closing an issue.
This is a place for a longer comment. Closes #1
| Python | mit | bbci/playground | ---
+++
@@ -8,7 +8,7 @@
def main():
- koeffs = [.3, 1.2, .1, 7]
+ koeffs = [0.3, 1.2, 0.1, 7]
p = np.poly1d(koeffs)
x = np.linspace(-5, 5, 100)
y = p(x) + 2 * np.random.randn(100) - 1 |
cc7253020251bc96d7d7f22a991b094a60bbc104 | startServers.py | startServers.py |
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand... |
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linux... | Revert "keep servers running for fun and profit" | Revert "keep servers running for fun and profit"
This reverts commit c574ba41fb609db7a2c75340363fe1a1dcc31399.
| Python | mit | IngenuityEngine/coren_proxy,IngenuityEngine/coren_proxy | ---
+++
@@ -2,32 +2,23 @@
import sys
import time
import subprocess
-import psutil
-
-def startServer(command):
- if sys.platform.startswith('win'):
- return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
- else:
- linuxCommand = 'xterm -hold -e "%s"' % command
- return psutil.Popen(linuxComm... |
6ac172843dc78ae6af87f00b260ef70f8965b3b7 | start_server.py | start_server.py | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | #!/usr/bin/env python3
# tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | Handle case where pip is not found | Handle case where pip is not found
| Python | agpl-3.0 | Attorney-Online-Engineering-Task-Force/tsuserver3,Mariomagistr/tsuserver3 | ---
+++
@@ -17,7 +17,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-from server.tsuserver import TsuServer3
# Idiotproof setup
def check_pyyaml():
@@ -25,10 +24,14 @@
import yaml
except ModuleNotFo... |
e54fa97cb44557454655efd24380da5223a1c5ae | tests/random_object_id/random_object_id_test.py | tests/random_object_id/random_object_id_test.py | import contextlib
import re
import sys
import mock
from six.moves import cStringIO
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
new_out = StringIO()
old_out = sys.stdout
try:
sys.stdout = new_out
... | import contextlib
import re
import sys
import mock
import six
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
old_out = sys.stdout
try:
sys.stdout = six.StringIO()
yield sys.stdout
finally:
... | Change how StringIO is imported | Change how StringIO is imported
| Python | mit | mxr/random-object-id | ---
+++
@@ -3,7 +3,7 @@
import sys
import mock
-from six.moves import cStringIO
+import six
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@@ -11,10 +11,9 @@
@contextlib.contextmanager
def captured_output():
- new_out = StringIO()
old_out = sys.stdout
... |
eb34aadfcab01da9783688ffc72e23b0264713ad | spec/unit/hooks/for_caller.py | spec/unit/hooks/for_caller.py |
import os
import sys
import json
#
# input (stdin)
message = sys.stdin.read()
message = json.loads(message)
message["point"] = "receive"
message["payload"]["price"] = "CHF 5.00"
#
# other inputs
if len(sys.argv) > 1:
message["argument"] = sys.argv[1]
fcv = os.environ.get('ENV_VAR')
if fcv:
message["env_var"]... |
import os
import sys
import json
#
# input (stdin)
message = sys.stdin.read()
message = json.loads(message)
message["point"] = "receive"
message["payload"]["price"] = "CHF 5.00"
#
# other inputs
if len(sys.argv) > 1: message["argument"] = sys.argv[1]
fcv = os.environ.get('ENV_VAR')
if fcv: message["env_var"] = f... | Use if oneliners in Python caller sample | Use if oneliners in Python caller sample
| Python | mit | dmicky0419/flor,floraison/flor,floraison/flor,dmicky0419/flor,flon-io/flor,dmicky0419/flor,floraison/flor | ---
+++
@@ -15,12 +15,10 @@
#
# other inputs
-if len(sys.argv) > 1:
- message["argument"] = sys.argv[1]
+if len(sys.argv) > 1: message["argument"] = sys.argv[1]
fcv = os.environ.get('ENV_VAR')
-if fcv:
- message["env_var"] = fcv
+if fcv: message["env_var"] = fcv
#
# output |
bb07ae592fbeb51a55b619a9880f4afc57bedee4 | jwt_knox/urls.py | jwt_knox/urls.py | """jwt_knox urls.py
"""
from django.conf.urls import url, include
from django.contrib import admin
from .views import DebugVerifyTokenView, LoginView, LogoutView, LogoutOtherView, LogoutAllView, VerifyView
urlpatterns = [
url(r'^get_token$', LoginView.as_view()),
url(r'^verify$', VerifyView.as_view()),
... | """jwt_knox urls.py
"""
from django.conf.urls import url, include
from django.contrib import admin
from .views import DebugVerifyTokenView, LoginView, LogoutView, LogoutOtherView, LogoutAllView, VerifyView
app_name = 'jwt_knox'
urlpatterns = [
url(r'^get_token$', LoginView.as_view(), name='get_new_token'),
... | Add names to URLs in JWT-Knox | Add names to URLs in JWT-Knox
| Python | agpl-3.0 | gpul-org/xea-core | ---
+++
@@ -7,11 +7,14 @@
from .views import DebugVerifyTokenView, LoginView, LogoutView, LogoutOtherView, LogoutAllView, VerifyView
+
+app_name = 'jwt_knox'
+
urlpatterns = [
- url(r'^get_token$', LoginView.as_view()),
- url(r'^verify$', VerifyView.as_view()),
- url(r'^debug$', DebugVerifyTokenView.as... |
80da397eb882622bc0bf1641bc4ee4e5813cf655 | lopypi/pypi.py | lopypi/pypi.py | import re
from urlparse import urlsplit
from bs4 import BeautifulSoup
import requests
from urlparse import urldefrag, urljoin
class PyPI(object):
def __init__(self, index="http://pypi.python.org/simple"):
self._index = index
def list_packages(self):
resp = requests.get(self._index)
s... | import re
from urlparse import urlsplit
from bs4 import BeautifulSoup
import requests
from urlparse import urldefrag, urljoin
class PyPI(object):
def __init__(self, index="http://pypi.python.org/simple"):
self._index = index
def list_packages(self):
resp = requests.get(self._index)
s... | Replace reference to previously factored out variable | Replace reference to previously factored out variable
| Python | mit | bwhmather/LoPyPI,bwhmather/LoPyPI | ---
+++
@@ -12,7 +12,7 @@
def list_packages(self):
resp = requests.get(self._index)
- soup = BeautifulSoup(package_list)
+ soup = BeautifulSoup(resp.content)
for link in soup.find_all("a"):
yield link.text |
4b6ae0eb113689515ba38e85c33a2ba40e58a163 | src/minerva/storage/trend/engine.py | src/minerva/storage/trend/engine.py | from contextlib import closing
from operator import contains
from functools import partial
from minerva.util import k, identity
from minerva.directory import EntityType
from minerva.storage import Engine
from minerva.storage.trend import TableTrendStore
class TrendEngine(Engine):
@staticmethod
def store_cmd(... | from contextlib import closing
from operator import contains
from functools import partial
from minerva.util import k, identity
from minerva.directory import EntityType
from minerva.storage import Engine
from minerva.storage.trend import TableTrendStore
class TrendEngine(Engine):
@staticmethod
def store_cmd(... | Rename parameter filter_package to a more appropriate transform_package | Rename parameter filter_package to a more appropriate transform_package
| Python | agpl-3.0 | hendrikx-itc/minerva,hendrikx-itc/minerva | ---
+++
@@ -10,12 +10,12 @@
class TrendEngine(Engine):
@staticmethod
- def store_cmd(package, filter_package=k(identity)):
+ def store_cmd(package, transform_package=k(identity)):
"""
Return a function to bind a data source to the store command.
:param package: A DataPackage... |
1db5ed3fa2fbb724c480bbf52c1d40c390dc857f | examples/example1.py | examples/example1.py | import fte.encoder
regex = '^(a|b)+$'
fixed_slice = 512
input_plaintext = 'test'
fteObj = fte.encoder.RegexEncoder(regex, fixed_slice)
ciphertext = fteObj.encode(input_plaintext)
output_plaintext = fteObj.decode(ciphertext)
print 'regex='+regex
print 'fixed_slice='+str(fixed_slice)
print 'input_plaintext='+input_pl... | import regex2dfa
import fte.encoder
regex = '^(a|b)+$'
fixed_slice = 512
input_plaintext = 'test'
dfa = regex2dfa.regex2dfa(regex)
fteObj = fte.encoder.DfaEncoder(dfa, fixed_slice)
ciphertext = fteObj.encode(input_plaintext)
[output_plaintext, remainder] = fteObj.decode(ciphertext)
print 'input_plaintext='+input_pl... | Update example code to represent current FTE API and usage. | Update example code to represent current FTE API and usage.
| Python | apache-2.0 | kpdyer/libfte,kpdyer/libfte | ---
+++
@@ -1,16 +1,16 @@
+import regex2dfa
import fte.encoder
regex = '^(a|b)+$'
fixed_slice = 512
input_plaintext = 'test'
-fteObj = fte.encoder.RegexEncoder(regex, fixed_slice)
+dfa = regex2dfa.regex2dfa(regex)
+fteObj = fte.encoder.DfaEncoder(dfa, fixed_slice)
ciphertext = fteObj.encode(input_plaintext... |
f38b117316039042f3c00c73bbb7ceaeb0f2e6e1 | src/python/pants/core_tasks/noop.py | src/python/pants/core_tasks/noop.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.task.noop... | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.task.noop... | Add public api markers for core_tasks | Add public api markers for core_tasks
The following modules were reviewed and all api's were left as private. As
far as I can tell these modules are not currently used by plugins.
* pants.core_tasks.bash_completion.py
* pants.core_tasks.changed_target_tasks.py
* pants.core_tasks.clean.py
* pants.core_tasks.deferred_s... | Python | apache-2.0 | manasapte/pants,twitter/pants,fkorotkov/pants,jsirois/pants,pantsbuild/pants,peiyuwang/pants,pombredanne/pants,cevaris/pants,fkorotkov/pants,mateor/pants,baroquebobcat/pants,gmalmquist/pants,peiyuwang/pants,fkorotkov/pants,wisechengyi/pants,fkorotkov/pants,UnrememberMe/pants,wisechengyi/pants,ericzundel/pants,ericzunde... | ---
+++
@@ -9,7 +9,10 @@
class NoopCompile(NoopExecTask):
- """A no-op that provides a product type that can be used to force scheduling."""
+ """A no-op that provides a product type that can be used to force scheduling.
+
+ :API: public
+ """
@classmethod
def product_types(cls):
@@ -17,7 +20,10 @@
... |
6837986db77c9c9bd85392a74faebc019c1395a1 | swen/flowexecutor.py | swen/flowexecutor.py | from . import flow
class FlowExecutor:
"""
This class is responsible for flow execution
"""
def __init__(self, yaml_data):
self.flow = flow.Flow(yaml_data)
def execute(self):
(exit_code, stdout, stderr) = None, None, None
for step in self.flow.next_step():
if... | from . import flow
import logging
class FlowExecutor:
"""
This class is responsible for flow execution
"""
def __init__(self, yaml_data):
self.flow = flow.Flow(yaml_data)
def execute(self):
(exit_code, stdout, stderr) = None, None, None
for step in self.flow.next_step():... | Add debug logging to flow executor | Add debug logging to flow executor
| Python | mit | unix-beard/swen,unix-beard/swen,unix-beard/swen | ---
+++
@@ -1,4 +1,5 @@
from . import flow
+import logging
class FlowExecutor:
@@ -16,8 +17,10 @@
if step.step is not None:
(exit_code, stdout, stderr) = step.execute(exit_code=exit_code, stdout=stdout, stderr=stderr)
+ logging.debug("Executed step:... |
a4184edab35890673b8b6a67e68a73e6ab7f0b89 | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | Add back in running of extra tests | Add back in running of extra tests
| Python | bsd-3-clause | jmagnusson/wtforms,cklein/wtforms,Xender/wtforms,pawl/wtforms,Aaron1992/wtforms,pawl/wtforms,subyraman/wtforms,wtforms/wtforms,skytreader/wtforms,hsum/wtforms,Aaron1992/wtforms,crast/wtforms | ---
+++
@@ -20,7 +20,7 @@
def main():
extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x)
- suite = make_suite('', )
+ suite = make_suite('', extra_tests)
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
e452bee7b2babeec427a84e82ee3b4046f242bfc | process_urls.py | process_urls.py | #!/usr/bin/env python
import os
import sys
import subprocess
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
with open(sys.argv[1], 'r') as handle:
for line in handle:
if line.startswith('#'):
continue
data = line.strip().split('\t')
sha = data... | #!/usr/bin/env python
import os
import sys
import subprocess
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
with open(sys.argv[1], 'r') as handle:
print """<!DOCTYPE html><html><head><title>Galaxy Package
Cache</title></head><body><h1>About</h1><p>This package cache serves t... | Update to have html output | Update to have html output
| Python | mit | galaxyproject/cargo-port,galaxyproject/cargo-port,erasche/community-package-cache,erasche/community-package-cache,gregvonkuster/cargo-port,erasche/community-package-cache,gregvonkuster/cargo-port,gregvonkuster/cargo-port | ---
+++
@@ -6,14 +6,23 @@
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
+
with open(sys.argv[1], 'r') as handle:
+ print """<!DOCTYPE html><html><head><title>Galaxy Package
+ Cache</title></head><body><h1>About</h1><p>This package cache serves to
+ preserve packages permanently. Ple... |
52ddec80be8e2c90807a7b07425a6f260c9e86e0 | src/zeit/retresco/tests/test_tag.py | src/zeit/retresco/tests/test_tag.py | # coding: utf8
import unittest
class TagTest(unittest.TestCase):
"""Testing ..tag.Tag."""
def test_from_code_generates_a_tag_object_equal_to_its_source(self):
from ..tag import Tag
tag = Tag(u'Vipraschül', 'Person')
self.assertEqual(tag, Tag.from_code(tag.code))
| # coding: utf8
import zeit.cms.interfaces
import zeit.retresco.testing
class TagTest(zeit.retresco.testing.FunctionalTestCase):
"""Testing ..tag.Tag."""
def test_from_code_generates_a_tag_object_equal_to_its_source(self):
from ..tag import Tag
tag = Tag(u'Vipraschül', 'Person')
self.a... | Test that adapter in `zeit.cms` handles unicode escaped uniqueId correctly. | ZON-3199: Test that adapter in `zeit.cms` handles unicode escaped uniqueId correctly.
| Python | bsd-3-clause | ZeitOnline/zeit.retresco | ---
+++
@@ -1,11 +1,17 @@
# coding: utf8
-import unittest
+import zeit.cms.interfaces
+import zeit.retresco.testing
-class TagTest(unittest.TestCase):
+class TagTest(zeit.retresco.testing.FunctionalTestCase):
"""Testing ..tag.Tag."""
def test_from_code_generates_a_tag_object_equal_to_its_source(self)... |
0b6e0e09abd007dad504693ca8cae4c7b0222765 | gamernews/apps/threadedcomments/views.py | gamernews/apps/threadedcomments/views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | Remove name, url and email from comment form | Remove name, url and email from comment form
| Python | mit | underlost/GamerNews,underlost/GamerNews | ---
+++
@@ -16,8 +16,7 @@
def comment_posted(request):
if request.GET['c']:
- comment_id, blob_id = request.GET['c']
- comment = Comment.objects.get( pk=comment_id )
+ blob_id = request.GET['c']
blob = Blob.objects.get(pk=blob_id)
if blob: |
716c0c4ab08266ce42f65afc0cd4bd8e0ed191e0 | table_parser.py | table_parser.py | #!/usr/bin/python
import sys
import latex_table
import table_to_file
if __name__ == "__main__":
# Parse arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input", help="the LaTeX input file to be parsed")
# Add two mutually exclusive arguments: grouped/ungrouped
... | #!/usr/bin/python
import sys
import latex_table
import table_to_file
if __name__ == "__main__":
# Parse arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input", help="the LaTeX input file to be parsed")
# Add two mutually exclusive arguments: grouped/ungrouped
... | Remove exit statement and error message for tex output | Remove exit statement and error message for tex output
| Python | mit | knutzk/parse_latex_table | ---
+++
@@ -34,9 +34,7 @@
if args.json_file:
table_to_file.storeJSON(table, args.json_file)
if args.tex_file:
- print "Printing to TEX file not yet implemented"
table_to_file.storeTEX(table, args.tex_file)
- sys.exit(1)
for row in rows:
for column in columns: |
a0fa76a7aeb3dba3b358abeab95fc03a90a0e8b6 | members/views.py | members/views.py | from django.shortcuts import render
def homepage(request):
return render(request, "index.html", {})
| from django.shortcuts import render
from django.http import HttpResponse
from .models import User
def homepage(request):
return render(request, "index.html", {})
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) ... | Add view for searching users and return json format | Add view for searching users and return json format
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -1,5 +1,21 @@
from django.shortcuts import render
+from django.http import HttpResponse
+
+from .models import User
def homepage(request):
return render(request, "index.html", {})
+
+
+def search(request, name):
+ members = User.objects.filter(first_name__icontains=name) or \
+ User.ob... |
4e31496e1d9e0b2af2ce8aa4bb58baa86f352521 | flake8_docstrings.py | flake8_docstrings.py | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.2'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __versio... | # -*- coding: utf-8 -*-
"""Implementation of pep257 integration with Flake8.
pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.2'
class pep257Checker(object):
"""Flake8 needs a class to check python fi... | Fix up a couple of minor issues | Fix up a couple of minor issues
| Python | mit | PyCQA/flake8-docstrings | ---
+++
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
-"""pep257 docstrings convention needs error code and class parser for be
+"""Implementation of pep257 integration with Flake8.
+
+pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
@@ -11,15 +13,15 @@
... |
e5ef9ca9c089ce1da4ff363d0c5a5090785ae0c5 | test_scraper.py | test_scraper.py | from scraper import search_CL
from scraper import read_search_results
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_... | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert t... | Add test for extract listings that asserts each listing is a bs4.element.Tag | Add test for extract listings that asserts each listing is a bs4.element.Tag
| Python | mit | jefrailey/basic-scraper | ---
+++
@@ -1,9 +1,12 @@
from scraper import search_CL
from scraper import read_search_results
+from scraper import parse_source
+from scraper import extract_listings
+import bs4
def test_search_CL():
- test_body, test_encoding = search_CL(minAsk=100)
+ test_body, test_encoding = search_CL(minAsk=100, ma... |
aca158817c21b8baeeb64d7290d61c32a79124f9 | tests/test_heat_demand.py | tests/test_heat_demand.py | """
Test the electricity demand
SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de>
SPDX-FileCopyrightText: Patrik Schönfeldt
SPDX-License-Identifier: MIT
"""
import numpy as np
from demandlib.examples import heat_demand_example
def test_heat_example():
"""Test the results of the heat example."""
ann... | """
Test the electricity demand
SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de>
SPDX-FileCopyrightText: Patrik Schönfeldt
SPDX-License-Identifier: MIT
"""
import numpy as np
from demandlib.examples import heat_demand_example
def test_heat_example():
"""Test the results of the heat example."""
ann... | Increase tollerance for heat demand test | Increase tollerance for heat demand test
| Python | mit | oemof/demandlib | ---
+++
@@ -24,4 +24,4 @@
testmode=True).sum()
for key in ann_demands_per_type:
- assert np.isclose(demands[key], ann_demands_per_type[key])
+ assert np.isclose(demands[key], ann_demands_per_type[key], rtol=1e-04) |
101b4e5fb29195e500103230b3bbdae2369fde75 | tests/test_mal_scraper.py | tests/test_mal_scraper.py | import mal_scraper
def test_import_mal_scraper():
"""Can we import mal_scraper"""
assert mal_scraper
assert mal_scraper.__version__.split('.') == ['0', '1', '0']
class TestAutomaticUserDicoveryIntegration(object):
"""Can we discover users as we download pages?"""
pass # TODO
| import mal_scraper
def test_import_mal_scraper():
"""Can we import mal_scraper"""
assert mal_scraper
assert mal_scraper.__version__.split('.') == ['0', '2', '0']
class TestAutomaticUserDicoveryIntegration(object):
"""Can we discover users as we download pages?"""
pass # TODO
| Fix failing tests (version number) | Fix failing tests (version number)
| Python | mit | QasimK/mal-scraper | ---
+++
@@ -4,7 +4,7 @@
def test_import_mal_scraper():
"""Can we import mal_scraper"""
assert mal_scraper
- assert mal_scraper.__version__.split('.') == ['0', '1', '0']
+ assert mal_scraper.__version__.split('.') == ['0', '2', '0']
class TestAutomaticUserDicoveryIntegration(object): |
0060a32b58c7769ac97ac894cbaf6a2eaa1b389f | mmiisort/main.py | mmiisort/main.py | from isort import SortImports
import mothermayi.colors
import mothermayi.errors
import mothermayi.files
def plugin():
return {
'name' : 'isort',
'pre-commit' : pre_commit,
}
def do_sort(filename):
results = SortImports(filename)
return getattr(results, 'in_lines', None) and... | from isort import SortImports
import mothermayi.colors
import mothermayi.errors
import mothermayi.files
def plugin():
return {
'name' : 'isort',
'pre-commit' : pre_commit,
}
def do_sort(filename):
results = SortImports(filename, check=True)
return results.incorrectly_sorted... | Leverage isort's check mode to make our logic simpler | Leverage isort's check mode to make our logic simpler
This avoids having to check for in_lines or compare against the
out_lines by just asking for a check and using the results
| Python | mit | EliRibble/mothermayi-isort | ---
+++
@@ -10,8 +10,8 @@
}
def do_sort(filename):
- results = SortImports(filename)
- return getattr(results, 'in_lines', None) and results.in_lines != results.out_lines
+ results = SortImports(filename, check=True)
+ return results.incorrectly_sorted
def get_status(had_changes):
return m... |
ed76f648f60f96216377e4f12fea7043eaed904b | tests/helpers.py | tests/helpers.py | import virtualbox
def list_machines():
vbox = virtualbox.vb_get_manager()
for machine in vbox.getArray(vbox, "Machines"):
print "Machine '%s' logs in '%s'" % (
machine.name,
machine.logFolder
)
| import unittest
import virtualbox
class VirtualboxTestCase(unittest.TestCase):
def setUp(self):
self.vbox = virtualbox.vb_get_manager()
def assertMachineExists(self, name, msg=None):
try:
self.vbox.findMachine(name)
except Exception as e:
if msg:
... | Create a basic VirtualBoxTestCase with helper assertions | Create a basic VirtualBoxTestCase with helper assertions
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -1,4 +1,22 @@
+import unittest
import virtualbox
+
+
+class VirtualboxTestCase(unittest.TestCase):
+ def setUp(self):
+ self.vbox = virtualbox.vb_get_manager()
+
+ def assertMachineExists(self, name, msg=None):
+ try:
+ self.vbox.findMachine(name)
+ except Exception a... |
990a3266739e5a4d763dd585f7cb722c0fe2b0f5 | astroplpython/function/statistic/Maximum.py | astroplpython/function/statistic/Maximum.py | '''
Created on Feb 6, 2015
@author: thomas
'''
class Maximum (object):
@staticmethod
def calculate (measurement_list):
import numpy as np
'''
Find the maximum measurement value for any list of
measured values.
'''
x = []
for val in measurement_list:
... | '''
Created on Feb 6, 2015
@author: thomas
'''
class Maximum (object):
@staticmethod
def calculate (measurement_list):
import numpy as np
'''
Find the maximum measurement value for any list of
measured values.
'''
x = []
for val in measurement_list:
... | Remove initializer..this is a 'static' class which | Remove initializer..this is a 'static' class which
we are using functional approach with, e.g. no instances
if we can help it..
| Python | mit | brianthomas/astroplpython,brianthomas/astroplpython | ---
+++
@@ -19,8 +19,3 @@
return measurement_list[np.argmax(x)]
- def __init__(self, ndarray):
- '''
- Constructor
- '''
- |
554ef995f8c4ba42d00482480bf291bac2fd96e1 | utils/database.py | utils/database.py | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | Reduce code to a simpler form that checks if a user is already in the DB | Reduce code to a simpler form that checks if a user is already in the DB
| Python | mit | wolfy1339/Python-IRC-Bot | ---
+++
@@ -23,16 +23,11 @@
'account': account,
'seen': [__import__("time").time(), ""]
}
- failed = False
- try:
- user = self[channel][nick]
- except KeyError:
- failed = True
+ if nick in self[channel]:
+ del temp['seen... |
12f3cc403f6ba0be957d1fb18253fb7529009764 | moss/plotting.py | moss/plotting.py | import matplotlib.pyplot as plt
def grid_axes_labels(f, xlabel=None, ylabel=None, **kws):
axes = f.axes
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
... | import matplotlib.pyplot as plt
def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws):
plt.setp(axes.flat, xlabel="", ylabel="")
if xlabel is not None:
for ax in axes[-1]:
ax.set_xlabel(xlabel, **kws)
if ylabel is not None:
for ax in axes[0]:
ax.set_ylabel(... | Use matrix of axes not figure | Use matrix of axes not figure
| Python | bsd-3-clause | mwaskom/moss,mwaskom/moss | ---
+++
@@ -1,9 +1,7 @@
import matplotlib.pyplot as plt
-def grid_axes_labels(f, xlabel=None, ylabel=None, **kws):
-
- axes = f.axes
+def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws):
plt.setp(axes.flat, xlabel="", ylabel="")
|
acdbb1a9ca73b43b2a56b9372ded6859f5945721 | bpython/test/test_autocomplete.py | bpython/test/test_autocomplete.py | from bpython import autocomplete
import unittest
try:
from unittest import skip
except ImportError:
def skip(f):
return lambda self: None
#TODO: Parts of autocompletion to test:
# Test that the right matches come back from find_matches (test that priority is correct)
# Test the various complete method... | from bpython import autocomplete
import unittest
try:
from unittest import skip
except ImportError:
def skip(f):
return lambda self: None
#TODO: Parts of autocompletion to test:
# Test that the right matches come back from find_matches (test that priority is correct)
# Test the various complete method... | Make test work under Python 2.6. | Make test work under Python 2.6.
| Python | mit | wevial/bpython,aktorion/bpython,wevial/bpython,kdart/bpython,aktorion/bpython,kdart/bpython | ---
+++
@@ -14,8 +14,8 @@
class TestSafeEval(unittest.TestCase):
def test_catches_syntax_error(self):
- with self.assertRaises(autocomplete.EvaluationError):
- autocomplete.safe_eval('1re',{})
+ self.assertRaises(autocomplete.EvaluationError,
+ autocomplete.sa... |
ba2938267ac6198242e101d091339152767df557 | calexicon/fn/tests/test_julian.py | calexicon/fn/tests/test_julian.py | import unittest
from calexicon.calendars.tests.test_calendar import JulianGregorianConversion
from calexicon.fn import julian_to_gregorian, gregorian_to_julian
from calexicon.fn import julian_to_julian_day_number, julian_day_number_to_julian
class TestJulianConversion(JulianGregorianConversion):
def setUp(self)... | import unittest
from calexicon.calendars.tests.test_calendar import JulianGregorianConversion
from calexicon.fn import julian_to_gregorian, gregorian_to_julian
from calexicon.fn import julian_to_julian_day_number, julian_day_number_to_julian
class TestJulianConversion(JulianGregorianConversion):
def setUp(self)... | Correct test to match the inverse test. | Correct test to match the inverse test.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -31,4 +31,4 @@
self.assertEqual(julian_to_julian_day_number(-4712, 1, 1), 365)
def test_julian_date_to_number(self):
- self.assertEqual(julian_day_number_to_julian(1), (-4713, 1, 1))
+ self.assertEqual(julian_day_number_to_julian(0), (-4713, 1, 1)) |
02e03748e66ebf516a4a9b24f52563362e6bb895 | command_line/scale_down_images.py | command_line/scale_down_images.py | from __future__ import division
def nproc():
from libtbx.introspection import number_of_processors
return number_of_processors(return_value_if_unknown=-1)
def joiner(args):
from dials.util.scale_down_image import scale_down_image
scale_down_image(*args)
def scale_down_images(in_template, out_template, start,... | from __future__ import division
def nproc():
from libtbx.introspection import number_of_processors
return number_of_processors(return_value_if_unknown=-1)
def joiner(args):
from dials.util.scale_down_image import scale_down_image
scale_down_image(*args)
print args[1]
def scale_down_images(in_template, out_... | Print out file name after writing | Print out file name after writing | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | ---
+++
@@ -7,6 +7,7 @@
def joiner(args):
from dials.util.scale_down_image import scale_down_image
scale_down_image(*args)
+ print args[1]
def scale_down_images(in_template, out_template, start, end, scale_factor):
from multiprocessing import Pool |
49ce9aa1bdd3479c31b8aa2e606b1768a444aea2 | irrigator_pro/farms/templatetags/today_filters.py | irrigator_pro/farms/templatetags/today_filters.py | from django import template
from datetime import date, datetime, timedelta
register = template.Library()
@register.filter(expects_localtime=True)
def is_today(value):
if isinstance(value, datetime):
value = value.date()
return value == date.today()
@register.filter(expects_localtime=True)
def is_past... | from django import template
from datetime import date, datetime, timedelta
register = template.Library()
@register.filter(expects_localtime=True)
def is_today(value):
if isinstance(value, datetime):
value = value.date()
return value == date.today()
@register.filter(expects_localtime=True)
def is_past... | Add new filter to determine if today is within the time period for a season. | Add new filter to determine if today is within the time period for a season.
| Python | mit | warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro | ---
+++
@@ -26,3 +26,10 @@
if isinstance(value, datetime):
value = value.date()
return value - date.today()
+
+@register.filter(expects_locattime=True)
+def today_in_season(season):
+ start_date = season.season_start_date
+ end_date = season.season_end_date
+ return (start_date <= date.t... |
0e0b96d0d800716102204cfdca7317ccb92cee95 | pytextql/util.py | pytextql/util.py | # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chun... | # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chun... | Add a simple UnicodeCSVWriter, probably flawed. | Add a simple UnicodeCSVWriter, probably flawed.
| Python | mit | TkTech/pytextql | ---
+++
@@ -48,3 +48,18 @@
@property
def line_num(self):
return self.reader.line_num
+
+
+class UnicodeCSVWriter(object):
+ def __init__(self, *args, **kwargs):
+ self.encoding = kwargs.pop('encoding', 'utf8')
+ self.writer = csv.writer(*args, **kwargs)
+
+ def writerow(self, ro... |
c67acb72d5ddea8a1e4fb8a12aa3a6913629e0cb | Lib/setup.py | Lib/setup.py |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
#config.add_subpackage('cluster')
#config.add_subpackage('fftpack')
#config.add_subpackage('integrate')
#config.add_subpackage('interpo... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
config.add_subpackage('cluster')
config.add_subpackage('fftpack')
config.add_subpackage('integrate')
config.add_subpackage('interpolate... | Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too. | Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@2022 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor | ---
+++
@@ -2,25 +2,25 @@
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
- #config.add_subpackage('cluster')
- #config.add_subpackage('fftpack')
- #config.add_subpackage('integrate')
- ... |
1441654c46e08b7286999b6887e59c56fa238ff7 | python/piling-up.py | python/piling-up.py | from collections import deque
def isVerticallyStackable(pile):
vertical_stack = []
while pile:
largest_cube, cube_sizes = remove_largest_cube_from_pile(pile)
if vertical_stack == []:
vertical_stack.append(largest_cube)
else:
top_of_stack = vertical_stack[-1]
... | from collections import deque
def isVerticallyStackable(pile):
vertical_stack = []
while pile:
largest_cube = remove_largest_cube_from_pile(pile)
if vertical_stack == []:
vertical_stack.append(largest_cube)
else:
top_of_stack = vertical_stack[-1]
if(... | Remove returned pile b/c mutating directly | Remove returned pile b/c mutating directly
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | ---
+++
@@ -4,7 +4,7 @@
def isVerticallyStackable(pile):
vertical_stack = []
while pile:
- largest_cube, cube_sizes = remove_largest_cube_from_pile(pile)
+ largest_cube = remove_largest_cube_from_pile(pile)
if vertical_stack == []:
vertical_stack.append(largest_cube)
... |
bb229be50e37bb710c32541cec7b159da9508335 | tests/functional/subcommands/test_subcommands.py | tests/functional/subcommands/test_subcommands.py | import subprocess
def test_subcommand():
"""
Test that a command from the example project is registered.
"""
output = subprocess.check_output(['textx'], stderr=subprocess.STDOUT)
assert b'testcommand' in output
def test_subcommand_group():
"""
Test that a command group is registered.
... | import sys
import pytest
import subprocess
if (3, 6) <= sys.version_info < (3, 8):
pytest.skip("Temporary workaround for Travis problems", allow_module_level=True)
def test_subcommand():
"""
Test that a command from the example project is registered.
"""
output = subprocess.check_output(['textx'... | Add workaround for Travis CI problems | Add workaround for Travis CI problems
| Python | mit | igordejanovic/textX,igordejanovic/textX,igordejanovic/textX | ---
+++
@@ -1,4 +1,10 @@
+import sys
+import pytest
import subprocess
+
+
+if (3, 6) <= sys.version_info < (3, 8):
+ pytest.skip("Temporary workaround for Travis problems", allow_module_level=True)
def test_subcommand(): |
82f7a48695bc1dd97f9ab2697548f15b124dc82a | pyoracc/atf/atffile.py | pyoracc/atf/atffile.py | from .atflex import AtfLexer
from .atfyacc import AtfParser
from mako.template import Template
class AtfFile(object):
template = Template("${text.serialize()}")
def __init__(self, content):
self.content = content
if content[-1] != '\n':
content += "\n"
lexer = AtfLexer().... | from .atflex import AtfLexer
from .atfyacc import AtfParser
from mako.template import Template
class AtfFile(object):
template = Template("${text.serialize()}")
def __init__(self, content):
self.content = content
if content[-1] != '\n':
content += "\n"
lexer = AtfLexer().... | Correct typo in debug function | Correct typo in debug function
| Python | mit | UCL/pyoracc | ---
+++
@@ -31,7 +31,7 @@
for tok in lexer:
print(tok)
print("Lexed file")
- exer = AtfLexer().lexer
+ lexer = AtfLexer().lexer
parser = AtfParser().parser
parser.parse(text, lexer=lexer)
print("Parsed file") |
b0e5dff69b9e40b916ad8a6655624de7fa85d247 | chmvh_website/team/migrations/0002_auto_20161024_2338.py | chmvh_website/team/migrations/0002_auto_20161024_2338.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-24 23:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-24 23:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team', '0001_initial'),
]
operations = [
migrations.AddField(
m... | Change order of migration operations. | Change order of migration operations.
| Python | mit | cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website | ---
+++
@@ -12,13 +12,13 @@
]
operations = [
- migrations.AlterModelOptions(
- name='teammember',
- options={'ordering': ('order',)},
- ),
migrations.AddField(
model_name='teammember',
name='order',
field=models.PositiveSm... |
85fce5f5ab57b6c2144c92ec0d9b185740d7dc91 | pyinform/__init__.py | pyinform/__init__.py | # Copyright 2016 ELIFE. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
from ctypes import CDLL
def get_libpath():
"""
Get the library path of the the distributed inform binary.
"""
import os
import re
from os.path import dirn... | # Copyright 2016 ELIFE. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
from ctypes import CDLL
def get_libpath():
"""
Get the library path of the the distributed inform binary.
"""
import os
import re
from os.path import dirn... | Resolve the library on windows | Resolve the library on windows
| Python | mit | ELIFE-ASU/PyInform | ---
+++
@@ -10,6 +10,7 @@
import os
import re
from os.path import dirname, abspath, realpath, join
+ from platform import system
libre = re.compile(r"^inform-(\d+)\.(\d+)\.(\d+)$")
@@ -30,6 +31,9 @@
if libdir is None:
raise ImportError("cannot find libinform")
+
+ if syst... |
0d1904345d73bf067f8640d62f9d4186757239b6 | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.3.8.dev0 | Update dsub version to 0.3.8.dev0
PiperOrigin-RevId: 293000641
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.3.7'
+DSUB_VERSION = '0.3.8.dev0' |
8098b4e73f0b407c47ecbe53318f2a246bd07d37 | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Bump version to 0.1.5 in preparation for a release | Bump version to 0.1.5 in preparation for a release
PiperOrigin-RevId: 182068450
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.1.4.dev0'
+DSUB_VERSION = '0.1.5' |
4551732c93b248e669b63d8ea6a9705c52b69dc3 | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', ... | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/... | Add url for project_status_edit option | Add url for project_status_edit option
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -4,6 +4,7 @@
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
+ url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/(?P<project_id... |
1cc68fee10975f85ca5a2e2a63b972314a1b62d9 | tests/test_redis_storage.py | tests/test_redis_storage.py | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
... | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
... | Remove old extra argument from track tests | Remove old extra argument from track tests
| Python | mit | alisaifee/sifr,alisaifee/sifr | ---
+++
@@ -30,8 +30,8 @@
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
- storage.track(span, "1", 3)
- storage.track(span, "1", 3)
- storage.track(span, "2", 3)
- storage.track(span, "3", 3)... |
9f1783ac694d91b287dcb5840f54fb3df746a963 | bot/action/core/action.py | bot/action/core/action.py | from bot.api.api import Api
from bot.multithreading.scheduler import SchedulerApi
from bot.storage import Config, State, Cache
class Action:
def __init__(self):
pass
def get_name(self):
return self.__class__.__name__
def setup(self, api: Api, config: Config, state: State, cache: Cache, s... | from bot.api.api import Api
from bot.multithreading.scheduler import SchedulerApi
from bot.storage import Config, State, Cache
class Action:
def __init__(self):
pass
def get_name(self):
return self.__class__.__name__
def setup(self, api: Api, config: Config, state: State, cache: Cache, s... | Add shutdown callback support to Action | Add shutdown callback support to Action
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -24,6 +24,12 @@
def process(self, event):
pass
+ def pre_shutdown(self):
+ pass
+
+ def shutdown(self):
+ self.pre_shutdown()
+
class ActionGroup(Action):
def __init__(self, *actions):
@@ -40,6 +46,10 @@
def process(self, event):
self.for_each(lambd... |
85efa9c105ddb9240a25be433de76ef21b3ed2b3 | xutils/const.py | xutils/const.py | # encoding: utf-8
import sys
class _const(object):
class ConstError(TypeError):
pass
class ConstCaseError(ConstError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError, "Can't change const.{0}".format(name)
if not name... | # encoding: utf-8
import sys
class _const(object):
class ConstError(TypeError):
pass
class ConstCaseError(ConstError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError("Can't change const.{0}".format(name))
if not name... | Fix a bug on Python 3.6 | Fix a bug on Python 3.6
| Python | mit | xgfone/pycom,xgfone/xutils | ---
+++
@@ -12,10 +12,10 @@
def __setattr__(self, name, value):
if name in self.__dict__:
- raise self.ConstError, "Can't change const.{0}".format(name)
+ raise self.ConstError("Can't change const.{0}".format(name))
if not name.isupper():
- raise self.ConstC... |
2bcc941b015c443c64f08a13012e8caf70028754 | ideascube/search/migrations/0001_initial.py | ideascube/search/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import ideascube.search.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
c... | Fix the initial search migration | Fix the initial search migration
There is no point in creating the model in this way, that's just not how
it's used: instead we want to use the FTS4 extension from SQLite.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -1,8 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-from django.db import migrations, models
-import ideascube.search.models
+from django.db import migrations
+from ideascube.search.utils import create_index_table
+
+
+class CreateSearchModel(migrations.CreateModel):
+ def... |
fc818ccd0d83ff6b37b38e5e9d03abcae408b503 | froide/problem/templatetags/problemreport_tags.py | froide/problem/templatetags/problemreport_tags.py | from collections import defaultdict
from django import template
from ..models import ProblemReport
from ..forms import ProblemReportForm
register = template.Library()
@register.inclusion_tag('problem/message_toolbar_item.html')
def render_problem_button(message):
if not hasattr(message, 'problemreports'):
... | from collections import defaultdict
from django import template
from ..models import ProblemReport
from ..forms import ProblemReportForm
register = template.Library()
@register.inclusion_tag('problem/message_toolbar_item.html')
def render_problem_button(message):
if not hasattr(message, 'problemreports'):
... | Fix overriding variable in problem report tag | Fix overriding variable in problem report tag | Python | mit | stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide | ---
+++
@@ -16,13 +16,13 @@
message_reports = defaultdict(list)
for report in reports:
message_reports[report.message_id].append(report)
- for message in request.messages:
- message.problemreports = message_reports[message.id]
- message.problemreports_count ... |
a3347eff5791c89949a88988a958c45ec50cccdf | runtests.py | runtests.py | #!/usr/bin/env python
import os, sys
import django
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
settings.configure(
DEBUG = True,
DATABASES = {
'default': {'ENGINE': 'django.db.backends.sqlite3'},
},
INSTALLED_APPS = (
'django.contrib.auth',
... | #!/usr/bin/env python
import os, sys
import django
from django.conf import settings
DIRNAME = os.path.dirname(__file__)
settings.configure(
DEBUG = True,
DATABASES = {
'default': {'ENGINE': 'django.db.backends.sqlite3'},
},
INSTALLED_APPS = (
'django.contrib.auth',
... | Add `TEMPLATE` config to test runner, to define template backend. | Add `TEMPLATE` config to test runner, to define template backend.
| Python | bsd-2-clause | potatolondon/django-hashbrown | ---
+++
@@ -19,6 +19,12 @@
),
# Django 1.7 raises a warning if this isn't set. Pollutes test output.
MIDDLEWARE_CLASSES = (),
+ TEMPLATES = [{
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'DIRS': [],
+ 'APP_DIRS': True,
+ 'OPTI... |
af5eae0b477c73c1c8d1bbce646d94858d157142 | whip/web.py | whip/web.py | #!/usr/bin/env python
import socket
from flask import Flask, abort, make_response, request
from whip.db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db
db = Database(app.config['DATABASE_DIR'])
@ap... | #!/usr/bin/env python
import socket
from flask import Flask, abort, make_response, request
from whip.db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db
db = Database(app.config['DATABASE_DIR'])
@ap... | Return empty responses (not HTTP 404) in REST API for missing data | Return empty responses (not HTTP 404) in REST API for missing data
| Python | bsd-3-clause | wbolster/whip | ---
+++
@@ -34,7 +34,7 @@
info_as_json = db.lookup(key, dt)
if info_as_json is None:
- abort(404)
+ info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json' |
a5b73a7ded0e277662308e0b4d38ac0429c404fb | django_facebook/models.py | django_facebook/models.py | from django.db import models
class FacebookProfileModel(models.Model):
'''
Abstract class to add to your profile model.
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in.
'''
about_me = models.TextField(blank=True, null=True)
facebook_id = models.I... | from django.db import models
from django.contrib.auth.models import User
class FacebookProfileModel(models.Model):
'''
Abstract class to add to your profile model.
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in.
'''
user = models.OneToOneField(User)... | Add reference to user model and __unicode__() method to FacebookProfileModel | Add reference to user model and __unicode__() method to FacebookProfileModel
| Python | bsd-3-clause | pjdelport/Django-facebook,QLGu/Django-facebook,Shekharrajak/Django-facebook,VishvajitP/Django-facebook,troygrosfield/Django-facebook,QLGu/Django-facebook,cyrixhero/Django-facebook,rafaelgontijo/Django-facebook-fork,fyndsi/Django-facebook,jcpyun/Django-facebook,abendleiter/Django-facebook,danosaure/Django-facebook,cyrix... | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.contrib.auth.models import User
class FacebookProfileModel(models.Model):
'''
@@ -7,6 +8,7 @@
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in.
'''
+ user = models.OneToOneField(User)
... |
3122736e0eccd4d4b1f003faa1db6ec05710883f | addstr.py | addstr.py | #!/usr/bin/python
import argparse
from dx.dex import Dex
from sha1 import update_signature
from adler32 import update_checksum
def main():
parser = argparse.ArgumentParser(description="Parse and reconstruct dex file")
parser.add_argument('target',help='Target DEX file')
parser.add_argument('string',hel... | #!/usr/bin/python
import argparse
from dx.dex import Dex
from dx.hash import update_signature, update_checksum
def main():
parser = argparse.ArgumentParser(description="Parse and reconstruct dex file")
parser.add_argument('target',help='Target DEX file')
parser.add_argument('string',help='String to be ... | Fix attempted import from non-existent module. | Fix attempted import from non-existent module. | Python | bsd-3-clause | strazzere/dexterity,strazzere/dexterity,rchiossi/dexterity,strazzere/dexterity,rchiossi/dexterity,rchiossi/dexterity | ---
+++
@@ -4,8 +4,7 @@
from dx.dex import Dex
-from sha1 import update_signature
-from adler32 import update_checksum
+from dx.hash import update_signature, update_checksum
def main():
parser = argparse.ArgumentParser(description="Parse and reconstruct dex file") |
edd50431f9c99bcbc765cc85786ead60ba8ba6e4 | admin/base/migrations/0002_groups.py | admin/base/migrations/0002_groups.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import Group
import logging
logger = logging.getLogger(__file__)
def add_groups(*args):
group, created = Group.objects.get_or_create(name='nodes_and_users')
if created:
lo... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import Group
import logging
logger = logging.getLogger(__file__)
def add_groups(*args):
group, created = Group.objects.get_or_create(name='nodes_and_users')
if created:
lo... | Add reverse migration for new groups | Add reverse migration for new groups
| Python | apache-2.0 | brianjgeiger/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,crcresearch/osf.io,aaxelb/osf.io,erinspace/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,erinspace/osf.io... | ---
+++
@@ -24,6 +24,14 @@
logger.info('prereg group created')
+def remove_groups(*args):
+ Group.objects.filter(name='nodes_and_users').delete()
+
+ group = Group.objects.get(name='prereg')
+ group.name = 'prereg_group'
+ group.save()
+
+
class Migration(migrations.Migration):
de... |
eef28c81f19d7e5eb72635cc2e6bf3b74331c743 | quilt/patch.py | quilt/patch.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | Patch parameter --prefix does need a path seperator | Patch parameter --prefix does need a path seperator
The --prefix parameter of the patch command needs a path seperator at
the end to store the backup in a directory.
| Python | mit | vadmium/python-quilt,bjoernricks/python-quilt | ---
+++
@@ -19,6 +19,8 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
+import os
+
from quilt.utils import Process
class Patch(object):
@@ -29,6 +31,8 @@
cmd.append("--backup")
if prefix:
cmd.append("--prefix")
+ if not prefix... |
306a09153de72f5f9f4043fa45472440065ac473 | bindings/pyroot/JupyROOT/kernel/magics/jsrootmagic.py | bindings/pyroot/JupyROOT/kernel/magics/jsrootmagic.py | # -*- coding:utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2016, ROOT Team.
# Authors: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
#-----------------------------------------------------------------------------
from JupyROOT.utils import enableJSVis, disableJS... | # -*- coding:utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2016, ROOT Team.
# Authors: Danilo Piparo <Danilo.Piparo@cern.ch> CERN
#-----------------------------------------------------------------------------
from JupyROOT.utils import enableJSVis, disableJS... | Make the jsroot magic a line magic for the C++ kernel | Make the jsroot magic a line magic for the C++ kernel
| Python | lgpl-2.1 | veprbl/root,beniz/root,gbitzes/root,simonpf/root,mhuwiler/rootauto,CristinaCristescu/root,georgtroska/root,sawenzel/root,beniz/root,pspe/root,olifre/root,krafczyk/root,abhinavmoudgil95/root,thomaskeck/root,lgiommi/root,thomaskeck/root,root-mirror/root,georgtroska/root,davidlt/root,satyarth934/root,thomaskeck/root,krafc... | ---
+++
@@ -13,7 +13,7 @@
super(JSRootMagics, self).__init__(kernel)
@option('arg', default="on", help='Enable or disable JavaScript visualisation. Possible values: on (default), off')
- def cell_jsroot(self, args):
+ def line_jsroot(self, args):
'''Change the visualisation of plots fro... |
a37ac8daad8eee1f044d3e19a80a172138460ec3 | google_analytics/models.py | google_analytics/models.py | from django.db import models
from django.conf import settings
from django.contrib.sites.admin import SiteAdmin
from django.contrib.sites.models import Site
from django.contrib import admin
if getattr(settings, 'GOOGLE_ANALYTICS_MODEL', False):
class Analytic(models.Model):
site = models.ForeignKey(Site, u... | from django.contrib import admin
from django.contrib.sites.models import Site
from django.db import models
class Analytic(models.Model):
site = models.ForeignKey(Site, unique=True)
analytics_code = models.CharField(blank=True, max_length=100)
| Fix django version problem with new menu options in admin app. | Fix django version problem with new menu options in admin app.
| Python | agpl-3.0 | OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server | ---
+++
@@ -1,19 +1,7 @@
+from django.contrib import admin
+from django.contrib.sites.models import Site
from django.db import models
-from django.conf import settings
-from django.contrib.sites.admin import SiteAdmin
-from django.contrib.sites.models import Site
-from django.contrib import admin
-if getattr(setti... |
ec04b842c21cddaef1cf010e419113e83f3be3f1 | tests/test_logging_service.py | tests/test_logging_service.py |
import os.path
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
sys.path.append(os.path.join(os.path.dirname(__file__), '../vCenterShell'))
from vCenterShell.pycommon.logging_service import LoggingService
class TestLoggingService(unittest.TestCase):
def test_logging_se... |
import os.path
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
sys.path.append(os.path.join(os.path.dirname(__file__), '../vCenterShell'))
from vCenterShell.pycommon.logging_service import LoggingService
class TestLoggingService(unittest.TestCase):
def test_logging_se... | Remove File Creation Command for UnitTesting | Remove File Creation Command for UnitTesting
| Python | apache-2.0 | QualiSystems/vCenterShell,QualiSystems/vCenterShell | ---
+++
@@ -12,14 +12,19 @@
def test_logging_service_01(self):
log_file_name = "test_log.log"
- LoggingService("CRITICAL", "DEBUG", log_file_name)
- self.assertTrue(os.path.isfile(log_file_name))
- os.unlink(log_file_name)
+ LoggingService("CRITICAL", "DEBUG", None)
+ ... |
2b99108a817a642c86be06a14ac8d71cdc339555 | scripts/speak.py | scripts/speak.py | #!/usr/bin/env python
import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String
class ChatbotSpeaker:
def __init__(self):
rospy.init_node('chatbot_speaker')
self._client = SoundClient()
rospy.Subscriber('chatbot_responses', Strin... | #!/usr/bin/env python
import os
import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String
import urllib
tts_cmd = (
'wget -q -U "Mozilla/5.0" -O -
"http://translate.google.com/translate_tts?tl=en-uk&q={}" > /tmp/speech.mp3'
)
sox_cmd = 'so... | Use Google Translate API to get a female TTS | Use Google Translate API to get a female TTS
| Python | mit | jstnhuang/chatbot | ---
+++
@@ -1,9 +1,17 @@
#!/usr/bin/env python
+import os
import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String
+import urllib
+
+tts_cmd = (
+ 'wget -q -U "Mozilla/5.0" -O -
+ "http://translate.google.com/translate_tts?tl=en-uk&q... |
11be4b77e84c721ef8de583b0dcf1035367d4b25 | libtmux/__about__.py | libtmux/__about__.py | __title__ = 'libtmux'
__package_name__ = 'libtmux'
__version__ = '0.8.0'
__description__ = 'scripting library / orm for tmux'
__email__ = 'tony@git-pull.com'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tmux-python/libtmux'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016-2018 Tony Narlock'
| __title__ = 'libtmux'
__package_name__ = 'libtmux'
__version__ = '0.8.0'
__description__ = 'scripting library / orm for tmux'
__email__ = 'tony@git-pull.com'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tmux-python/libtmux'
__pypi__ = 'https://pypi.python.org/pypi/libtmux'
__license__ = 'MIT'
__copyrigh... | Add __pypi__ url to metadata | Add __pypi__ url to metadata
| Python | bsd-3-clause | tony/libtmux | ---
+++
@@ -5,5 +5,6 @@
__email__ = 'tony@git-pull.com'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tmux-python/libtmux'
+__pypi__ = 'https://pypi.python.org/pypi/libtmux'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016-2018 Tony Narlock' |
f3fef8dab576ef5d7a4120a4041ade326868f0ca | flexget/plugins/ui/execute.py | flexget/plugins/ui/execute.py | import logging
from flask import render_template, request, Response, redirect, flash
from flask import Module, escape
from flexget.webui import register_plugin, manager, BufferQueue
from Queue import Empty
from flask.helpers import jsonify
execute = Module(__name__, url_prefix='/execute')
log = logging.getLo... | import logging
from flask import render_template, request, Response, redirect, flash
from flask import Module, escape
from flexget.webui import register_plugin, manager, BufferQueue
from Queue import Empty
from flask.helpers import jsonify
execute = Module(__name__, url_prefix='/execute')
log = logging.getLo... | Fix an issue with repeated messages in json execution output provider. | Fix an issue with repeated messages in json execution output provider.
git-svn-id: 555d7295f8287ebc42f8316c6775e40d702c4756@1726 3942dd89-8c5d-46d7-aeed-044bccf3e60c
| Python | mit | oxc/Flexget,tsnoam/Flexget,offbyone/Flexget,malkavi/Flexget,ibrahimkarahan/Flexget,ratoaq2/Flexget,asm0dey/Flexget,sean797/Flexget,OmgOhnoes/Flexget,ibrahimkarahan/Flexget,drwyrm/Flexget,jawilson/Flexget,thalamus/Flexget,tarzasai/Flexget,tvcsantos/Flexget,tarzasai/Flexget,Danfocus/Flexget,drwyrm/Flexget,xfouloux/Flexge... | ---
+++
@@ -39,6 +39,7 @@
item = bufferqueue.get_nowait()
if item != '\n':
result['items'].append(item)
+ bufferqueue.task_done()
except Empty:
pass
|
9346b34c68fc08dfba0002e907d73829000068cd | labmanager/shell.py | labmanager/shell.py | import cmd
class LMShell(cmd.Cmd):
def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None):
cmd.Cmd.__init__(self, completekey, stdin, stdout)
self._lmapi = lmapi
def do_list(self, line):
configs = self._lmapi.list_library_configurations()
print configs
def ... | import cmd
class LMShell(cmd.Cmd):
def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None):
cmd.Cmd.__init__(self, completekey, stdin, stdout)
self._lmapi = lmapi
def do_list(self, line):
configs = self._lmapi.list_library_configurations()
print configs
def ... | Add 'quit' command to lmsh | Add 'quit' command to lmsh
| Python | bsd-3-clause | jamesls/labmanager-shell | ---
+++
@@ -11,6 +11,9 @@
print configs
def do_EOF(self, line):
+ return True
+
+ def do_quit(self, line):
return True
|
713fcc3f86b4be4d35f0c5ba081a4f786648320a | vim/pythonx/elixir_helpers.py | vim/pythonx/elixir_helpers.py | """
Elixir-related Ultisnips snippet helper functions.
NOTE: Changes to this file require restarting Vim!
"""
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
def closing_character(tabstop):
"""
Return closing character for a tabs... | """
Elixir-related Ultisnips snippet helper functions.
NOTE: Changes to this file require restarting Vim!
"""
import re
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
_CLOSING_CHARACTERS = {
"(": ")",
"{": "}",
"[": "]",
"\"": "\""... | Refactor python if statement into dictionary | Refactor python if statement into dictionary
| Python | mit | paulfioravanti/dotfiles,paulfioravanti/dotfiles,paulfioravanti/dotfiles | ---
+++
@@ -6,20 +6,19 @@
_DASHES_AND_UNDERSCORES = re.compile("[-_]")
_MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex")
+_CLOSING_CHARACTERS = {
+ "(": ")",
+ "{": "}",
+ "[": "]",
+ "\"": "\""
+}
def closing_character(tabstop):
"""
Return closing character for a ... |
f1b0b1fc96802bf236cf9bfbc894ebdf47704b33 | test_example.py | test_example.py | """Usage: prog [-vqr] [FILE]
prog INPUT OUTPUT
prog --help
Options:
-v print status messages
-q report only file names
-r show all occurrences of the same error
--help
"""
from docopt import docopt, Options, Arguments, DocoptExit
from pytest import raises
def test_docopt():
o, a =... | """Usage: prog [-vqr] [FILE]
prog INPUT OUTPUT
prog --help
Options:
-v print status messages
-q report only file names
-r show all occurrences of the same error
--help
"""
from docopt import docopt, Options, Arguments, DocoptExit
from pytest import raises
def test_docopt():
o, a =... | Correct test to catch SystemExit on normal exit. | Correct test to catch SystemExit on normal exit.
| Python | mit | docopt/docopt,jagguli/docopt,benthomasson/docopt,kenwilcox/docopt,devonjones/docopt,snowsnail/docopt,Zearin/docopt,wkentaro/docopt,crcsmnky/docopt | ---
+++
@@ -28,5 +28,5 @@
with raises(DocoptExit):
docopt(__doc__, '--fake')
- with raises(DocoptExit):
+ with raises(SystemExit):
docopt(__doc__, '--hel') |
77744d61918510fcd943d9420ce4c61717a0711b | test/functionalities/connect_remote/TestConnectRemote.py | test/functionalities/connect_remote/TestConnectRemote.py | """
Test lldb 'process connect' command.
"""
import os
import unittest2
import lldb
import pexpect
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
#... | """
Test lldb 'process connect' command.
"""
import os
import unittest2
import lldb
import pexpect
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@expectedFailureFreeBSD('llvm.org/pr18313')
def test_connect_remote(self):
"""Test "process co... | Add decorator for GDB connect test failing on FreeBSD | Add decorator for GDB connect test failing on FreeBSD
llvm.org/pr18313
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@197910 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb | ---
+++
@@ -12,6 +12,7 @@
mydir = TestBase.compute_mydir(__file__)
+ @expectedFailureFreeBSD('llvm.org/pr18313')
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
|
4e3f10cc417f28badc34646cc89fcd9d0307b4be | utility/lambdas/s3-static-site-deploy/lambda_function.py | utility/lambdas/s3-static-site-deploy/lambda_function.py | # import boto3
def lambda_handler(event, context):
pass
| # Invoked by: CloudFormation
# Returns: A `Data` object to a pre-signed URL
#
# Deploys the contents of a versioned zip file object from one bucket in S3
# to a another bucket
import sys
import boto3
from botocore.client import Config
import io
import zipfile
import os
import urllib.request
import json
import tracebac... | Add S3 static deploy custom resource Lambda function | Add S3 static deploy custom resource Lambda function
| Python | mit | PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure | ---
+++
@@ -1,5 +1,82 @@
-# import boto3
+# Invoked by: CloudFormation
+# Returns: A `Data` object to a pre-signed URL
+#
+# Deploys the contents of a versioned zip file object from one bucket in S3
+# to a another bucket
+
+import sys
+import boto3
+from botocore.client import Config
+import io
+import zipfile
+impo... |
aed82bc0995cf4175c0ab8c521dfc8e89d776a7e | Mac/scripts/zappycfiles.py | Mac/scripts/zappycfiles.py | # Zap .pyc files
import os
import sys
doit = 1
def main():
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
if not sys.argv[1:]:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in... | #!/usr/local/bin/python
"""Recursively zap all .pyc files"""
import os
import sys
# set doit true to actually delete files
# set doit false to just print what would be deleted
doit = 1
def main():
if not sys.argv[1:]:
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files ... | Patch by Russel Owen: if we have command line arguments zap pyc files in the directories given. | Patch by Russel Owen: if we have command line arguments zap pyc files
in the directories given.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,23 +1,26 @@
-# Zap .pyc files
+#!/usr/local/bin/python
+"""Recursively zap all .pyc files"""
import os
import sys
+# set doit true to actually delete files
+# set doit false to just print what would be deleted
doit = 1
def main():
- if os.name == 'mac':
- import macfs
- fss, ok = macfs.GetDire... |
db04d6884c68b1f673a785866155427af86fad65 | apps/predict/templatetags/jsonify.py | apps/predict/templatetags/jsonify.py | """Add a template tag to turn python objects into JSON"""
import types
import json
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def jsonify(obj):
if isinstance(obj, types.GeneratorType):
obj = list(obj)
return mark_safe(json.... | """Add a template tag to turn python objects into JSON"""
import types
import json
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def jsonify(obj):
"""Turn object into a json instance"""
if isinstance(obj, types.GeneratorType):
... | Remove single quote marks from jsonif | Remove single quote marks from jsonif
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site | ---
+++
@@ -9,7 +9,7 @@
@register.filter
def jsonify(obj):
+ """Turn object into a json instance"""
if isinstance(obj, types.GeneratorType):
obj = list(obj)
- return mark_safe(json.dumps(obj))
-
+ return mark_safe(json.dumps(obj).replace("'", "\\'")) |
73d4aa7fa41117bbbe6447466cf453153f76b5ba | armstrong/core/arm_wells/views.py | armstrong/core/arm_wells/views.py | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView
from django.views.generic.list import MultipleObjectMixin
from django.utils.translation import ugettext as _
from .models import Well
class SimpleWellView(TemplateView):
allow_empty = False
well_title = None... | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView
from django.views.generic.list import MultipleObjectMixin
from django.utils.translation import ugettext as _
from .models import Well
class SimpleWellView(TemplateView):
allow_empty = False
well_title = None... | Switch to None based on feedback from @niran | Switch to None based on feedback from @niran
| Python | apache-2.0 | armstrong/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells | ---
+++
@@ -21,7 +21,7 @@
return Well.objects.get_current(title=self.well_title)
except Well.DoesNotExist:
if self.allow_empty:
- return False
+ return None
raise
def get_context_data(self, **kwargs):
@@ -33,7 +33,7 @@
class QuerySe... |
8ed2aa1a8108ae3a678ff18f4e8fda3539f4b603 | avalonstar/components/games/admin.py | avalonstar/components/games/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Game, Platform
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed']
raw_id_fields = ['platform']
autocomplete_lookup_fields = { 'fk': ['platform'] }
admin.site.register(... | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Game, Platform
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed']
list_editable = ['is_abandoned', 'is_completed']
raw_id_fields = ['platform']
autocomplete_lookup... | Make the game booleans editable. | Make the game booleans editable.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | ---
+++
@@ -6,6 +6,7 @@
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed']
+ list_editable = ['is_abandoned', 'is_completed']
raw_id_fields = ['platform']
autocomplete_lookup_fields = { 'fk': ['platform'] } |
12683ea64a875b624230f2dd84609a77eaec1095 | cd_wizard.py | cd_wizard.py | #!/usr/bin/env python
"""Wizard to guide user to:
- insert cd
- please rip with eac
- check for a good rip
- upload with metadata (freedb, musicmind)
"""
from PyQt4 import QtGui
def createIntroPage():
page = QtGui.QWizardPage()
page.setTitle("Introduction")
page.setSubTitle("This wizard will help y... | #!/usr/bin/env python
"""Wizard to guide user to:
- insert cd
- please rip with eac
- check for a good rip
- upload with metadata (freedb, musicmind)
"""
from PyQt4 import QtGui
def createIntroPage():
page = QtGui.QWizardPage()
page.setTitle("Introduction")
page.setSubTitle("This wizard will help y... | Add file browser to choose a CD. | Add file browser to choose a CD.
| Python | agpl-3.0 | brewsterkahle/archivecd | ---
+++
@@ -26,6 +26,22 @@
return page
+def choose_cd():
+ page = QtGui.QWizardPage()
+ page.setTitle("Choose CD Drive")
+
+ file_dialog = QtGui.QFileDialog()
+ file_dialog.setFileMode(QtGui.QFileDialog.Directory)
+ file_dialog.setOptions(QtGui.QFileDialog.ShowDirsOnly)
+ file_dialog.setDir... |
e7cb5b0be49bc5e811809c56eb4ad3c0dc861cdf | examples/child_watcher.py | examples/child_watcher.py | import logging
import random
from tornado import gen
from zoonado import exc
log = logging.getLogger()
def arguments(parser):
parser.add_argument(
"--path", "-p", type=str, default="/examplewatcher",
help="ZNode path to use for the example."
)
def watcher_callback(children):
children.so... | import logging
import random
from tornado import gen
from zoonado import exc
log = logging.getLogger()
def arguments(parser):
parser.add_argument(
"--path", "-p", type=str, default="/examplewatcher",
help="ZNode path to use for the example."
)
def watcher_callback(children):
children.so... | Fix up to the child watcher example. | Fix up to the child watcher example.
Without yielding to the ioloop after each call to client.delete() the child
znodes would be deleted but that would never be reported.
| Python | apache-2.0 | wglass/zoonado | ---
+++
@@ -15,7 +15,7 @@
def watcher_callback(children):
children.sort()
- log.info("There are %d items now: %s", len(children), children)
+ log.info("There are %d items now: %s", len(children), ", ".join(children))
@gen.coroutine
@@ -40,3 +40,4 @@
for item in to_make:
yield client... |
615e57fefa2b3b52ce351ef1d8039216927dc891 | Parallel/Testing/Cxx/TestSockets.py | Parallel/Testing/Cxx/TestSockets.py | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the c... | Fix space problem and put try around os.kill | ERR: Fix space problem and put try around os.kill
| Python | bsd-3-clause | SimVascular/VTK,johnkit/vtk-dev,gram526/VTK,daviddoria/PointGraphsPhase1,sankhesh/VTK,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,msmolens/VTK,SimVascular/VTK,arnaudgelas/VTK,gram526/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,Wuteyan/VTK,aashish24/VTK-old,mspark93/VTK,hendradarwin/VTK,collects/VTK,collec... | ---
+++
@@ -12,10 +12,13 @@
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
- retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
+ retVal = os.system('"%s" -D "%s" -V "%s"' % ( sys.argv[2], sys.argv[3],
... |
e8d57ef08616b06e5f94da7e01ba96c13b9124d7 | perfrunner/celeryremote.py | perfrunner/celeryremote.py | BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker'
CELERY_RESULT_BACKEND = 'amqp'
CELERY_RESULT_EXCHANGE = 'perf_results'
CELERY_RESULT_PERSISTENT = False
| BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker'
CELERY_RESULT_BACKEND = 'amqp'
CELERY_RESULT_EXCHANGE = 'perf_results'
CELERY_RESULT_PERSISTENT = False
CELERYD_HIJACK_ROOT_LOGGER = False
| Disable hijacking of previously configured log handlers | Disable hijacking of previously configured log handlers
See also:
http://docs.celeryproject.org/en/3.1/configuration.html#celeryd-hijack-root-logger
Change-Id: Ibf4618e8bfeb28f877db4a40b4a911ff00442cc9
Reviewed-on: http://review.couchbase.org/82543
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couch... | Python | apache-2.0 | couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner | ---
+++
@@ -2,3 +2,4 @@
CELERY_RESULT_BACKEND = 'amqp'
CELERY_RESULT_EXCHANGE = 'perf_results'
CELERY_RESULT_PERSISTENT = False
+CELERYD_HIJACK_ROOT_LOGGER = False |
dc883b81a2c5714d9401fb113101639e13e396f5 | integration_tests/tests/hello_world_sleep_and_time.py | integration_tests/tests/hello_world_sleep_and_time.py | integration_test = True
timeout = 2
SLEEP_INTERVAL = int(100e6)
def check_state(state):
import re
from functools import partial
from operator import is_not
r = re.compile('^(\d+) \[.*\] Hello World!')
lines = map(r.match, state.console.split('\n'))
lines = filter(partial(is_not, None), lines... | integration_test = True
timeout = 2
SLEEP_INTERVAL = int(100e6)
MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC
def check_state(state):
import re
from functools import partial
from operator import is_not
r = re.compile('^(\d+) \[.*\] Hello World!')
lines = map(r.match, state.console.split(... | Make sure current date is late enough | Make sure current date is late enough
| Python | bsd-2-clause | unigornel/unigornel,unigornel/unigornel | ---
+++
@@ -3,6 +3,7 @@
timeout = 2
SLEEP_INTERVAL = int(100e6)
+MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC
def check_state(state):
import re
@@ -22,4 +23,5 @@
for t in times:
diff = t - prev
assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTE... |
c7e9b65d7951b9757f907da9e4bf35e43dbdbd88 | django_env/bin/install.py | django_env/bin/install.py | #!/usr/bin/env python
import sys, os
def main():
django_env_dir = os.path.abspath('%s/../' % os.path.dirname(__file__))
workon_home = os.environ.get('WORKON_HOME')
if not workon_home:
print "ERROR: The $WORKON_HOME environment variable is not set. Please check to make sure you've installed and s... | #!/usr/bin/env python
import sys
import os
def main():
django_env_dir = os.path.abspath('%s/../' % os.path.dirname(__file__))
workon_home = os.environ.get('WORKON_HOME')
if not workon_home:
print "ERROR: The $WORKON_HOME environment variable is not set. Please check to make sure you've installed... | Switch the os import to it's own line for pep8 compliance. | Switch the os import to it's own line for pep8 compliance.
| Python | bsd-3-clause | epicserve/django-environment,epicserve/django-environment | ---
+++
@@ -1,7 +1,8 @@
#!/usr/bin/env python
-import sys, os
+import sys
+import os
def main(): |
f3fb5bd0dbb3e19e58558af015aaee5ec120af71 | portal/template_helpers.py | portal/template_helpers.py | """ Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
re... | """ Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
""... | Allow for list/tuples in config files when looking for comma delimited strings. | Allow for list/tuples in config files when looking for comma delimited
strings.
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal | ---
+++
@@ -5,4 +5,8 @@
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
+ """Given string (or tuple) return the delimited values"""
+ # If given a tuple, split already happened
+ if isinstance(s, (list, tuple)):
+ return s
return s.split(delim... |
674f6e0b9fbb76684a9b05d16a5da0d4cc732b1d | scripts/analysis/plot_tracking_vector_estimator_stats.py | scripts/analysis/plot_tracking_vector_estimator_stats.py | #!/usr/bin/env python2
import numpy as np
import matplotlib.pyplot as plt
import argparse
import sys
import os
parser = argparse.ArgumentParser(
prog='plot_tracking_vector_estimator')
parser.add_argument('directory', type=str, help='Data directory')
args = parser.parse_args()
data = np.genfromtxt(
os.path.join... | #!/usr/bin/env python2
import numpy as np
import matplotlib.pyplot as plt
import argparse
import sys
import os
parser = argparse.ArgumentParser(
prog='plot_tracking_vector_estimator')
parser.add_argument('directory', type=str, help='Data directory')
args = parser.parse_args()
data = np.genfromtxt(
os.path.join... | Change estimator script based on modifications to estimator | Change estimator script based on modifications to estimator
| Python | mpl-2.0 | jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy | ---
+++
@@ -14,14 +14,15 @@
args.directory,
'tracking_vector_estimator'),
delimiter=',', names=True)
-state_labels = ['Marker_x', 'Marker_y', 'Marker_z', 'Velocity_x', 'Velocity_y', 'Velocity_z']
-noise_labels = ['Noise_x', 'Noise_y', 'Noise_z', 'Noise_vx', 'Noise_vy', 'Noise_vz']
-meas_labels ... |
a0aa74d9e6295e34f02b4eefd76e7eb9a1e6425f | node/floor_divide.py | node/floor_divide.py | #!/usr/bin/env python
from nodes import Node
class FloorDiv(Node):
char = "f"
args = 2
results = 1
@Node.test_func([3,2], [1])
@Node.test_func([6,-3], [-2])
def func(self, a:Node.number,b:Node.number):
"""a/b. Rounds down, returns an int."""
return a//b
@Node.test... | #!/usr/bin/env python
from nodes import Node
class FloorDiv(Node):
char = "f"
args = 2
results = 1
@Node.test_func([3,2], [1])
@Node.test_func([6,-3], [-2])
def func(self, a:Node.number,b:Node.number):
"""a/b. Rounds down, returns an int."""
return a//b
@Node.test... | Add a group chunk, chunks a list into N groups | Add a group chunk, chunks a list into N groups
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -22,3 +22,26 @@
return a 3-list containing the string itself,
followed by two empty strings."""
return [list(string.partition(sep))]
+
+ @Node.test_func(["134", 1], [["134"]])
+ @Node.test_func(["1234", 2], [["12", "34"]])
+ @Node.test_func(["1234", 3], [["1", "2", "34"]])
+ @Nod... |
9361af556cfa7f4fb6bb3c53b4e74e2c115cd7d7 | annict/client.py | annict/client.py | # -*- coding: utf-8 -*-
from operator import methodcaller
import requests
from furl import furl
class Client(object):
def __init__(self, access_token, base_url='https://api.annict.com', api_version='v1'):
self.access_token = access_token
self.base_url = base_url
self.api_version = api_ve... | # -*- coding: utf-8 -*-
from operator import methodcaller
import requests
from furl import furl
class Client(object):
def __init__(self, access_token, base_url='https://api.annict.com', api_version='v1'):
self.access_token = access_token
self.base_url = base_url
self.api_version = api_ve... | Fix Client returns requests's response. | Fix Client returns requests's response.
| Python | mit | kk6/python-annict | ---
+++
@@ -24,12 +24,7 @@
url = furl(self.base_url)
url.path.add(self.api_version).add(path)
m = methodcaller(http_method, url.url, **d)
- response = m(requests)
-
- if not response.content:
- return None
-
- return response.json()
+ return m(requests... |
069a29351e228996a465b962b1dffed5581685de | src/gewebehaken/cli.py | src/gewebehaken/cli.py | """
Gewebehaken
~~~~~~~~~~~
Command-line interface
:Copyright: 2015-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from argparse import ArgumentParser
from .app import create_app
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 5000
DEFAULT_LOG_FILENAME = 'incoming.log'
def parse_args():
"""... | """
Gewebehaken
~~~~~~~~~~~
Command-line interface
:Copyright: 2015-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from argparse import ArgumentParser
from .app import create_app
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 5000
def parse_args():
"""Setup and apply the command line argum... | Make log filename configurable and optional | Make log filename configurable and optional
| Python | mit | homeworkprod/gewebehaken | ---
+++
@@ -15,7 +15,6 @@
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 5000
-DEFAULT_LOG_FILENAME = 'incoming.log'
def parse_args():
@@ -44,10 +43,16 @@
help='the port to listen on [default: {:d}]'.format(DEFAULT_PORT),
metavar='PORT')
+ parser.add_argument(
+ '--logfile',
+ ... |
dffbc7d79c67c3629f718c7a0330f9922499640d | examples/translations/portuguese_test_1.py | examples/translations/portuguese_test_1.py | # Portuguese Language Test - Python 3 Only!
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Visita... | # Portuguese Language Test - Python 3 Only!
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua... | Update the Portuguese example test | Update the Portuguese example test
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -7,16 +7,17 @@
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
- self.verificar_elemento('[title="Visitar a página principal"]')
+ self.verificar_elemento('[title="Língua portuguesa"]')
self.atualizar... |
135c84189720aa2b7c07e516c782f7fab7b4d8fe | astropy/units/format/base.py | astropy/units/format/base.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
class _FormatterMeta(type):
registry = {}
def __new__(mcls, name, bases, members):
if 'name' in members:
formatter_name = members['name'].lower()
else:
formatter_name = members['name'] = name.lower()
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
class Base:
"""
The abstract base class of all unit formats.
"""
registry = {}
def __new__(cls, *args, **kwargs):
# This __new__ is to make it clear that there is no reason to
# instantiate a Formatter--if you try to y... | Remove use of metaclass for unit formats | Remove use of metaclass for unit formats
| Python | bsd-3-clause | astropy/astropy,saimn/astropy,mhvk/astropy,lpsinger/astropy,saimn/astropy,lpsinger/astropy,mhvk/astropy,pllim/astropy,astropy/astropy,lpsinger/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,astropy/astropy,pllim/astropy,lpsinger/astropy,larrybradley/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/ast... | ---
+++
@@ -1,31 +1,25 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
-class _FormatterMeta(type):
- registry = {}
-
- def __new__(mcls, name, bases, members):
- if 'name' in members:
- formatter_name = members['name'].lower()
- else:
- formatter_name =... |
52ef9217f954617283be54c889a317b2432651d7 | licensing/models.py | licensing/models.py | from django.db import models
class License(models.Model):
name = models.CharField(max_length=80, unique=True)
symbols = models.CharField(max_length=5)
url = models.URLField(unique=True)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return self.url
class Lic... | from django.db import models
class License(models.Model):
name = models.CharField(max_length=80, unique=True)
symbols = models.CharField(max_length=5)
url = models.URLField(unique=True)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
def get_absol... | Add __str__() method to license model | Add __str__() method to license model
__unicode__() is not used in python3
| Python | unlicense | editorsnotes/django-licensing,editorsnotes/django-licensing | ---
+++
@@ -9,6 +9,9 @@
def __unicode__(self):
return self.name
+ def __str__(self):
+ return self.name
+
def get_absolute_url(self):
return self.url
|
49d831a61c5770d02609ff2df8fed3effc3869c2 | avalonstar/components/games/admin.py | avalonstar/components/games/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Game, Platform
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'platform', 'gbid']
raw_id_fields = ['platform']
autocomplete_lookup_fields = { 'fk': ['platform'] }
admin.site.register(Game, GameAdmin)
class Platfor... | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Game, Platform
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed']
raw_id_fields = ['platform']
autocomplete_lookup_fields = { 'fk': ['platform'] }
admin.site.register(... | Add booleans in for games. | Add booleans in for games.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | ---
+++
@@ -5,7 +5,7 @@
class GameAdmin(admin.ModelAdmin):
- list_display = ['name', 'platform', 'gbid']
+ list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed']
raw_id_fields = ['platform']
autocomplete_lookup_fields = { 'fk': ['platform'] } |
ca144b8254691e9633ddedb7ad11b2c4919b8b77 | app/stores/views/search.py | app/stores/views/search.py | from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
distance = 25
def get_location(self... | from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
distance = 25
def get_location(self... | Convert the lat/lng to floats for Point. | Convert the lat/lng to floats for Point.
| Python | bsd-3-clause | nikdoof/vapemap,nikdoof/vapemap | ---
+++
@@ -18,7 +18,7 @@
if location:
name, geo = caching_geo_lookup(location)
elif lat and lng:
- geo = (lat, lng)
+ geo = (float(lat), float(lng))
else:
geo = None
self.location_geo = geo |
0e766eb66eba099071b6cfae49bf79492e29e648 | 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 documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -15,9 +15,13 @@
import ibmcnx.functions
dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/'))
-print dbs
-dbs = dbs.split('(')[0]
-print dbs
+# print dbs
+dblist = []
+for db in dbs:
+ dblist.append(db)
+print dblist
+# dbs = dbs.split('(')[0]
+# print dbs
# dbs = ['FNOSD... |
aecff9764ef8d18b7016a6acba41e74a43e66085 | clio/utils.py | clio/utils.py |
import json
from bson import json_util
from flask.wrappers import Request, cached_property
def getBoolean(string):
return {
'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False, None: False
}[string.lower()]
class ExtRequest(Requ... |
import json
from bson import json_util
from flask.wrappers import Request, cached_property
def getBoolean(string):
if string is None:
return False
return {
'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False, None: False
... | Add support to getBoolean function for None objects. | Add support to getBoolean function for None objects.
| Python | apache-2.0 | geodelic/clio,geodelic/clio | ---
+++
@@ -5,6 +5,8 @@
from flask.wrappers import Request, cached_property
def getBoolean(string):
+ if string is None:
+ return False
return {
'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False, None: False |
58d73429952a942d03b232242424946895ec3e8c | multi_schema/middleware.py | multi_schema/middleware.py | """
Middleware to automatically set the schema (namespace).
if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that.
Otherwise, set the schema to the one associated with the logged in user.
"""
from models import Schema
class SchemaMiddleware:
def process_request(self, request):
... | """
Middleware to automatically set the schema (namespace).
if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that.
Otherwise, set the schema to the one associated with the logged in user.
"""
from django.core.exceptions import ObjectDoesNotExist
from models import Schema
class Schem... | Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?). | Add some data into the request context.
Better handling of missing Schema objects when logging in (should we raise an error?).
| Python | bsd-3-clause | schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse | ---
+++
@@ -7,18 +7,28 @@
"""
+from django.core.exceptions import ObjectDoesNotExist
+
from models import Schema
class SchemaMiddleware:
def process_request(self, request):
if request.user.is_anonymous():
return None
- if request.user.is_superuser and '__schema' in request.G... |
b98e86ad9b3120dce9f163236b5e28f564547c27 | TWLight/resources/factories.py | TWLight/resources/factories.py | # -*- coding: utf-8 -*-
import factory
import random
from django.conf import settings
from TWLight.resources.models import Partner, Stream, Video, Suggestion
class PartnerFactory(factory.django.DjangoModelFactory):
class Meta:
model = Partner
strategy = factory.CREATE_STRATEGY
company_name =... | # -*- coding: utf-8 -*-
import factory
import random
from django.conf import settings
from TWLight.resources.models import Partner, Stream, Video, Suggestion
class PartnerFactory(factory.django.DjangoModelFactory):
class Meta:
model = Partner
strategy = factory.CREATE_STRATEGY
company_name =... | Change suggested_company_name factory var to pystr | Change suggested_company_name factory var to pystr
| Python | mit | WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight | ---
+++
@@ -32,9 +32,7 @@
model = Suggestion
strategy = factory.CREATE_STRATEGY
- suggested_company_name = factory.Faker(
- "company", locale=random.choice(settings.FAKER_LOCALES)
- )
+ suggested_company_name = factory.Faker("pystr", max_chars=40)
company_url = factory.Faker("... |
bf5307afe52415960d0ffc794f687b0ecebb48da | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.login import login_user, logout_user, current_user, login_required, LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask, session
from flask.ext.session import Session
from flask.ext.mail import Mail
app = Flask(__name__)
# Configuration file reading
... | from flask import Flask
from flask.ext.login import login_user, logout_user, current_user, login_required, LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask, session
from flask.ext.session import Session
from flask.ext.mail import Mail
import logging
from logging.handlers import RotatingF... | Enable file logging for the application. | Enable file logging for the application.
| Python | mit | ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp | ---
+++
@@ -4,6 +4,8 @@
from flask import Flask, session
from flask.ext.session import Session
from flask.ext.mail import Mail
+import logging
+from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@@ -25,4 +27,15 @@
# Mail engine init
mail = Mail(app)
+##################
+# Logging syste... |
04328bb0ed84180aa9e5ce7f749eafb1ab96d4fc | app/api/auth.py | app/api/auth.py | from urllib import urlencode
from datetime import datetime
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from django.utils.timezone import now
from api.models import AuthAPIKey, AuthAPILog
class APIKeyAuthentication(object):
""" Validats a request by API key ... | from urllib import urlencode
from datetime import datetime
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from django.utils.timezone import now
from api.models import AuthAPIKey, AuthAPILog
class APIKeyAuthentication(object):
""" Validats a request by API key ... | Use create instead of instance and save | Use create instead of instance and save
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -24,7 +24,7 @@
url = "%s?%s" % (request.path, urlencode(params))
else:
url = request.path
- AuthAPILog(key=keyobj, access_datetime=now(), url=url).save()
+ AuthAPILog.objects.create(key=keyobj, access_datetime=now(), u... |
6091fccc90bb6b90c47a2e4fb7ee6821876eb1a1 | synthnotes/generators/lengthgenerator.py | synthnotes/generators/lengthgenerator.py | from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename(__name__,
'resources/note_lengths.csv')):
# print(length_file)
df = pd... | from pkg_resources import resource_filename
import pandas as pd
import numpy as np
class LengthGenerator(object):
def __init__(self,
length_file=resource_filename('synthnotes.resources',
'note_lengths.csv')):
# print(length_file)
df ... | Change LengthGenerator to get appropriate file path | Change LengthGenerator to get appropriate file path
| Python | mit | ebegoli/SynthNotes | ---
+++
@@ -6,8 +6,8 @@
class LengthGenerator(object):
def __init__(self,
- length_file=resource_filename(__name__,
- 'resources/note_lengths.csv')):
+ length_file=resource_filename('synthnotes.resources',
+ ... |
fc7cadecb95fa798a8e8aaeb544ad5464f13a533 | nanomon/registry.py | nanomon/registry.py | from weakref import WeakValueDictionary
class DuplicateEntryError(Exception):
def __init__(self, name, obj, registry):
self.name = name
self.obj = obj
self.registry = registry
def __str__(self):
return "Duplicate entry in '%s' registry for '%s'." % (
self.regist... | from weakref import WeakValueDictionary
class DuplicateEntryError(Exception):
def __init__(self, name, obj, registry):
self.name = name
self.obj = obj
self.registry = registry
def __str__(self):
return "Duplicate entry in '%s' registry for '%s'." % (
self.regist... | Clean up some commented out code | Clean up some commented out code
| Python | bsd-2-clause | cloudtools/nymms | ---
+++
@@ -8,13 +8,12 @@
def __str__(self):
return "Duplicate entry in '%s' registry for '%s'." % (
- self.registry._registry_name, self.name)
+ self.registry._object_type.__name__, self.name)
class Registry(WeakValueDictionary):
def __init__(self, object_type,... |
d9f03ad1c73cc18276666f28e9a9360c71139a0d | nib/plugins/time.py | nib/plugins/time.py | import datetime
import time
from nib import jinja
@jinja('time')
def timeformat(t=None, f='%Y-%m-%d %I:%M %p'):
if t is None:
t = time.gmtime()
elif isinstance(t, datetime.date) or isinstance(t, datetime.datetime):
t = t.timetuple()
elif isinstance(t, float):
t = time.gmtime(t)
... | import datetime
import time
from nib import jinja
@jinja('time')
def timeformat(t=None, f='%Y-%m-%d %I:%M %p'):
if t is None:
t = time.gmtime()
elif isinstance(t, datetime.date) or isinstance(t, datetime.datetime):
t = t.timetuple()
elif isinstance(t, float):
t = time.gmtime(t)
... | Add 'longdate' filter for readable dates in templates | Add 'longdate' filter for readable dates in templates
| Python | mit | jreese/nib | ---
+++
@@ -27,3 +27,7 @@
def dateformat(t=None, f='%Y-%m-%d'):
return timeformat(t,f)
+@jinja('longdate')
+def longdateformat(t=None, f='%B %d, %Y'):
+ return timeformat(t, f)
+ |
43a515ddfbe38686672fe00d4765d3f2e1bc5346 | scarlet/assets/settings.py | scarlet/assets/settings.py | from django.conf import settings
# Main Assets Directory. This will be a subdirectory within MEDIA_ROOT.
# Set to None to use MEDIA_ROOT directly
DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets')
# Which size should be used as CMS thumbnail for images.
CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL... | from django.conf import settings
# Main Assets Directory. This will be a subdirectory within MEDIA_ROOT.
# Set to None to use MEDIA_ROOT directly
DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets')
# Which size should be used as CMS thumbnail for images.
CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL... | Set upscale to True by default for admin asset | Set upscale to True by default for admin asset
| Python | mit | ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet | ---
+++
@@ -20,7 +20,10 @@
ASSET_TYPES = getattr(settings, "ASSET_TYPES", None)
DEFAULT_IMAGE_SIZES = {
- 'admin' : { 'width' : 100, 'height' : 100, 'editable': False }
+ 'admin' : {
+ 'width' : 100, 'height' : 100,
+ 'editable': False, 'upscale': True,
+ },
}
IMAGE_SIZES = getattr(sett... |
b57d5ecf56640c9d0a69b565006e2240662d6b46 | profile_collection/startup/11-temperature-controller.py | profile_collection/startup/11-temperature-controller.py | from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(Epi... | from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(Epi... | Remove settle_time kwarg from c700 | Remove settle_time kwarg from c700
This kwarg has been removed from ophyd, but will be coming back (and be
functional) soon. Revert these changes when that happens: ophyd 0.2.1)
| Python | bsd-2-clause | NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd | ---
+++
@@ -17,8 +17,10 @@
status._finished()
return status
-cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700',
- settle_time=10)
+cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700')
+# this functionality never worked, ... |
28627a41918be15037ba22e930a45d022e88388d | opps/articles/adminx.py | opps/articles/adminx.py | # -*- coding: utf-8 -*-
#from django.contrib import admin
from .models import Post, Album, Link
from opps.contrib import admin
admin.site.register(Post)
admin.site.register(Album)
admin.site.register(Link)
| # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from .models import Post, Album, Link
from opps.containers.models import ContainerSource, ContainerImage
from opps.contrib import admin
from opps.contrib.admin.layout import *
from xadmin.plugins.inline import Inline
class ImageInline(ob... | Add Inline example on post model xadmin | Add Inline example on post model xadmin
| Python | mit | jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps | ---
+++
@@ -1,9 +1,56 @@
# -*- coding: utf-8 -*-
-#from django.contrib import admin
+from django.utils.translation import ugettext_lazy as _
from .models import Post, Album, Link
+from opps.containers.models import ContainerSource, ContainerImage
from opps.contrib import admin
+from opps.contrib.admin.layout imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.