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 |
|---|---|---|---|---|---|---|---|---|---|---|
ee6c7caabdfcd0bddd9b92d05cddd8b6be7cbe10 | tests/functional/test_pip_runner_script.py | tests/functional/test_pip_runner_script.py | import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's no pip installed in the e... | import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's no pip installed in the e... | Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp | Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp
| Python | mit | pradyunsg/pip,pypa/pip,pfmoore/pip,pfmoore/pip,sbidoul/pip,pradyunsg/pip,sbidoul/pip,pypa/pip | ---
+++
@@ -12,7 +12,9 @@
# Ensure there's no pip installed in the environment
script.pip("uninstall", "pip", "--yes", use_module=True)
- script.pip("--version", expect_error=True)
+ # We don't use script.pip to check here, as when testing a
+ # zipapp, script.pip will run pip from the zipapp.
+ ... |
ab00a69ee0d5c556af118d9cf76b5b9a0db25e6d | telemetry/telemetry/page/page_test_results.py | telemetry/telemetry/page/page_test_results.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import traceback
import unittest
class PageTestResults(unittest.TestResult):
def __init__(self):
super(PageTestResults, self).__init__()
self.... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import traceback
import unittest
class PageTestResults(unittest.TestResult):
def __init__(self):
super(PageTestResults, self).__init__()
self.... | Add skipped and addSkip() to PageTestResults, for Python < 2.7. | [telemetry] Add skipped and addSkip() to PageTestResults, for Python < 2.7.
Fixing bots after https://chromiumcodereview.appspot.com/15153003/
Also fix typo in addSuccess(). successes is only used by record_wpr, so that mistake had no effect on the bots.
TBR=tonyg@chromium.org
BUG=None.
TEST=None.
Review URL: https:... | Python | bsd-3-clause | benschmaus/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,catapult-pro... | ---
+++
@@ -9,6 +9,7 @@
def __init__(self):
super(PageTestResults, self).__init__()
self.successes = []
+ self.skipped = []
def addError(self, test, err):
if isinstance(test, unittest.TestCase):
@@ -23,7 +24,10 @@
self.failures.append((test, ''.join(traceback.format_exception(*err))))... |
0e835c6381374c5b00b7387057d056d679f635c4 | zproject/legacy_urls.py | zproject/legacy_urls.py | from django.conf.urls import url
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These are json format views used by the web client. They r... | from django.urls import path
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These are json format views used by the web client. They requi... | Migrate legacy urls to use modern django pattern. | urls: Migrate legacy urls to use modern django pattern.
| Python | apache-2.0 | shubhamdhama/zulip,punchagan/zulip,kou/zulip,showell/zulip,hackerkid/zulip,timabbott/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,zulip/zulip,synicalsyntax/zulip,zulip/zulip,andersk/zulip,shubhamdhama/zulip,showell/zulip,kou/zulip,hackerkid/zulip,shubhamdhama/zulip,andersk/zulip,eeshangarg/zulip,brainwane/zulip,shubh... | ---
+++
@@ -1,4 +1,4 @@
-from django.conf.urls import url
+from django.urls import path
import zerver.views
import zerver.views.streams
import zerver.views.auth
@@ -15,5 +15,5 @@
# for devs, and I don't think we need to go to the server
# any more to find out about subscriptions, since they are already
... |
5b6026bac75ae906d55410c583ebe4a756232dd7 | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
self._setup()
two_years = self.n... | import sys
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
two_years = self.now - relati... | Change functionality depending on where command is called from | Change functionality depending on where command is called from | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -1,3 +1,4 @@
+import sys
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
@@ -7,7 +8,6 @@
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
- self._setup()
two_years = self.now - relativede... |
53e89d0e7af03bd9f59a2e6bcbe6cdbfe8e8f50a | corehq/apps/custom_data_fields/management/commands/convert_custom_user_data.py | corehq/apps/custom_data_fields/management/commands/convert_custom_user_data.py | from django.core.management.base import BaseCommand
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField
from corehq.apps.users.models import CommCareUser
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):... | from django.core.management.base import BaseCommand
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField
from corehq.apps.users.models import CommCareUser
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):... | Drop empty field keys in migration | Drop empty field keys in migration
| Python | bsd-3-clause | puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq | ---
+++
@@ -27,7 +27,7 @@
for user in iter_docs(CommCareUser.get_db(), user_ids):
user_data = user.get('user_data', {})
for key in user_data.keys():
- if key not in existing_field_slugs:
+ if key and key not in existing_field_slugs:
... |
fe47651ddd32a5795dab28ca998230b042a70c59 | app/views/comment_view.py | app/views/comment_view.py | from flask_classy import FlaskView
from flask_user import current_user, login_required
from ..models import CommentModel, PostModel
from ..forms import CommentForm
class Comment(FlaskView):
def get(self):
pass
def all(self, post_id):
comment = CommentModel()
comment.query.add_filter(... | from flask import jsonify
from flask_classy import FlaskView
from flask_user import current_user, login_required
from ..models import CommentModel, PostModel
from ..forms import CommentForm
class Comment(FlaskView):
def get(self):
pass
def all(self, post_id):
comment = CommentModel()
... | Comment all view return a json of all comments | Comment all view return a json of all comments
| Python | mit | oldani/nanodegree-blog,oldani/nanodegree-blog,oldani/nanodegree-blog | ---
+++
@@ -1,3 +1,4 @@
+from flask import jsonify
from flask_classy import FlaskView
from flask_user import current_user, login_required
from ..models import CommentModel, PostModel
@@ -12,8 +13,7 @@
def all(self, post_id):
comment = CommentModel()
comment.query.add_filter('post_id', '=', i... |
5b9f0270aaa53a562ca65fa74769885621da4a8e | website/addons/s3/__init__.py | website/addons/s3/__init__.py | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Am... | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Am... | Change S3 full name to Amazon S3 | Change S3 full name to Amazon S3
| Python | apache-2.0 | hmoco/osf.io,jmcarp/osf.io,abought/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,sloria/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,HarryRybacki/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,wearpants/osf.io,TomBaxter/osf.io,samanehsan/osf.io,zachjanicki/osf.io,mluo613/osf.io,Zobai... | ---
+++
@@ -11,7 +11,7 @@
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
-FULL_NAME = 'Amazon Simple Storage Service'
+FULL_NAME = 'Amazon S3'
OWNERS = ['user', 'node'] |
3a073bb52224876b2424404a59df3c9e3d3fff89 | lesson2/read_passwd/read_passwd.py | lesson2/read_passwd/read_passwd.py | '''
Created on Sep 27, 2013
@author: dgamez
'''
def run():
t = lee_passwd ()
for l in t:
# print l
e = l.split(":")
user = e[0]
shell = e[-1].rstrip("\n")
print "%s -> %s" % (user, shell)
def lee_passwd ():
f = open('/etc/passwd','r')
t = f.readlines ... | '''
Created on Sep 27, 2013
Testing
@author: dgamez
'''
def run():
t = lee_passwd ()
for l in t:
# print l
e = l.split(":")
user = e[0]
shell = e[-1].rstrip("\n")
print "%s -> %s" % (user, shell)
def lee_passwd ():
f = open('/etc/passwd','r')
t = f.rea... | Verify EGit commits/pushes to Master | Verify EGit commits/pushes to Master | Python | bsd-2-clause | gamezdaniel/mswl-dt-2013,gamezdaniel/mswl-dt-2013 | ---
+++
@@ -1,6 +1,6 @@
'''
Created on Sep 27, 2013
-
+Testing
@author: dgamez
'''
|
02e718fb9dd82b252a5726a81eb3a70817d91a88 | test/backend/test_database/__init__.py | test/backend/test_database/__init__.py | # The main Flask application needs to imported before any of the database tests so that linkr.db
# is defined before attempting to access any of the database modules database.*.
# This is the result of a import "race condition" caused by the fact that Flask requires references
# to any libraries to be declared explicit... | Fix import race condition on CI | Fix import race condition on CI
| Python | mit | LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr | ---
+++
@@ -0,0 +1,7 @@
+# The main Flask application needs to imported before any of the database tests so that linkr.db
+# is defined before attempting to access any of the database modules database.*.
+# This is the result of a import "race condition" caused by the fact that Flask requires references
+# to any lib... | |
d18ff30bbddde5049ffbe23bce19288c3c47e41b | posts/views.py | posts/views.py | from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
| from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
def get_queryset(self):
"""
Order posts by the day they were added, from newest, to oldest.... | Order posts from newest to oldest | posts: Order posts from newest to oldest
| Python | mit | rtrembecky/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,matus-stehlik/roots,matus-stehlik/roots,matus-stehlik/glowing-batman,matus-stehlik/roots,matus-stehlik/glowing-batman,rtrembecky/roots,tbabej/roots | ---
+++
@@ -9,6 +9,14 @@
model = Post
context_object_name = 'posts'
+ def get_queryset(self):
+ """
+ Order posts by the day they were added, from newest, to oldest.
+ """
+
+ queryset = super(PostListView, self).get_queryset()
+ return queryset.order_by('-added_at')
... |
dae8420456280fdf1f0971301986995c21fd8027 | static_template_view/views.py | static_template_view/views.py | # View for semi-static templatized content.
#
# List of valid templates is explicitly managed for (short-term)
# security reasons.
from mitxmako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
from django.core.context_processors import csrf
from django.conf import settings
... | # View for semi-static templatized content.
#
# List of valid templates is explicitly managed for (short-term)
# security reasons.
from mitxmako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
from django.core.context_processors import csrf
from django.conf import settings
... | Support for static pages added | Support for static pages added
| Python | agpl-3.0 | appliedx/edx-platform,SivilTaram/edx-platform,inares/edx-platform,shurihell/testasia,zofuthan/edx-platform,wwj718/edx-platform,abdoosh00/edx-rtl-final,10clouds/edx-platform,unicri/edx-platform,Edraak/edx-platform,praveen-pal/edx-platform,jruiperezv/ANALYSE,fly19890211/edx-platform,Lektorium-LLC/edx-platform,morenopc/ed... | ---
+++
@@ -9,8 +9,7 @@
from django.conf import settings
#valid_templates=['index.html', 'staff.html', 'info.html', 'credits.html']
-valid_templates=['mitx_global.html',
- 'index.html',
+valid_templates=['index.html',
'tos.html',
'privacy.html',
... |
b583c5fb00d1ebfa0458a6233be85d8b56173abf | python/printbag.py | python/printbag.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Print a rosbag file.
"""
import sys
import logging
import numpy as np
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
from antlia.dtype import LIDAR_CONVERTED_DTYPE
def print_bag(bag, topics=None):
if topics is No... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Print a rosbag file.
"""
import sys
import logging
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
def print_bag(bag, topics=None):
for message in bag.read_messages(topics=topics):
print(message)
if __name... | Add argument to specify bag topics | Add argument to specify bag topics
| Python | bsd-2-clause | oliverlee/antlia | ---
+++
@@ -2,38 +2,36 @@
# -*- coding: utf-8 -*-
"""Print a rosbag file.
"""
-
import sys
import logging
-
-import numpy as np
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
-from antlia.dtype import LIDAR_CONVERTED_DTYPE
def print_bag(bag, topics=None... |
ca06bf1d52cd51ccec178c98ad407bfe59f1ada1 | strobe.py | strobe.py | import RPi.GPIO as GPIO
from time import sleep
def onoff(period, pin):
"""Symmetric square wave, equal time on/off"""
half_cycle = period / 2.0
GPIO.output(pin, GPIO.HIGH)
sleep(half_cycle)
GPIO.output(pin, GPIO.LOW)
sleep(half_cycle)
def strobe(freq, dur, pin):
nflashes = freq * dur
s... | # Adapted from code by Rahul Kar
# http://www.rpiblog.com/2012/09/using-gpio-of-raspberry-pi-to-blink-led.html
import RPi.GPIO as GPIO
from time import sleep
def onoff(ontime, offtime, pin):
GPIO.output(pin, GPIO.HIGH)
sleep(ontime)
GPIO.output(pin, GPIO.LOW)
sleep(offtime)
def strobe(freq, dur, pin)... | Make onoff function more versatile | Make onoff function more versatile
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie | ---
+++
@@ -1,17 +1,18 @@
+# Adapted from code by Rahul Kar
+# http://www.rpiblog.com/2012/09/using-gpio-of-raspberry-pi-to-blink-led.html
+
import RPi.GPIO as GPIO
from time import sleep
-def onoff(period, pin):
- """Symmetric square wave, equal time on/off"""
- half_cycle = period / 2.0
+def onoff(ontime,... |
aca17ff2fddd35bd50d78d62dc6dab7e47fb8e4e | controllers/default.py | controllers/default.py | import os
def index():
def GET():
return locals()
@request.restful()
def api():
response.view = 'generic.json'
def GET(resource,resource_id):
if not resource=='study': raise HTTP(400)
# return the correct nexson of study_id
return _get_nexson(resource_id)
def POST(resou... | import os
def index():
def GET():
return locals()
@request.restful()
def api():
response.view = 'generic.json'
def GET(resource,resource_id):
if not resource=='study': raise HTTP(400)
# return the correct nexson of study_id
return _get_nexson(resource_id)
def POST(resou... | Use the new location of study NexSON | Use the new location of study NexSON
Each study now has a distinct directory. Currently we only plan to store
a single JSON file in each directory, until one becomes larger than 50MB.
Additionally, this allows various metadata/artifacts about a study to live
near the actually study data.
| Python | bsd-2-clause | OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api | ---
+++
@@ -28,9 +28,8 @@
this_dir = os.path.dirname(os.path.abspath(__file__))
- # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3...
try:
- filename = this_dir + "/../treenexus/study/0/" + study_id + ".json"
+ filename = this_dir +... |
c9355e9ae6815b40dce72df9a9a8b1d8f169a8a3 | tests/test_morando_floripa.py | tests/test_morando_floripa.py | # coding: utf-8
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APIClient
class TestAPIViews(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.client ... | # coding: utf-8
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APIClient
class TestAPIViews(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.client ... | Fix na rota dos testes | Fix na rota dos testes
| Python | mit | AlexandreProenca/backend-morandofloripa,AlexandreProenca/backend-morandofloripa,AlexandreProenca/backend-morandofloripa | ---
+++
@@ -20,14 +20,14 @@
"""
Testa o login com um usuario de testes.
"""
- response = self.client.post(path='/rest-auth/login/', data={"username": 'testuser@test.com', "password": 'testing'}, format='json')
+ response = self.client.post(path='/v1/rest-auth/login/', data={"u... |
a08de1d3c7f7dfc72c8b3b8e9019d1b7b5ad004e | mdtraj/tests/test_load.py | mdtraj/tests/test_load.py | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: y... | from mdtraj import load
from mdtraj.testing import get_fn
def test_load_single():
"""
Just check for any raised errors coming from loading a single file.
"""
load(get_fn('frame0.pdb'))
def test_load_single_list():
"""
See if a single-element list of files is successfully loaded.
"""
lo... | Fix test for loading multiple trajectories. | Fix test for loading multiple trajectories.
| Python | lgpl-2.1 | msultan/mdtraj,rmcgibbo/mdtraj,tcmoore3/mdtraj,mdtraj/mdtraj,jchodera/mdtraj,msultan/mdtraj,ctk3b/mdtraj,ctk3b/mdtraj,mdtraj/mdtraj,msultan/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,jchodera/mdtraj,leeping/mdtraj,gph82/mdtraj,rmcgibbo/mdtraj,gph82/mdtraj,jchodera/mdtraj,mdtraj/mdtraj,leeping/mdtraj,tcmoore3/mdtraj,ct... | ---
+++
@@ -1,30 +1,3 @@
-##############################################################################
-# MDTraj: A Python Library for Loading, Saving, and Manipulating
-# Molecular Dynamics Trajectories.
-# Copyright 2012-2013 Stanford University and the Authors
-#
-# Authors: Robert McGibbon
-# Contributo... |
4456fbdb36b82608501107c4060825377a75c0bf | ColorHistograms-python/color_histogram_cuda.py | ColorHistograms-python/color_histogram_cuda.py | import pycuda.autoinit
import pycuda.driver as drv
import numpy
from scipy import misc
from color_histogram_cuda_module import histogram_atomics, histogram_accum
def histogram(image_path, num_bins):
image = misc.imread(image_path)
bin_size = 256 / num_bins
# calculate image dimensions
(w, h, c) = ima... | import pycuda.autoinit
import pycuda.driver as drv
import numpy
from scipy import misc
from color_histogram_cuda_module import histogram_atomics, histogram_accum
def histogram(image_path, num_bins):
image = misc.imread(image_path)
bin_size = 256 / num_bins
# calculate image dimensions
(w, h, c) = ima... | Change dimensions of output in python wrapper | Change dimensions of output in python wrapper
| Python | bsd-3-clause | kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT | ---
+++
@@ -15,7 +15,7 @@
# reinterpret image with 4-byte type
image = image.view(numpy.uint32)
- dest = numpy.zeros((bin_size, c), numpy.uint32)
+ dest = numpy.zeros((c, bin_size), numpy.uint32)
parts = num_bins * c
block1 = (32, 4, 1)
grid1 = (16, 16, 1) |
b3400070d47d95bfa2eeac3a9f696b8957d88128 | conjureup/controllers/clouds/tui.py | conjureup/controllers/clouds/tui.py | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is no... | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is no... | Fix issue where non localhost headless clouds werent calling finish | Fix issue where non localhost headless clouds werent calling finish
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
| Python | mit | conjure-up/conjure-up,Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up,ubuntu/conjure-up | ---
+++
@@ -33,6 +33,7 @@
events.Shutdown.set(1)
except app.provider.LocalhostError:
raise
+ self.finish()
def render(self):
app.loop.create_task(self._check_lxd_compat()) |
8ed7983859e2b7031b736b92b875040fa13fb39c | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handl... | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handl... | Remove square brackets around log level in log ouput | Remove square brackets around log level in log ouput
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -18,8 +18,8 @@
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
-formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
-formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
+formatterch = logging.Formatter('%(asctime)s %(lev... |
b123001ea0d4fb475184727c39eafd5b46cc0964 | shopit_app/urls.py | shopit_app/urls.py | from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
from authentication_app.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpattern... | from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
from authentication_app.views import AccountViewSet, LoginView, LogoutView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)... | Add the endpoint for the logout. | Add the endpoint for the logout.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | ---
+++
@@ -4,7 +4,7 @@
from rest_framework_nested import routers
from shopit_app.views import IndexView
-from authentication_app.views import AccountViewSet, LoginView
+from authentication_app.views import AccountViewSet, LoginView, LogoutView
router = routers.SimpleRouter()
router.register(r'accounts', Acco... |
0d7921b4dcf5e3b511fdb54fc30ebc0547b14d47 | django_dzenlog/urls.py | django_dzenlog/urls.py | from django.conf.urls.defaults import *
from models import GeneralPost
from feeds import LatestPosts
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
'all': LatestPosts,
}
urlpatterns = patterns('django.views.generic',
(r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'd... | from django.conf.urls.defaults import *
from models import GeneralPost
from feeds import latest
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
'all': latest(GeneralPost, 'dzenlog-post-list'),
}
urlpatterns = patterns('django.views.generic',
(r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.objec... | Use 'latest' to generate feed for GeneralPost. | Use 'latest' to generate feed for GeneralPost.
| Python | bsd-3-clause | svetlyak40wt/django-dzenlog | ---
+++
@@ -1,13 +1,13 @@
from django.conf.urls.defaults import *
from models import GeneralPost
-from feeds import LatestPosts
+from feeds import latest
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
- 'all': LatestPosts,
+ 'all': latest(GeneralPost, 'dzenlog-post-list'),
}
... |
acc6ae5fcdc7cc79b8e6ca76088080c3b73ed4f1 | django_rocket/admin.py | django_rocket/admin.py | from django.contrib import admin
from django_rocket.models import Subscriber
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email', 'created')
date_hierarchy = ('created',)
admin.site.register(Subscriber, SubscriberAdmin) | from django.contrib import admin
from django_rocket.models import Subscriber
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email', 'created')
date_hierarchy = 'created'
admin.site.register(Subscriber, SubscriberAdmin) | Correct mention to date hierachy | Correct mention to date hierachy
| Python | mit | mariocesar/django-rocket,mariocesar/django-rocket | ---
+++
@@ -5,7 +5,7 @@
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email', 'created')
- date_hierarchy = ('created',)
+ date_hierarchy = 'created'
admin.site.register(Subscriber, SubscriberAdmin) |
7269322106911fcb1fb71160421fc3e011fbee1d | byceps/config_defaults.py | byceps/config_defaults.py | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after... | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after... | Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE` | Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE`
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -46,7 +46,6 @@
# home page
ROOT_REDIRECT_TARGET = None
-ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin' |
cab0f9ea3471cf88dd03da7a243ae55579b44b65 | client.py | client.py | #!/usr/env/bin python
import RPi.GPIO as io
import requests
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
switches = set()
def has_free():
... | #!/usr/env/bin python
import RPi.GPIO as io
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
server_url = sys.argv[1]
switches = set()
def has_... | Set server URL with command line argument | Set server URL with command line argument
| Python | mit | madebymany/isthetoiletfree | ---
+++
@@ -1,7 +1,6 @@
#!/usr/env/bin python
import RPi.GPIO as io
-import requests
import sys
class Switch(object):
@@ -15,15 +14,15 @@
PINS = (8, 16, 18)
+server_url = sys.argv[1]
switches = set()
def has_free():
global switches
return not all([s.is_on for s in switches])
-def call_api... |
22ae576872e0cbe2c42e9ec4bddc050a22780531 | bika/lims/upgrade/to1010.py | bika/lims/upgrade/to1010.py | import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def addBatches(tool):
"""
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
setup = port... | import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def addBatches(tool):
"""
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
setup = port... | Fix 1010 upgrade step (setBatchID -> setBatch) | Fix 1010 upgrade step (setBatchID -> setBatch)
| Python | agpl-3.0 | DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,anneline/Bika-LIMS,rockfruit/bika.lims,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS | ---
+++
@@ -33,11 +33,11 @@
# and place it after ClientFolder
portal.moveObjectToPosition('batches', portal.objectIds().index('clients'))
- # add BatchID to all AnalysisRequest objects.
+ # add Batch to all AnalysisRequest objects.
# When the objects are reindexed, BatchUID will also be populat... |
384beaa77e2eaad642ec7f764acd09c2c3e04350 | res_company.py | res_company.py | from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remittance Letter '
... | from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remittance Letter '
... | Make Remittance Letter config messages translatable | Make Remittance Letter config messages translatable
| Python | agpl-3.0 | xcgd/account_streamline | ---
+++
@@ -10,12 +10,12 @@
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remittance Letter '
'reports. Available variables: "$iban" for the IBAN; "$date" for '
- 'the payment date. HTML tags are allowed.')
- ),
+ 'the ... |
550a3f2b402f841d740cdbd6a25e832aab0fd974 | oneflow/settings/chani.py | oneflow/settings/chani.py | # -*- coding: utf-8 -*-
# Settings for 1flow.net (local development)
MAIN_SERVER = '127.0.0.1'
from sparks.django.settings import include_snippets
include_snippets(
(
# Don't forget to deactivate nobother when we'ge got time to
# fix other's bugs. Just kidding…
'000_nobother',
'00... | # -*- coding: utf-8 -*-
# Settings for 1flow.net (local development)
MAIN_SERVER = '127.0.0.1'
import socket
from sparks.django.settings import include_snippets
include_snippets(
(
# Don't forget to deactivate nobother when we'ge got time to
# fix other's bugs. Just kidding…
'000_nobother... | Make lil&big merged configuration hostname-aware for SITE_DOMAIN, this fixes the bad hostname in JS bookmarklets. | Make lil&big merged configuration hostname-aware for SITE_DOMAIN, this fixes the bad hostname in JS bookmarklets. | Python | agpl-3.0 | 1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow | ---
+++
@@ -3,6 +3,7 @@
MAIN_SERVER = '127.0.0.1'
+import socket
from sparks.django.settings import include_snippets
include_snippets(
@@ -30,6 +31,7 @@
ALLOWED_HOSTS += [
'lil.1flow.io',
+ 'big.1flow.io',
'chani.licorn.org',
'duncan.licorn.org',
'leto.licorn.org',
@@ -37,7 +39,10 @... |
a0c656f89829ca18c383f1884e3186103b9e5fa6 | fabfile.py | fabfile.py | from fabric.api import cd, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
with cd("~/vagrant-installers"):
run("git pull")
| from fabric.api import cd, env, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
with cd("~/vagrant-installers"):
run("git pull")
@task
def all():
"Run the task against all hosts."
for _, value in env.roledefs.iteritems():
... | Allow the targetting of specific roles with fabric | Allow the targetting of specific roles with fabric
| Python | mit | redhat-developer-tooling/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,mitchellh/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,chrisroberts/vagrant-installers,redhat-developer-tooling/vagrant... | ---
+++
@@ -1,4 +1,4 @@
-from fabric.api import cd, run, task
+from fabric.api import cd, env, run, task
try:
import fabfile_local
@@ -10,3 +10,14 @@
def update():
with cd("~/vagrant-installers"):
run("git pull")
+
+@task
+def all():
+ "Run the task against all hosts."
+ for _, value in e... |
813dd27a2057d2e32726ff6b43ab8ca1411303c7 | fabfile.py | fabfile.py | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('python sana_builder/manage... | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('python sana_builder/manage... | Prepare for deploy in deploy script. | Prepare for deploy in deploy script.
| Python | bsd-3-clause | SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder | ---
+++
@@ -12,6 +12,8 @@
local('git push')
def deploy():
+ prepare_deploy()
+
with cd(env.project_root), prefix('workon sana_protocol_builder'):
print(green('Pulling latest revision...'))
run('git pull') |
e8f8407ee422375af07027af2846a95c9cfaad37 | fabfile.py | fabfile.py | #!/usr/bin/env python
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def push_code():
rsync... | #!/usr/bin/env python
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def push_code():
rsync... | Use checksum when pushing code with rsync | Use checksum when pushing code with rsync
| Python | mit | Foxboron/Frank,Foxboron/Frank,mpolden/jarvis2,Foxboron/Frank,martinp/jarvis2,martinp/jarvis2,mpolden/jarvis2,mpolden/jarvis2,martinp/jarvis2 | ---
+++
@@ -17,7 +17,7 @@
@task
def push_code():
rsync_project(local_dir='.', remote_dir=home, exclude=('.git', '.vagrant'),
- extra_opts='--filter=":- .gitignore"')
+ extra_opts='--checksum --filter=":- .gitignore"')
@task |
b374221d8d0e902494066d666570c1a882c962bc | s3img_magic.py | s3img_magic.py | from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_k... | from StringIO import StringIO
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_bucket(bucket_name):
conn = boto.connect_s3()
r... | Add magic to save a Matplotlib figure to S3 | Add magic to save a Matplotlib figure to S3
| Python | mit | AustinRochford/s3img-ipython-magic,AustinRochford/s3img-ipython-magic | ---
+++
@@ -1,6 +1,10 @@
+from StringIO import StringIO
+
+from IPython.core.magic import Magics, magics_class, line_magic
from IPython.display import Image
import boto
+
def parse_s3_uri(uri):
if uri.startswith('s3://'):
@@ -9,13 +13,24 @@
return uri.split('/', 1)
+def get_s3_bucket(bucket_name)... |
db06039ecb94100bbecb23b5fdee13e306458809 | atlassian/__init__.py | atlassian/__init__.py | import logging
from urllib.parse import urlsplit, urljoin
from requests import get
l = logging.getLogger(__name__)
#TODO: move this somewhere sensible
#TODO: useful error handling (CLI...)
class HTTPClient:
def __init__(self, base, user=None, password=None):
self.base = base
self.user = user
... | import logging
from urllib.parse import urlsplit, urljoin
from requests import get
#TODO: move this somewhere sensible
#TODO: useful error handling (CLI...)
class HTTPClient:
def __init__(self, base, user=None, password=None):
self.base = base
self.user = user
self.password = password
... | Fix big fuckup from last commit | Fix big fuckup from last commit
| Python | mit | victorhahncastell/atlassian_permissions,victorhahncastell/atlassian_permissions | ---
+++
@@ -1,8 +1,6 @@
import logging
from urllib.parse import urlsplit, urljoin
from requests import get
-
-l = logging.getLogger(__name__)
#TODO: move this somewhere sensible
#TODO: useful error handling (CLI...)
@@ -13,16 +11,14 @@
self.password = password
def get(self, url):
- reque... |
c58ac76b2d0e575068a050f87f1cc0eb6ef09014 | autocloud/__init__.py | autocloud/__init__.py | # -*- coding: utf-8 -*-
import ConfigParser
import os
DEBUG = True
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
if DEBUG:
config.read("{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT))
else:
config.read('/etc/autocloud/autocl... | # -*- coding: utf-8 -*-
import ConfigParser
import os
DEBUG = True
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
if DEBUG:
config.read("{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT))
else:
config.read('/etc/autocloud/autocl... | Add redis config path format | Add redis config path format
| Python | agpl-3.0 | maxamillion/autocloud,maxamillion/autocloud,kushaldas/autocloud,maxamillion/autocloud,kushaldas/autocloud,kushaldas/autocloud,maxamillion/autocloud,kushaldas/autocloud | ---
+++
@@ -17,7 +17,8 @@
BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url')
if DEBUG:
- REDIS_CONFIG_FILEPATH = "{PROJECT_ROOT}/config/redis_server.json"
+ REDIS_CONFIG_FILEPATH = "{PROJECT_ROOT}/config/redis_server.json".format(
+ PROJECT_ROOT=PROJECT_ROOT)
else:
REDIS_CONFIG_... |
b7aa7e85064430dc95e74a0f676f0484fee12733 | tests/cli/test_pinout.py | tests/cli/test_pinout.py | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import pytest
from gpiozero.cli import pinout
def test_args_incorrect():
with pytest.raises(SystemExit) as ex:
pinout.parse_args(['--nonexistentarg'])
def test_args_color():
a... | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import pytest
from gpiozero.cli.pinout import main
def test_args_incorrect():
with pytest.raises(SystemExit) as ex:
main(['pinout', '--nonexistentarg'])
def test_args_color():
... | Fix up pinout tests so they work with new structure | Fix up pinout tests so they work with new structure
| Python | bsd-3-clause | MrHarcombe/python-gpiozero,waveform80/gpio-zero,RPi-Distro/python-gpiozero | ---
+++
@@ -9,27 +9,27 @@
import pytest
-from gpiozero.cli import pinout
+from gpiozero.cli.pinout import main
def test_args_incorrect():
with pytest.raises(SystemExit) as ex:
- pinout.parse_args(['--nonexistentarg'])
+ main(['pinout', '--nonexistentarg'])
def test_args_color():
- a... |
0ef346389b680e81ab618d4d782239640c1926f5 | tests/test_collection.py | tests/test_collection.py | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
... | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
... | Remove unnecessary test of collection children | Remove unnecessary test of collection children
| Python | agpl-3.0 | UMD-DRASTIC/drastic | ---
+++
@@ -37,5 +37,3 @@
assert coll.get_child_collection_count() == 2
- assert str(children[0].id) == str(child1.id)
- assert str(children[1].id) == str(child2.id) |
afa10a27aa1fe1eaa719d988902c2f3f4d5d0928 | webapp/controllers/contact.py | webapp/controllers/contact.py | # -*- coding: utf-8 -*-
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call(): return service()
### end requires
def index():
return dict()
| # -*- coding: utf-8 -*-
from opentreewebapputil import (get_opentree_services_method_urls,
fetch_current_TNRS_context_names)
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call(): return service()
### end requir... | Fix missing search-context list on Contact page. | Fix missing search-context list on Contact page.
| Python | bsd-2-clause | OpenTreeOfLife/opentree,OpenTreeOfLife/opentree,OpenTreeOfLife/opentree,OpenTreeOfLife/opentree,OpenTreeOfLife/opentree,OpenTreeOfLife/opentree | ---
+++
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+from opentreewebapputil import (get_opentree_services_method_urls,
+ fetch_current_TNRS_context_names)
### required - do no delete
def user(): return dict(form=auth())
@@ -6,6 +8,9 @@
def call(): return service()
### end requires
... |
c7dbf93c123d4b055fcd4a73e5d3374e48ee248a | pegasus/service/server.py | pegasus/service/server.py | import os
import logging
from optparse import OptionParser
from pegasus.service import app, em
from pegasus.service.command import Command
class ServerCommand(Command):
usage = "%prog [options]"
description = "Start Pegasus Service"
def __init__(self):
Command.__init__(self)
self.parser.a... | import os
import logging
from optparse import OptionParser
from pegasus.service import app, em
from pegasus.service.command import Command
log = logging.getLogger("server")
class ServerCommand(Command):
usage = "%prog [options]"
description = "Start Pegasus Service"
def __init__(self):
Command._... | Allow service to start without EM if Condor and Pegasus are missing | Allow service to start without EM if Condor and Pegasus are missing
| Python | apache-2.0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus-service,pegasus-isi/pegasus-service,pegasus-isi/pegasus-service,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | ---
+++
@@ -4,6 +4,8 @@
from pegasus.service import app, em
from pegasus.service.command import Command
+
+log = logging.getLogger("server")
class ServerCommand(Command):
usage = "%prog [options]"
@@ -20,8 +22,6 @@
logging.basicConfig(level=logging.INFO)
- # Make sure the environment i... |
6858e4a2e2047c906a3b8f69b7cd7b04a0cbf666 | pivoteer/writer/censys.py | pivoteer/writer/censys.py | """
Classes and functions for writing IndicatorRecord objects with a record type of "CE" (Censys Record)
"""
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(se... | """
Classes and functions for writing IndicatorRecord objects with a record type of "CE" (Censys Record)
"""
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(se... | Resolve issues with exporting empty dataset for certificate list | Resolve issues with exporting empty dataset for certificate list
| Python | mit | gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID | ---
+++
@@ -18,6 +18,7 @@
"""
super(CensysCsvWriter, self).__init__(writer)
+
def create_title_rows(self, indicator, records):
yield ["Certificate Search Results"]
@@ -25,14 +26,15 @@
return ["Subject", "Issuer", "SHA256", "Validity Start", "Validity End"]
def creat... |
4a6a2155878d309e6bc96a948811daafa4a92908 | protocols/no_reconnect.py | protocols/no_reconnect.py | try:
from .. import api, shared as G
from ... import editor
from ..exc_fmt import str_e
from ..protocols import floo_proto
except (ImportError, ValueError):
from floo import editor
from floo.common import api, shared as G
from floo.common.exc_fmt import str_e
from floo.common.protocols i... | try:
from .. import api, shared as G
from ... import editor
from ..exc_fmt import str_e
from ..protocols import floo_proto
except (ImportError, ValueError):
from floo import editor
from floo.common import api, shared as G
from floo.common.exc_fmt import str_e
from floo.common.protocols i... | Call connect instead of reconnect. | Call connect instead of reconnect.
| Python | apache-2.0 | Floobits/plugin-common-python | ---
+++
@@ -25,6 +25,6 @@
else:
if not G.OUTBOUND_FILTERING:
G.OUTBOUND_FILTERING = True
- return super(NoReconnectProto, self).reconnect()
+ return self.connect()
editor.error_message('Something went wrong. See https://%s/help/floorc t... |
87d1801fefcd048f60c944c28bfc005101c5704b | dynd/tests/test_nd_groupby.py | dynd/tests/test_nd_groupby.py | import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dtype='{A: string; B: int32}'... | import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dtype='{A: string; B: int32}'... | Add some more simple nd.groupby tests | Add some more simple nd.groupby tests
| Python | bsd-2-clause | cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,insertinterestingnamehere/dynd-python,aterrel/dynd-python,cpcloud/dynd-python,cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,mwiebe/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,pombredanne/dynd-py... | ---
+++
@@ -20,5 +20,18 @@
[{'A': 'y', 'B': 1},
{'A': 'y', 'B': 4}]])
+ def test_grouped_slices(self):
+ a = nd.asarray([[1, 2, 3], [1, 4, 5]])
+ gb = nd.groupby(a[:, 1:], a[:, 0])
+ self.assertEqual(nd.as_py(gb.groups), [1])
+ self.assertEqual(nd.as... |
7b935b23e17ef873a060fdfbefbfdf232fe8b8de | git_release/release.py | git_release/release.py | import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
new_minor = 0
else... | import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
new_minor = 0
else... | Add missing argument to _increment_tag call | Add missing argument to _increment_tag call
| Python | mit | Authentise/git-release | ---
+++
@@ -24,6 +24,6 @@
if not tag:
raise errors.NoTagException("Unable to get current tag.\nAborting.")
- new_tag = _increment_tag(tag)
+ new_tag = _increment_tag(tag, release_type)
git_helpers.tag(signed, new_tag) |
14f4fe95be0501142f929a9b7bec807fd14e3d6f | eva/layers/residual_block.py | eva/layers/residual_block.py | from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from keras.engine.topology import merge
from eva.layers.masked_convolution2d import MaskedConvolution2D
def ResidualBlock(model, filters):
# 2h -> h
block = Convolution2D(filters//2, 1, 1)(model)
block = PReL... | from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from eva.layers.masked_convolution2d import MaskedConvolution2D
def ResidualBlock(model, filters):
# 2h -> h
block = PReLU()(model)
block = MaskedConvolution2D(filters//2, 1, 1)(block)
# h 3x3 -> h
b... | Fix residual blocks to be on-par with paper. | Fix residual blocks to be on-par with paper.
| Python | apache-2.0 | israelg99/eva | ---
+++
@@ -1,22 +1,22 @@
from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
-from keras.engine.topology import merge
from eva.layers.masked_convolution2d import MaskedConvolution2D
def ResidualBlock(model, filters):
# 2h -> h
- block = Convolution2D(filt... |
7f5d6e4386e3a80db5cfcbf961c7603b0c78cc52 | openxc/sources/serial.py | openxc/sources/serial.py | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
class Serial... | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
class Serial... | Make sure LOG is defined before using it. | Make sure LOG is defined before using it.
| Python | bsd-3-clause | openxc/openxc-python,openxc/openxc-python,openxc/openxc-python | ---
+++
@@ -3,14 +3,14 @@
import logging
+from .base import BytestreamDataSource, DataSourceError
+
+LOG = logging.getLogger(__name__)
+
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
-
-from .base import BytestreamDataSource, DataSourceEr... |
fcfceb59cbd368ddaee87906d3f53f15bbb30072 | examples/tornado/auth_demo.py | examples/tornado/auth_demo.py | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | Add the settings to the authdemo. | Add the settings to the authdemo. | Python | bsd-3-clause | solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2 | ---
+++
@@ -16,6 +16,6 @@
]
)
-commit([main])
+commit([main], settings={'limits.buffer_size': 4 * 1024})
|
f783d8ac4314923f1259208eb221c8874c03884a | calexicon/fn/iso.py | calexicon/fn/iso.py | from datetime import date as vanilla_date, timedelta
from overflow import OverflowDate
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError(
"Week number %d is invalid for an ISO calendar."
% (week, )
)
jan_8 = vanilla_date(year, 1, 8).... | from datetime import date as vanilla_date, timedelta
from overflow import OverflowDate
def _check_week(week):
if week < 1 or week > 54:
raise ValueError(
"Week number %d is invalid for an ISO calendar."
% (week, )
)
def iso_to_gregorian(year, week, weekday):
_check_w... | Move check for week number out into function. | Move check for week number out into function.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | ---
+++
@@ -3,12 +3,16 @@
from overflow import OverflowDate
-def iso_to_gregorian(year, week, weekday):
+def _check_week(week):
if week < 1 or week > 54:
raise ValueError(
"Week number %d is invalid for an ISO calendar."
% (week, )
)
+
+
+def iso_to_gregorian(year... |
11aab47e3c8c0d4044042aead7c01c990a152bea | tests/integration/customer/test_dispatcher.py | tests/integration/customer/test_dispatcher.py | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCa... | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCa... | Add tests for sending messages to emails without account. | Add tests for sending messages to emails without account.
| Python | bsd-3-clause | sonofatailor/django-oscar,solarissmoke/django-oscar,okfish/django-oscar,okfish/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,okfish... | ---
+++
@@ -39,3 +39,7 @@
message = mail.outbox[0]
self.assertIn(order_number, message.body)
+ # test sending messages to emails without account and text body
+ messages.pop('body')
+ dispatcher.dispatch_direct_messages(email, messages)
+ self.assertEqual(len(mail.outbo... |
ec7647c264bb702d4211779ef55ca5a694307faf | 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 | : Create documentation of DataSource Settings
Task-Url: | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -14,12 +14,8 @@
import ibmcnx.functions
-print AdminControl.getCell()
-cell = "/Cell:" + AdminControl.getCell() + "/"
-cellid = AdminConfig.getid( cell )
-dbs = AdminConfig.list( 'DataSource', str(cellid) )
-dbs = dbs.split('(')
-print dbs
+dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activit... |
1bdf4e29daaf896fb6bf3416e0cae65cd8144e6f | falcon_hateoas/middleware.py | falcon_hateoas/middleware.py | import json
import decimal
import sqlalchemy
class AlchemyJSONEncoder(json.JSONEncoder):
def default(self, o):
# if isinstance(getattr(o, 'metadata'), sqlalchemy.schema.MetaData):
if issubclass(o.__class__,
sqlalchemy.ext.declarative.DeclarativeMeta):
d = {}
... | import json
import decimal
import sqlalchemy
class AlchemyJSONEncoder(json.JSONEncoder):
def _is_alchemy_object(self, obj):
try:
sqlalchemy.orm.base.object_mapper(obj)
return True
except sqlalchemy.orm.exc.UnmappedInstanceError:
return False
def default(sel... | Use SQLAlchemy object_mapper for testing Alchemy objects | Use SQLAlchemy object_mapper for testing Alchemy objects
Signed-off-by: Michal Juranyi <29976087921aeab920eafb9b583221faa738f3f4@vnet.eu>
| Python | mit | Vnet-as/falcon-hateoas | ---
+++
@@ -4,10 +4,15 @@
class AlchemyJSONEncoder(json.JSONEncoder):
+ def _is_alchemy_object(self, obj):
+ try:
+ sqlalchemy.orm.base.object_mapper(obj)
+ return True
+ except sqlalchemy.orm.exc.UnmappedInstanceError:
+ return False
+
def default(self, o):... |
c4103c00b51ddb9cb837d65b43c972505e533bdc | tilescraper.py | tilescraper.py | from PIL import Image
import json, StringIO, requests
import time
service = "http://dlss-dev-azaroth.stanford.edu/services/iiif/f1rc/"
resp = requests.get(service + "info.json")
js = json.loads(resp.text)
h = js['height']
w = js['width']
img = Image.new("RGB", (w,h), "white")
tilesize = 400
for x in range(w/tilesize+... | from PIL import Image
import json, StringIO, requests
import time
import robotparser
import re
host = "http://dlss-dev-azaroth.stanford.edu/"
service = host + "services/iiif/f1rc/"
resp = requests.get(service + "info.json")
js = json.loads(resp.text)
h = js['height']
w = js['width']
img = Image.new("RGB", (w,h), "whi... | Add in good practices for crawling | Add in good practices for crawling
| Python | apache-2.0 | azaroth42/iiif-harvester | ---
+++
@@ -1,14 +1,40 @@
from PIL import Image
import json, StringIO, requests
import time
+import robotparser
+import re
-service = "http://dlss-dev-azaroth.stanford.edu/services/iiif/f1rc/"
+host = "http://dlss-dev-azaroth.stanford.edu/"
+
+service = host + "services/iiif/f1rc/"
resp = requests.get(service +... |
7873017564570dd993a19648e3c07f0d2e79ec19 | dodocs/profiles/remove.py | dodocs/profiles/remove.py | """Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogge... | """Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogg... | Adjust logging and fix module documentation | Adjust logging and fix module documentation
| Python | mit | montefra/dodocs | ---
+++
@@ -1,4 +1,4 @@
-"""Create the profile.
+"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
@@ -22,13 +22,13 @@
for name in args.name:
dlog.set_profile(name)
- log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not pro... |
0ceadc93f0798bd04404cb18d077269f19111438 | nap/auth.py | nap/auth.py | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_... | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_... | Fix wrong paramter name in permit_groups decorator | Fix wrong paramter name in permit_groups decorator
| Python | bsd-3-clause | MarkusH/django-nap,limbera/django-nap | ---
+++
@@ -26,7 +26,7 @@
def permit_groups(*groups):
def in_groups(request, *args):
- return request.user.groups.filter(name__in=args).exists()
+ return request.user.groups.filter(name__in=groups).exists()
return permit(
lambda self, *args, **kwargs: in_groups(self.request, *group... |
f3efb01c530db87f48d813b118f80a2ee1fd5996 | dthm4kaiako/users/apps.py | dthm4kaiako/users/apps.py | """Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon intialising application."""... | """Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon intialising application."""... | Exclude import from style checking | Exclude import from style checking
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -11,4 +11,4 @@
def ready(self):
"""Import signals upon intialising application."""
- import users.signals
+ import users.signals # noqa F401 |
6454372da6550455735cbcb3a86a966e61c134a1 | elasticsearch/__init__.py | elasticsearch/__init__.py | from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
RoundRobinSelec... | from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
RoundRobinSelec... | Allow people to import ThriftConnection from elasticsearch package itself | Allow people to import ThriftConnection from elasticsearch package itself
| Python | apache-2.0 | veatch/elasticsearch-py,chrisseto/elasticsearch-py,Garrett-R/elasticsearch-py,brunobell/elasticsearch-py,tailhook/elasticsearch-py,AlexMaskovyak/elasticsearch-py,brunobell/elasticsearch-py,mjhennig/elasticsearch-py,thomdixon/elasticsearch-py,kelp404/elasticsearch-py,gardsted/elasticsearch-py,elastic/elasticsearch-py,el... | ---
+++
@@ -10,6 +10,6 @@
RoundRobinSelector
from elasticsearch.serializer import JSONSerializer
from elasticsearch.connection import Connection, RequestsHttpConnection, \
- Urllib3HttpConnection, MemcachedConnection
+ Urllib3HttpConnection, MemcachedConnection, ThriftConnection
from elasticsearch.excep... |
4a37feed87efa3dd05e38ad6f85afe392afd3a16 | gitless/cli/gl_switch.py | gitless/cli/gl_switch.py | # -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git.
# Licensed under GNU GPL v2.
"""gl switch - Switch branches."""
from __future__ import unicode_literals
from clint.textui import colored
from . import pprint
def parser(subparsers, _):
"""Adds the switch parser to the given subpa... | # -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git.
# Licensed under GNU GPL v2.
"""gl switch - Switch branches."""
from __future__ import unicode_literals
from clint.textui import colored
from . import pprint
def parser(subparsers, _):
"""Adds the switch parser to the given subpa... | Fix ui bug in switch | Fix ui bug in switch
| Python | mit | sdg-mit/gitless,sdg-mit/gitless | ---
+++
@@ -29,7 +29,7 @@
b = repo.lookup_branch(args.branch)
if not b:
- pprint.err('Branch {0} doesn\'t exist'.format(colored.green(args.branch)))
+ pprint.err('Branch {0} doesn\'t exist'.format(args.branch))
pprint.err_exp('to list existing branches do gl branch')
return False
|
f46a0cdf869b8629a1e4a08105a065933d4199f9 | climlab/__init__.py | climlab/__init__.py | __version__ = '0.4.3.dev0'
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.m... | __version__ = '0.5.0.dev0'
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.m... | Increment version number to 0.5.0.dev0 | Increment version number to 0.5.0.dev0
| Python | mit | cjcardinale/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab,brian-rose/climlab | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '0.4.3.dev0'
+__version__ = '0.5.0.dev0'
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants |
56446567f764625e88d8efdbfa2849e0a579d5c4 | indra/tests/test_rest_api.py | indra/tests/test_rest_api.py | import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "ME... | import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "ME... | Update REST API address in test | Update REST API address in test
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/indra | ---
+++
@@ -4,7 +4,7 @@
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT":... |
4ec9d5a5a59c1526a846f6d88f1e43154e859fb7 | report_context/controllers/main.py | report_context/controllers/main.py | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import json
from odoo.http import request, route
from odoo.addons.web.controllers import main as report
class ReportController(report.ReportController):
@route()
def report_routes(self, reportname, docids=None... | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import json
from odoo.http import request, route
from odoo.addons.web.controllers import main as report
class ReportController(report.ReportController):
@route()
def report_routes(self, reportname, docids=None... | Fix json.loads when context is None | Fix json.loads when context is None
Co-authored-by: Pierre Verkest <94ea506e1738fc492d3f7a19e812079abcde2af1@gmail.com> | Python | agpl-3.0 | OCA/reporting-engine,OCA/reporting-engine,OCA/reporting-engine,OCA/reporting-engine | ---
+++
@@ -11,7 +11,7 @@
@route()
def report_routes(self, reportname, docids=None, converter=None, **data):
report = request.env["ir.actions.report"]._get_report_from_name(reportname)
- original_context = json.loads(data.get("context", "{}"))
+ original_context = json.loads(data.get(... |
6bdbbf4d5e100856acbaba1c5fc024a9f7f78718 | tests/tools.py | tests/tools.py | """
Test tools required by multiple suites.
"""
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.form... | """
Test tools required by multiple suites.
"""
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
from brandon import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--sta... | Test tool to create temporary devpi index. | Test tool to create temporary devpi index.
| Python | bsd-3-clause | tylerdave/devpi-builder | ---
+++
@@ -10,6 +10,7 @@
import subprocess
import tempfile
+from brandon import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
@@ -22,3 +23,22 @@
subprocess.check_call(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)])
finally:
shutil.rmtree(server_dir)... |
8460b1249d1140234798b8b7e482b13cde173a1e | bluebottle/settings/jenkins.py | bluebottle/settings/jenkins.py | # NOTE: local.py must be an empty file when using this configuration.
from .defaults import *
# Put jenkins environment specific overrides below.
INSTALLED_APPS += ('django_jenkins',)
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db... | # NOTE: local.py must be an empty file when using this configuration.
from .defaults import *
# Put jenkins environment specific overrides below.
INSTALLED_APPS += ('django_jenkins',)
SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q=='
DATABASES = {
'default': {
'ENGINE': 'django.db... | Disable django.contrib.sites tests in Jenkins. | Disable django.contrib.sites tests in Jenkins.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -25,6 +25,11 @@
# https://code.djangoproject.com/ticket/17966
PROJECT_APPS.remove('django.contrib.auth')
+# This app fails with a strange error:
+# DatabaseError: no such table: django_comments
+# Not sure what's going on so it's disabled for now.
+PROJECT_APPS.remove('django.contrib.sites')
+
# https... |
21a6ddca55c8b5da70d806afa18f08ac20cb04c0 | src/zsl/interface/webservice/performers/method.py | src/zsl/interface/webservice/performers/method.py | """
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module, reload
import sys
from zsl.router.method import get_method_packages
def call_expose... | """
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module
import sys
from zsl.router.method import get_method_packages
def call_exposers_in_me... | Remove the unused import and fix testing library | Remove the unused import and fix testing library
| Python | mit | AtteqCom/zsl,AtteqCom/zsl | ---
+++
@@ -7,7 +7,7 @@
from __future__ import unicode_literals
import logging
-from importlib import import_module, reload
+from importlib import import_module
import sys
|
497990c526add919dc31965b0afd49d86ace49cf | models.py | models.py | import datetime
import mongoengine
from mongoengine.django import auth
from piplmesh.account import fields
class User(auth.User):
birthdate = fields.LimitedDateTimeField(upper_limit=datetime.datetime.today(), lower_limit=datetime.datetime.today() - datetime.timedelta(366 * 120))
gender = fields.GenderField()... | import datetime
import mongoengine
from mongoengine.django import auth
from piplmesh.account import fields
class User(auth.User):
birthdate = fields.LimitedDateTimeField(upper_limit=datetime.date.today(), lower_limit=datetime.date.today() - datetime.timedelta(366 * 120))
gender = fields.GenderField()
lan... | Change date's limits format to datetime.date. | Change date's limits format to datetime.date.
| Python | agpl-3.0 | mitar/django-mongo-auth,mitar/django-mongo-auth,mitar/django-mongo-auth | ---
+++
@@ -6,7 +6,7 @@
from piplmesh.account import fields
class User(auth.User):
- birthdate = fields.LimitedDateTimeField(upper_limit=datetime.datetime.today(), lower_limit=datetime.datetime.today() - datetime.timedelta(366 * 120))
+ birthdate = fields.LimitedDateTimeField(upper_limit=datetime.date.today... |
392bdf5845be19ece8f582f79caf2d09a0af0dfb | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apps.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
# manage.py script of cronos
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apps.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Add header, needed for the upcoming changes in the update_cronos.sh script | Add header, needed for the upcoming changes in the update_cronos.sh
script
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr | ---
+++
@@ -1,4 +1,6 @@
#!/usr/bin/env python
+# manage.py script of cronos
+
import os
import sys
|
6891edfe6228654940808a93fd36bfa6d24ae935 | marionette/tor_browser_tests/test_screenshots.py | marionette/tor_browser_tests/test_screenshots.py | from marionette_driver import By
from marionette_driver.errors import MarionetteException
from marionette_harness import MarionetteTestCase
import testsuite
class Test(MarionetteTestCase):
def setUp(self):
MarionetteTestCase.setUp(self)
ts = testsuite.TestSuite()
self.ts = ts
se... | from marionette_driver import By
from marionette_driver.errors import MarionetteException
from marionette_harness import MarionetteTestCase
import testsuite
class Test(MarionetteTestCase):
def setUp(self):
MarionetteTestCase.setUp(self)
ts = testsuite.TestSuite()
self.ts = ts
se... | Fix url for screenshot test | Fix url for screenshot test
| Python | bsd-3-clause | boklm/tbb-testsuite,boklm/tbb-testsuite,boklm/tbb-testsuite,boklm/tbb-testsuite,boklm/tbb-testsuite | ---
+++
@@ -13,7 +13,7 @@
self.ts = ts
self.URLs = [
- 'chrome://torlauncher/content/network-settings-wizard.xul',
+ 'chrome://torlauncher/content/network-settings-wizard.xhtml',
];
def test_check_tpo(self): |
6dfd6a4ae687dc9c7567c74a6c3ef3bd0f9dc5a1 | ci_scripts/buildLinuxWheels.py | ci_scripts/buildLinuxWheels.py | from subprocess import call, check_output
import sys
import os
isPython3 = sys.version_info.major == 3
# https://stackoverflow.com/a/3357357
command = 'git log --format=%B -n 1'.split()
out = check_output(command)
if b'build wheels' not in out.lower() or not isPython3:
exit(0)
path = os.path.abspath(sys.argv[1]... | from subprocess import call, check_output
import sys
import os
isPython3 = sys.version_info.major == 3
# https://stackoverflow.com/a/3357357
command = 'git log --format=%B -n 1'.split()
out = check_output(command)
if b'build wheels' not in out.lower() or not isPython3:
exit(0)
path = os.path.abspath(sys.argv[1]... | Fix build wheels and upload 5. | Fix build wheels and upload 5.
| Python | bsd-3-clause | jr-garcia/AssimpCy,jr-garcia/AssimpCy | ---
+++
@@ -15,6 +15,7 @@
call('pip install cibuildwheel==0.7.0'.split())
call('cibuildwheel --output-dir {}'.format(sys.argv[1]).split())
+call('pip install dropbox'.split())
from dropboxUpload import uploadAll
uploadAll(path) |
6d291571dca59243c0a92f9955776e1acd2e87da | falmer/content/queries.py | falmer/content/queries.py | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_... | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_... | Return empty result rather than graphql error | Return empty result rather than graphql error
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | ---
+++
@@ -21,7 +21,7 @@
result = root_page.route(info.context, path.split('/'))
return result.page
except Http404:
- raise GraphQLError(f'404: Page not found for {path}')
+ return None
def resolve_all_pages(self, info):
return Page.objects.spe... |
819ed0ededbdc8ebe150e5ce9f507c9607e2b724 | greins/__init__.py | greins/__init__.py | version_info = (0, 2, 0)
__version__ = ".".join(map(str, version_info))
| version_info = (0, 1, 0)
__version__ = ".".join(map(str, version_info))
| Revert "bump version" -- Not ready to release yet | Revert "bump version" -- Not ready to release yet
This reverts commit 60e383ce1e4432c360e615598813e3b1747befb8.
| Python | mit | meebo/greins,meebo/greins,harrisonfeng/greins,harrisonfeng/greins | ---
+++
@@ -1,3 +1,3 @@
-version_info = (0, 2, 0)
+version_info = (0, 1, 0)
__version__ = ".".join(map(str, version_info))
|
af2885d2bc9d2dfefd39e5d1dab53da137c793c2 | builders/horizons_telnet.py | builders/horizons_telnet.py | #!/usr/bin/env python2.7
#import argparse
from telnetlib import Telnet
def main(in_path, out_path):
with open(in_path) as f:
lines = f.read().split('\n')
tn = Telnet('horizons.jpl.nasa.gov', 6775)
out = open(out_path, 'w')
for line in lines:
print(repr(line))
tn.write(line + '\... | #!/usr/bin/env python2.7
#import argparse
from telnetlib import Telnet
def main(in_path, out_path):
with open(in_path) as f:
lines = f.read().split('\n')
tn = Telnet('horizons.jpl.nasa.gov', 6775)
out = open(out_path, 'w')
for line in lines:
print(repr(line))
tn.write(line + '\... | Fix filename error in HORIZONS telnet script | Fix filename error in HORIZONS telnet script
| Python | mit | GuidoBR/python-skyfield,exoanalytic/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,skyfielders/python-skyfield,ozialien/python-skyfield,GuidoBR/python-skyfield | ---
+++
@@ -18,7 +18,7 @@
if __name__ == '__main__':
try:
- main('horizons-input.txt', 'horizons-output.txt')
+ main('horizons_input.txt', 'horizons_output.txt')
except EOFError:
print
print('EOF') |
bf2502fc45854db8ce7666c9fa511d487eccfb2e | pavement.py | pavement.py | from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Ex... | from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Ex... | Rename package "si_prefix" to "si-prefix" | Rename package "si_prefix" to "si-prefix"
| Python | bsd-3-clause | cfobel/si-prefix | ---
+++
@@ -18,7 +18,7 @@
ext_modules = cythonize(ext_modules)
-setup(name='si_prefix',
+setup(name='si-prefix',
version=version.getVersion(),
description='Functions for formatting numbers according to SI standards.',
keywords='si prefix format number precision', |
d63905158f5148b07534e823d271326262369d42 | pavement.py | pavement.py | import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
VERSION = eval(re.search(... | import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
VERSION = eval(re.search(... | Use context manager to read README | Use context manager to read README
| Python | mit | jaraco/irc | ---
+++
@@ -17,11 +17,8 @@
return VERSION
def read_long_description():
- f = open('README')
- try:
+ with open('README') as f:
data = f.read()
- finally:
- f.close()
return data
setup( |
06d1039ccbf4653c2f285528b2ab058edca2ff1f | py/test/selenium/webdriver/common/proxy_tests.py | py/test/selenium/webdriver/common/proxy_tests.py | #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | Fix test as well :) | DanielWagnerHall: Fix test as well :)
r17825
| Python | apache-2.0 | misttechnologies/selenium,markodolancic/selenium,uchida/selenium,yukaReal/selenium,mestihudson/selenium,alb-i986/selenium,jabbrwcky/selenium,krmahadevan/selenium,jabbrwcky/selenium,AutomatedTester/selenium,s2oBCN/selenium,asolntsev/selenium,twalpole/selenium,o-schneider/selenium,jsakamoto/selenium,compstak/selenium,tku... | ---
+++
@@ -30,7 +30,7 @@
expected_capabilities = {
'proxy': {
- 'proxyType': 'manual',
+ 'proxyType': 'MANUAL',
'httpProxy': 'some.url:1234'
}
} |
6453baefa8c2f6ab9841efd3961da0a65aaa688f | test/test_packages.py | test/test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | Add a test for sysdig | Add a test for sysdig
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build | ---
+++
@@ -41,6 +41,7 @@
("scrot"),
("software-properties-common"),
("suckless-tools"),
+ ("sysdig"),
("sysstat"),
("tree"),
("vagrant"), |
ff50b3e43de0c083cd8c3daaa7644394daadc1a0 | test_passwd_change.py | test_passwd_change.py | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 'test'])
... | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 't... | Add tearDown() - remove test dir, test files existing and not existing. | Add tearDown() - remove test dir, test files existing and not existing.
| Python | mit | maxsocl/oldmailer | ---
+++
@@ -3,6 +3,7 @@
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
+import os
import subprocess
@@ -18,9 +19,24 @@
#TODO create shadow test file
#TODO create keys.txt file
+ def tearDown(self):
+ ... |
8db4213d20486a60abda1ba486438f54c3b830c0 | ci_scripts/installPandoc.py | ci_scripts/installPandoc.py | import os
from subprocess import call, check_output
import sys
from shutil import copy2
def checkAndInstall():
try:
check_output('pandoc -v'.split())
except OSError:
cudir = os.path.abspath(os.curdir)
os.chdir('downloads')
from requests import get
pandocFile = 'pandoc... | import os
from subprocess import call, check_output
import sys
from shutil import copy2
platform = sys.platform
def checkAndInstall():
try:
check_output('pandoc -v'.split())
except OSError:
cudir = os.path.abspath(os.curdir)
os.chdir(os.path.abspath(os.path.join(os.path.pardir, 'downl... | Fix build wheels with Pandoc. | Fix build wheels with Pandoc.
| Python | bsd-3-clause | jr-garcia/AssimpCy,jr-garcia/AssimpCy | ---
+++
@@ -2,6 +2,8 @@
from subprocess import call, check_output
import sys
from shutil import copy2
+
+platform = sys.platform
def checkAndInstall():
@@ -9,18 +11,29 @@
check_output('pandoc -v'.split())
except OSError:
cudir = os.path.abspath(os.curdir)
- os.chdir('downloads')
... |
d407f1bcd95daf4f4bd8dfe8ae3b4b9e68061cb5 | cref/sequence/fragment.py | cref/sequence/fragment.py |
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
for i in range(len(sequence) - size + 1):
... |
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
if size > 0:
for i in range(len(sequence)... | Handle sliding window with size 0 | Handle sliding window with size 0
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 | ---
+++
@@ -8,6 +8,6 @@
:return: a fragment of the sequence with the given size
"""
- for i in range(len(sequence) - size + 1):
- yield sequence[i: i + size]
-
+ if size > 0:
+ for i in range(len(sequence) - size + 1):
+ yield sequence[i: i + size] |
471681cc25f44f31792813a968074b6813efb38c | yle/serializers.py | yle/serializers.py | from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer, CharField, UUIDField
from alexa.settings import RADIO_LINK_BASE
from yle.models import News
class NewsSerializer(ModelSerializer):
uid = UUIDField(source='uuid')
updateDate = CharField(source='mod... | from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer, CharField, UUIDField
from alexa.settings import RADIO_LINK_BASE
from yle.models import News
class NewsSerializer(ModelSerializer):
uid = UUIDField(source='uuid')
updateDate = CharField(source='cre... | Update date from creation time | Update date from creation time
| Python | mit | anttipalola/alexa | ---
+++
@@ -8,7 +8,7 @@
class NewsSerializer(ModelSerializer):
uid = UUIDField(source='uuid')
- updateDate = CharField(source='modified')
+ updateDate = CharField(source='created')
titleText = CharField(source='title')
streamUrl = CharField(source='audio_url')
mainText = CharField(source=... |
dc186adbb1b49c821911af724725df4512fbf9f5 | socialregistration/templatetags/facebook_tags.py | socialregistration/templatetags/facebook_tags.py | from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.i... | from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.i... | Use syntax compatible with Python 2.4 | Use syntax compatible with Python 2.4
| Python | mit | bopo/django-socialregistration,bopo/django-socialregistration,bopo/django-socialregistration,kapt/django-socialregistration,lgapontes/django-socialregistration,mark-adams/django-socialregistration,0101/django-socialregistration,praekelt/django-socialregistration,flashingpumpkin/django-socialregistration,itmustbejj/djan... | ---
+++
@@ -13,5 +13,8 @@
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
- next = context['next'] if 'next' i... |
2f16eb25db856b72138f6dfb7d19e799bd460287 | tests/test_helpers.py | tests/test_helpers.py | # -*- coding: utf-8 -*-
import pytest
from os.path import basename
from helpers import utils, fixture
@pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
class TestHelpers():
def test_wildcards1():
d = utils.get_wildcards([('"... | # -*- coding: utf-8 -*-
import pytest
from os.path import basename
from helpers import utils, fixture
pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
def test_wildcards1():
d = utils.get_wildcards([('"{prefix}.bam"', ... | Use global pytestmark to skip tests; deprecate class | Use global pytestmark to skip tests; deprecate class
| Python | mit | percyfal/snakemake-rules,percyfal/snakemake-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules | ---
+++
@@ -3,31 +3,34 @@
from os.path import basename
from helpers import utils, fixture
-
-@pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
-class TestHelpers():
- def test_wildcards1():
- d = utils.get_wildcards([('"{p... |
723d7410b48fd4fc42ed9afe470ba3b37381599a | noxfile.py | noxfile.py | """Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
",".join(extras),
si... | """Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
",".join(extras),
si... | Add docs-live to perform demo-runs | Add docs-live to perform demo-runs
| Python | mit | GaretJax/sphinx-autobuild | ---
+++
@@ -39,3 +39,9 @@
def docs(session):
_install_this_editable(session, extras=["docs"])
session.run("sphinx-build", "-b", "html", "docs/", "build/docs")
+
+
+@nox.session(name="docs-live")
+def docs_live(session):
+ _install_this_editable(session, extras=["docs"])
+ session.run("sphinx-autobuil... |
41209aa3e27673f003ed62a46c9bfae0c19d0bf3 | il2fb/ds/airbridge/typing.py | il2fb/ds/airbridge/typing.py | # coding: utf-8
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.parsers.events.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringO... | # coding: utf-8
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.commons.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringOrNone =... | Update import of Event class | Update import of Event class
| Python | mit | IL2HorusTeam/il2fb-ds-airbridge | ---
+++
@@ -3,7 +3,7 @@
from pathlib import Path
from typing import Callable, Optional, List, Union
-from il2fb.parsers.events.events import Event
+from il2fb.commons.events import Event
EventOrNone = Optional[Event] |
462d94ddd57d2385889d2c6ef09563e38ffcccc9 | decisiontree/multitenancy/utils.py | decisiontree/multitenancy/utils.py | from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.models import Q
def multitenancy_enabled():
return "decisiontree.multitenancy" in settings.INSTALLED_APPS
def get_tenants_for_user(user):
"""Return all tenants that the user can manage."""
from multitenancy.mode... | from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.models import Q
def multitenancy_enabled():
return "decisiontree.multitenancy" in settings.INSTALLED_APPS
def get_tenants_for_user(user):
"""Return all tenants that the user can manage."""
from multitenancy.mode... | Fix error if passing a list of args to tenancy_reverse | Fix error if passing a list of args to tenancy_reverse
| Python | bsd-3-clause | caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app | ---
+++
@@ -30,7 +30,7 @@
if multitenancy_enabled():
# reverse disallows mixing *args and **kwargs.
if args:
- args = (request.group_slug, request.tenant_slug) + args
+ args = (request.group_slug, request.tenant_slug) + tuple(args)
else:
kwargs.setdef... |
7ee86e9b52292a8824dfa7bab632526cbb365b51 | routes.py | routes.py | # -*- coding:utf-8 -*-
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid='
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@wraps(f)
def decorated_function(*args... | # -*- coding:utf-8 -*-
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate'
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@wraps(f)
def decorated_functi... | Use new OpenAM token validation endpoint | Use new OpenAM token validation endpoint
| Python | unlicense | timhberry/openam-flask-decorator | ---
+++
@@ -5,7 +5,7 @@
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
-validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid='
+validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate'
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@@ -13,8 +13... |
d52f59911929eda6b8c0c42837ae9c19b9e133e4 | twokenize_py/align.py | twokenize_py/align.py | """Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
... | """Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
... | Fix typo in variable name. | BUG: Fix typo in variable name.
| Python | apache-2.0 | nryant/twokenize_py | ---
+++
@@ -36,7 +36,7 @@
for token in tokens:
try:
token_len = len(token)
- token_bi = bi + txt[bi:].index(token)
+ token_bi = bi + text[bi:].index(token)
token_ei = token_bi + token_len - 1
spans.append([token_bi,... |
463abcce738ca1c47729cc0e465da9dc399e21dd | examples/remote_download.py | examples/remote_download.py | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
from xunleipy.remote import XunLeiRemote
def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0):
remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy)
remote_client.l... | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
import sys
import os
from xunleipy.remote import XunLeiRemote
sys.path.append('/Users/gunner/workspace/xunleipy')
def remote_download(username,
password,
rk_username,
rk_password,
download_l... | Change example style for python3 | Change example style for python3
| Python | mit | lazygunner/xunleipy | ---
+++
@@ -1,15 +1,27 @@
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
+import sys
+import os
from xunleipy.remote import XunLeiRemote
+sys.path.append('/Users/gunner/workspace/xunleipy')
-def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0):
... |
ab47c678b37527a7b8a970b365503b65ffccda87 | populous/cli.py | populous/cli.py | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
... | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
... | Handle unexpected errors properly in load_blueprint | Handle unexpected errors properly in load_blueprint
| Python | mit | novafloss/populous | ---
+++
@@ -11,7 +11,8 @@
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
except Exception as e:
- pass
+ raise click.ClickException("Unexpected error during the blueprint "
+ "loading: {}".format(e.message))
@clic... |
3b0e80a159c4544a69adf35f4871b9167335795c | examples/user_agent_test.py | examples/user_agent_test.py | import time
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_user_agent(self):
self.open('http://www.whatsmyua.info/')
user_agent = self.get_text("#custom-ua-string")
print("\n\nUser-Agent = %s\n" % user_agent)
print("Displaying User-Agent Info:")
pr... | import time
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_user_agent(self):
self.open('https://www.whatsmyua.info/')
user_agent = self.get_text("#custom-ua-string")
print("\n\nUser-Agent = %s\n" % user_agent)
print("Displaying User-Agent Info:")
p... | Update the user agent test | Update the user agent test
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -5,7 +5,7 @@
class MyTestClass(BaseCase):
def test_user_agent(self):
- self.open('http://www.whatsmyua.info/')
+ self.open('https://www.whatsmyua.info/')
user_agent = self.get_text("#custom-ua-string")
print("\n\nUser-Agent = %s\n" % user_agent)
print("Displ... |
0485e6dcaf19061812d0e571890e58b85b5dea12 | lava_results_app/utils.py | lava_results_app/utils.py | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class Stre... | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class Stre... | Return an empty dict if no data | Return an empty dict if no data
Avoids a HTTP500 on slow instances where the file
may be created before data is written, causing the
YAML parser to return None.
Change-Id: I13b92941f3e368839a9665fe3197c706babd9335
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | ---
+++
@@ -36,4 +36,6 @@
except yaml.YAMLError:
logger.error("Unable to parse description for %s" % job_id)
return {}
+ if not data:
+ return {}
return data |
28c6af1381a1fc38b20ce05e85f494f3ae2beeb4 | arcutils/masquerade/templatetags/masquerade.py | arcutils/masquerade/templatetags/masquerade.py | from django import template
from .. import perms
from ..settings import get_user_attr
register = template.Library()
@register.filter
def is_masquerading(user):
info = getattr(user, get_user_attr())
return info['is_masquerading']
@register.filter
def can_masquerade(user):
return perms.can_masquerade(u... | from django import template
from .. import perms
from ..settings import get_user_attr, is_enabled
register = template.Library()
@register.filter
def is_masquerading(user):
if not is_enabled():
return False
info = getattr(user, get_user_attr(), None)
return info['is_masquerading']
@register.fi... | Make is_masquerading template tag more robust | Make is_masquerading template tag more robust
When masquerading is not enabled, immediately return False to avoid
checking for a request attribute that won't be present.
| Python | mit | PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils | ---
+++
@@ -1,7 +1,7 @@
from django import template
from .. import perms
-from ..settings import get_user_attr
+from ..settings import get_user_attr, is_enabled
register = template.Library()
@@ -9,7 +9,9 @@
@register.filter
def is_masquerading(user):
- info = getattr(user, get_user_attr())
+ if not... |
98c2c311ad1a0797205da58ce4d3b7d9b4c66c57 | nova/policies/pause_server.py | nova/policies/pause_server.py | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... | Introduce scope_types in pause server policy | Introduce scope_types in pause server policy
oslo.policy introduced the scope_type feature which can
control the access level at system-level and project-level.
- https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope
- http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/sy... | Python | apache-2.0 | openstack/nova,klmitch/nova,klmitch/nova,mahak/nova,mahak/nova,mahak/nova,klmitch/nova,openstack/nova,openstack/nova,klmitch/nova | ---
+++
@@ -23,26 +23,28 @@
pause_server_policies = [
policy.DocumentedRuleDefault(
- POLICY_ROOT % 'pause',
- base.RULE_ADMIN_OR_OWNER,
- "Pause a server",
- [
+ name=POLICY_ROOT % 'pause',
+ check_str=base.RULE_ADMIN_OR_OWNER,
+ description="Pause a server",
... |
263e517004df36938b430d8802d4fc80067fadf5 | djangoreact/urls.py | djangoreact/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^$', views.index),
url(r'^ap... | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^api/auth/', include('rest_auth.... | Fix to use react-router for all unmatched routes. | Fix to use react-router for all unmatched routes.
| Python | mit | willy-claes/django-react,willy-claes/django-react,willy-claes/django-react | ---
+++
@@ -8,9 +8,9 @@
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
- url(r'^$', views.index),
url(r'^api/auth/', include('rest_auth.urls')),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
+ ur... |
f83282b1747e255d35e18e9fecad1750d1564f9e | do_record/record.py | do_record/record.py | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
... | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
... | Remove Code That Doesn't Have a Test | Remove Code That Doesn't Have a Test
| Python | apache-2.0 | Jitsusama/lets-do-dns | ---
+++
@@ -33,8 +33,4 @@
@number.setter
def number(self, value):
- if self.number is None:
- self._number = value
- else:
- raise ValueError(
- 'Cannot externally reset a record\'s number identifier.')
+ self._number = value |
1633b9a1ace74a5a7cbf445ce7ceb790d0411e79 | modules/__init__.py | modules/__init__.py | #pipe2py modules package
#Author: Greg Gaughan
__all__ = ['pipefetch',
'pipefetchdata',
'pipedatebuilder',
'pipeurlbuilder',
'pipetextinput',
'pipeurlinput',
'pipefilter',
'pipeunion',
'pipeoutput',
]
| #pipe2py modules package
#Author: Greg Gaughan
#Note: each module name must match the name used internally by Yahoo, preceded by pipe
__all__ = ['pipefetch',
'pipefetchdata',
'pipedatebuilder',
'pipeurlbuilder',
'pipetextinput',
'pipeurlinput',
'pipef... | Add comment about module naming | Add comment about module naming
| Python | mit | nerevu/riko,nerevu/riko | ---
+++
@@ -1,5 +1,7 @@
#pipe2py modules package
#Author: Greg Gaughan
+
+#Note: each module name must match the name used internally by Yahoo, preceded by pipe
__all__ = ['pipefetch',
'pipefetchdata', |
413c3e9e8a093e3f336e27a663f347f5ea9866a6 | performanceplatform/collector/ga/__init__.py | performanceplatform/collector/ga/__init__.py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | Allow the 'dataType' field to be overriden | Allow the 'dataType' field to be overriden
The 'dataType' field in records predates data groups and data types. As
such they don't always match the new world order of data types. It's
fine to change in all cases other than Licensing which is run on
limelight, that we don't really want to touch.
| Python | mit | alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector | ---
+++
@@ -12,8 +12,8 @@
documents = query_documents_for(
client, query, options,
- data_set_config['data-type'], start_at, end_at
- )
+ options.get('dataType', data_set_config['data-type']),
+ start_at, end_at)
data_set = DataSet.from_config(data_set_config)
send_... |
95542ab1b7c22a6e0160e242349c66f2cef7e390 | syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py | syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py | from django.core.management.base import BaseCommand
from syntacticframes.models import VerbNetClass
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
for vn_class in VerbNetClass.objects.all():
try:
... | from django.core.management.base import BaseCommand
from syntacticframes.models import VerbNetFrameSet
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
for frameset in VerbNetFrameSet.objects.all():
print("{}:... | Check correspondances in framesets now | Check correspondances in framesets now
| Python | mit | aymara/verbenet-editor,aymara/verbenet-editor,aymara/verbenet-editor | ---
+++
@@ -1,18 +1,22 @@
from django.core.management.base import BaseCommand
-from syntacticframes.models import VerbNetClass
+from syntacticframes.models import VerbNetFrameSet
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **op... |
6c54fc230e8c889a2351f20b524382a5c6e29d1c | examples/apps.py | examples/apps.py | # coding: utf-8
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN.')
sys.exit(1)
api = TsuruClient(TSURU_TARGET, T... | # coding: utf-8
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
# Creating TsuruCli... | Update examples to match docs | Update examples to match docs
Use the interface defined in the docs in the examples scripts.
| Python | mit | rcmachado/pysuru | ---
+++
@@ -9,22 +9,19 @@
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
- print('You must set TSURU_TARGET and TSURU_TOKEN.')
+ print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
-api = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
+# Cr... |
5af4ef36ff7a56b34fc8d30df37c82a6837918e3 | pambox/speech/__init__.py | pambox/speech/__init__.py | """
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .binauralsepsm import BinauralSepsm
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
from .experiment import Experiment
__all__ = [
'Bi... | """
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .binauralsepsm import BinauralSepsm
from .binauralmrsepsm import BinauralMrSepsm
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
from .expe... | Include both binaural mr-sEPSM and sEPSM | Include both binaural mr-sEPSM and sEPSM
| Python | bsd-3-clause | achabotl/pambox | ---
+++
@@ -5,6 +5,7 @@
from __future__ import absolute_import
from .binauralsepsm import BinauralSepsm
+from .binauralmrsepsm import BinauralMrSepsm
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
@@ -13,6 +14,7 @@
__all__ = [
'BinauralSepsm',
+ 'BinauralMrSepsm',
'S... |
b5a8e7b6926bf7224abed6bd335d62b3f1ad1fb1 | performance_testing/command_line.py | performance_testing/command_line.py | import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
from datetime import datetime as date
from time import time
class Tool:
def __init__(self, config='config.yml', result_directory='result'):
self.read_config(config_file=config)
... | import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
from performance_testing.config import Config
from performance_testing.result import Result
class Tool:
def __init__(self, config='config.yml', result_directory='result'):
self.... | Use Config and Result class in Tool | Use Config and Result class in Tool
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | ---
+++
@@ -2,53 +2,23 @@
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
-from datetime import datetime as date
-from time import time
+from performance_testing.config import Config
+from performance_testing.result import Result
class Too... |
5fc699b89eae0c41923a813ac48281729c4d80b8 | orderable_inlines/inlines.py | orderable_inlines/inlines.py | from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
... | from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
... | Make this hack compatible with Django 1.9 | Make this hack compatible with Django 1.9
| Python | bsd-2-clause | frx0119/django-orderable-inlines,frx0119/django-orderable-inlines | ---
+++
@@ -16,8 +16,6 @@
}
def get_fieldsets(self, request, obj=None):
- if self.declared_fieldsets:
- return self.declared_fieldsets
form = self.get_formset(request, obj, fields=None).form
fields = list(form.base_fields) + list(self.get_readonly_fields(request, ob... |
533fb21586322c26fd9696213108d6a9e45ada64 | lib/ansible/cache/base.py | lib/ansible/cache/base.py | import exceptions
class BaseCacheModule(object):
def get(self, key):
raise exceptions.NotImplementedError
def set(self, key, value):
raise exceptions.NotImplementedError
def keys(self):
raise exceptions.NotImplementedError
def contains(self, key):
raise exceptions.No... | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | Add copyright header, let me know if corrections are needed. | Add copyright header, let me know if corrections are needed.
| Python | mit | thaim/ansible,thaim/ansible | ---
+++
@@ -1,3 +1,20 @@
+# (c) 2014, Brian Coca, Josh Drake, et al
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (... |
aff0eba2c0f7f5a0c9bebbfc9402f04c2c9d6d11 | preference/miExecPref.py | preference/miExecPref.py | import os
import json
SCRIPT_PATH = os.path.dirname(__file__)
def getPreference():
""" Load pref json data nad return as dict"""
prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSe... | import os
import json
import maya.cmds as cmds
SCRIPT_PATH = os.path.dirname(__file__)
MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)
def getPreference():
""" Load pref json data nad return as dict"""
for root, dirs, files in os.walk(MAYA_SCRIPT_DIR):
if 'miExecPref.json' in file... | Load user pref file if exists in the maya user script directory | Load user pref file if exists in the maya user script directory
| Python | mit | minoue/miExecutor | ---
+++
@@ -1,14 +1,23 @@
import os
import json
-
+import maya.cmds as cmds
SCRIPT_PATH = os.path.dirname(__file__)
+MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)
def getPreference():
""" Load pref json data nad return as dict"""
- prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.jso... |
64ed32aa5e2e36ce58209b0e356f7482137a81f2 | getMesosStats.py | getMesosStats.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=Tru... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=Tru... | Add KeyError exception and ZBX_NOT_SUPPORTED message. | Add KeyError exception and ZBX_NOT_SUPPORTED message.
| Python | mit | zolech/zabbix-mesos-template | ---
+++
@@ -11,7 +11,10 @@
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
- print data[metric]
+ try:
+ print data[metric]
+ except KeyError:
+ print "ZBX_NOT_S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.