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 |
|---|---|---|---|---|---|---|---|---|---|---|
e6fb5ba043c2db08cbacb119664297b3f3668517 | fluent_comments/forms/_captcha.py | fluent_comments/forms/_captcha.py | from django.core.exceptions import ImproperlyConfigured
try:
from captcha.fields import ReCaptchaField as CaptchaField
except ImportError:
try:
from captcha.fields import CaptchaField
except ImportError:
raise ImportError(
"To use the captcha contact form, you need to have "
... | from django.core.exceptions import ImproperlyConfigured
class CaptchaFormMixin(object):
def _reorder_fields(self, ordering):
"""
Test that the 'captcha' field is really present.
This could be broken by a bad FLUENT_COMMENTS_FIELD_ORDER configuration.
"""
if 'captcha' not in... | Fix duplicate captcha import check | Fix duplicate captcha import check
| Python | apache-2.0 | django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments | ---
+++
@@ -1,15 +1,4 @@
from django.core.exceptions import ImproperlyConfigured
-
-try:
- from captcha.fields import ReCaptchaField as CaptchaField
-except ImportError:
- try:
- from captcha.fields import CaptchaField
- except ImportError:
- raise ImportError(
- "To use the captcha... |
7f1ddec9e170941e3a5159236ede817c2d569f38 | graphical_tests/test_partition.py | graphical_tests/test_partition.py | """
Draw a solid circle off center in a blank image.
Use the same array as both the image and the mask.
The tiles should subdivide along the curved edge to trace out a smooth circle.
"""
from skimage import draw
import matplotlib.pyplot as plt
import numpy as np
import photomosaic as pm
img = np.zeros((1000, 1000))
rr... | """
Draw a solid circle off center in a blank image.
Use the same array as both the image and the mask.
The tiles should subdivide along the curved edge to trace out a smooth circle.
"""
from skimage import draw
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import photomosai... | Update test to match API. | TST: Update test to match API.
| Python | bsd-3-clause | danielballan/photomosaic | ---
+++
@@ -4,6 +4,8 @@
The tiles should subdivide along the curved edge to trace out a smooth circle.
"""
from skimage import draw
+import matplotlib
+matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import photomosaic as pm
@@ -12,5 +14,5 @@
rr, cc = draw.circle(300, 500, 150)
img[rr... |
8e1e6624fb9120b3f26ac373dc48e877240cccac | bootcamp/lesson5.py | bootcamp/lesson5.py | import datetime
import csv
# Question 1
# ----------
# Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app
# users should be one dictionary while the count of registration month should be another dictionary. There will be
# no checking or test harness so simpl... | import datetime
import csv
# Question 1
# ----------
# Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app
# users should be one dictionary while the count of registration month should be another dictionary. There will be
# no checking or test harness so simpl... | Add print function to demonstrate func calling | Add print function to demonstrate func calling
| Python | mit | infoscout/python-bootcamp-pv | ---
+++
@@ -6,7 +6,7 @@
# ----------
# Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app
# users should be one dictionary while the count of registration month should be another dictionary. There will be
-# no checking or test harness so simply print your... |
51c97b17220e8fc6334d2dce1fd945ee1861385e | healthcheck/utils.py | healthcheck/utils.py | import errno
import os
def file_exists(path):
"""Return True if a file exists at `path` (even if it can't be read),
otherwise False.
This is different from os.path.isfile and os.path.exists which return
False if a file exists but the user doesn't have permission to read it.
"""
try:
o... | import errno
import os
def file_exists(path):
"""Return True if a file exists at `path` (even if it can't be read),
otherwise False.
This is different from os.path.isfile and os.path.exists which return
False if a file exists but the user doesn't have permission to read it.
"""
try:
o... | Add period to end of long comment | Add period to end of long comment
| Python | mit | yola/healthcheck | ---
+++
@@ -14,7 +14,7 @@
return True
except OSError as e:
- # Permission denied: someone chose the wrong permissions but it exists
+ # Permission denied: someone chose the wrong permissions but it exists.
if e.errno == errno.EACCES:
return True
|
17ffc13ba4a5eab56b66b8fe144cc53e8d02d961 | easyedit/TextArea.py | easyedit/TextArea.py | from PyQt5.Qsci import QsciScintilla, QsciLexerPython
class TextArea(QsciScintilla):
def __init__(self):
super().__init__()
self.filePath = "Untitled"
self.pythonLexer = QsciLexerPython(self)
self.setLexer(self.pythonLexer)
self.setMargins(1)
self.setMarginType(0,... | from PyQt5.Qsci import QsciScintilla, QsciLexerPython
class TextArea(QsciScintilla):
def __init__(self):
super().__init__()
self.filePath = "Untitled"
self.pythonLexer = QsciLexerPython(self)
self.setLexer(self.pythonLexer)
self.setMargins(1)
self.setMarginType(0,... | Remove debugging print statement from changeMarginWidth | Remove debugging print statement from changeMarginWidth
| Python | mit | msklosak/EasyEdit | ---
+++
@@ -19,7 +19,6 @@
def changeMarginWidth(self):
numLines = self.lines()
- print(len(str(numLines)))
self.setMarginWidth(0, "00" * len(str(numLines)))
|
3f5b1e830eff73cdff013a423b647c795e21bef2 | captcha/fields.py | captcha/fields.py | from django.conf import settings
from django import forms
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
from recaptcha.client import captcha
from captcha.widgets import ReCaptcha
class ReCaptchaField(forms.CharField):
default_error_messages = {
... | from django.conf import settings
from django import forms
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
from recaptcha.client import captcha
from captcha.widgets import ReCaptcha
class ReCaptchaField(forms.CharField):
default_error_messages = {
... | Revert "Enforce valid captcha only if required, so tests can relax captcha requirement" | Revert "Enforce valid captcha only if required, so tests can relax captcha requirement"
This reverts commit c3c450b1a7070a1dd1b808e55371e838dd297857. It wasn't
such a great idea.
| Python | bsd-3-clause | mozilla/django-recaptcha | ---
+++
@@ -30,7 +30,7 @@
recaptcha_response_value = smart_unicode(values[1])
check_captcha = captcha.submit(recaptcha_challenge_value,
recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {})
- if self.required and not check_captcha.is_valid:
+ if not check_captcha.i... |
b48984747d0f33f8ad9a8721bf7489d8ff97c157 | matador/commands/deploy_ticket.py | matador/commands/deploy_ticket.py | #!/usr/bin/env python
from .command import Command
from matador import utils
class DeployTicket(Command):
def _add_arguments(self, parser):
parser.prog = 'matador deploy-ticket'
parser.add_argument(
'-e', '--environment',
type=str,
required=True,
he... | #!/usr/bin/env python
from .command import Command
from matador import utils
class DeployTicket(Command):
def _add_arguments(self, parser):
parser.prog = 'matador deploy-ticket'
parser.add_argument(
'-e', '--environment',
type=str,
required=True,
he... | Add package argument to deploy-ticket | Add package argument to deploy-ticket
| Python | mit | Empiria/matador | ---
+++
@@ -13,6 +13,13 @@
required=True,
help='Agresso environment name')
+ parser.add_argument(
+ '-', '--package',
+ type=bool,
+ default=False,
+ help='Agresso environment name')
+
def _execute(self):
project = utils.proj... |
f6ce19f558bd298a6f0651ead865b65da3a2c479 | spiff/sensors/tests.py | spiff/sensors/tests.py | from django.test import TestCase
from spiff.api.tests import APITestMixin, withPermission
import models
class SensorTest(APITestMixin):
def setUp(self):
self.setupAPI()
self.sensor = models.Sensor.objects.create(
name = 'sensor',
description = 'Test sensor',
type = 0,
ttl = 255
)
... | from django.test import TestCase
from spiff.api.tests import APITestMixin, withPermission
import models
class SensorTest(APITestMixin):
def setUp(self):
self.setupAPI()
self.sensor = models.Sensor.objects.create(
name = 'sensor',
description = 'Test sensor',
type = models.SENSOR_TYPE_BOOLEA... | Use a bool sensor for testing, and query the API instead of models | Use a bool sensor for testing, and query the API instead of models
| Python | agpl-3.0 | SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff | ---
+++
@@ -8,7 +8,7 @@
self.sensor = models.Sensor.objects.create(
name = 'sensor',
description = 'Test sensor',
- type = 0,
+ type = models.SENSOR_TYPE_BOOLEAN,
ttl = 255
)
@@ -18,11 +18,13 @@
self.patchAPI('/v1/sensor/%s/'%(self.sensor.id), {
'value': True,
... |
600fe835ddce18a6aec5702766350003f2f90745 | gen-android-icons.py | gen-android-icons.py | __author__ = 'Maksim Dmitriev'
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help', required=True)
args = parser.parse_args()
| __author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_... | Create an output directory unless it exists | Create an output directory unless it exists
| Python | bsd-3-clause | MaksimDmitriev/Python-Scripts | ---
+++
@@ -1,8 +1,17 @@
__author__ = 'Maksim Dmitriev'
import argparse
+import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
- parser.add_argument('--foo', help='foo help', required=True)
+ parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
+ p... |
195bcf4b834794642a502ce876f023025c91a690 | savate/buffer_event.py | savate/buffer_event.py | # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(sel... | # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(sel... | Use buffer() to try and avoid memory copies | Use buffer() to try and avoid memory copies
| Python | agpl-3.0 | noirbee/savate,noirbee/savate | ---
+++
@@ -31,7 +31,7 @@
total_sent_bytes += sent_bytes
if sent_bytes < len(self.buffer_queue[0]):
# One of the buffers was partially sent
- self.buffer_queue[0] = self.buffer_queue[0][sent_bytes:]
+ self.buffer_queue[0] = b... |
90fb352f313b26964adcc587beb8f21deb3395a4 | tor.py | tor.py | import socks
import socket
from stem.control import Controller
from stem import Signal
class Tor(object):
"""Tor class for socks proxy and controller"""
def __init__(self, socks_port=9050, control_port=9051, control_password=""):
self.socks_port = socks_port
self.control_port = control_port
... | import socks
import socket
import json
from stem.control import Controller
from stem import Signal
from urllib2 import urlopen
class Tor(object):
"""Tor class for socks proxy and controller"""
def __init__(self, socks_port=9050, control_port=9051, control_password=""):
self.socks_port = socks_port
... | Add print_ip method for debugging | Add print_ip method for debugging
| Python | mit | MA3STR0/simpletor | ---
+++
@@ -1,7 +1,9 @@
import socks
import socket
+import json
from stem.control import Controller
from stem import Signal
+from urllib2 import urlopen
class Tor(object):
@@ -26,3 +28,10 @@
with Controller.from_port(port=self.control_port) as controller:
controller.authenticate(self.co... |
a52039c139e0d5b1c5fedb1dfb160e2c9b9387b3 | teuthology/task/tests/test_locking.py | teuthology/task/tests/test_locking.py | import pytest
class TestLocking(object):
def test_correct_os_type(self, ctx, config):
os_type = ctx.config.get("os_type")
if os_type is None:
pytest.skip('os_type was not defined')
for remote in ctx.cluster.remotes.iterkeys():
assert remote.os.name == os_type
... | import pytest
class TestLocking(object):
def test_correct_os_type(self, ctx, config):
os_type = ctx.config.get("os_type")
if os_type is None:
pytest.skip('os_type was not defined')
for remote in ctx.cluster.remotes.iterkeys():
assert remote.os.name == os_type
... | Make an exception for debian in tests.test_correct_os_version | Make an exception for debian in tests.test_correct_os_version
This is because of a known issue where downburst gives us 7.1 when we
ask for 7.0. We're ok with this behavior for now. See: issue #10878
Signed-off-by: Andrew Schoen <1bb641dc23c3a93cce4eee683bcf4b2bea7903a3@redhat.com>
| Python | mit | SUSE/teuthology,yghannam/teuthology,dmick/teuthology,caibo2014/teuthology,dreamhost/teuthology,caibo2014/teuthology,t-miyamae/teuthology,ivotron/teuthology,SUSE/teuthology,ceph/teuthology,ivotron/teuthology,ktdreyer/teuthology,SUSE/teuthology,dmick/teuthology,t-miyamae/teuthology,robbat2/teuthology,zhouyuan/teuthology,... | ---
+++
@@ -14,6 +14,8 @@
os_version = ctx.config.get("os_version")
if os_version is None:
pytest.skip('os_version was not defined')
+ if ctx.config.get("os_type") == "debian":
+ pytest.skip('known issue with debian versions; see: issue #10878')
for remote in ... |
6fb605a46a9dd33a2f31128955ca79e44379ad4d | main.py | main.py | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software d... | # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software d... | Fix api key call to be renmamed key | Fix api key call to be renmamed key
| Python | apache-2.0 | googlearchive/appengine-python-vm-hello,bshaffer/appengine-python-vm-hello,bshaffer/appengine-python-vm-hello,googlearchive/appengine-python-vm-hello | ---
+++
@@ -20,7 +20,7 @@
@app.route('/get_author/<title>')
def get_author(title):
- host = 'https://www.googleapis.com/books/v1/volume?q={}&key={}&country=US'.format(title, api_key)
+ host = 'https://www.googleapis.com/books/v1/volume?q={}&key={}&country=US'.format(title, key)
request = urllib2.Reques... |
424162d2dc8a7c815c48946f4963561be20df62d | config_context.py | config_context.py | # A context carrying the loaded configuration.
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import config
class ConfigContext(object):
def __init__(self, config):
self._config = config
self._cloud_workstations = {}
self._volumes_by_cws = {... | # A context carrying the loaded configuration.
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import config
class ConfigContext(object):
def __init__(self, config):
self._config = config
self._cloud_workstations = {}
self._volumes = {}
... | Revert unintend change. Fixes bug. | Revert unintend change. Fixes bug.
| Python | mit | fhltang/chews,fhltang/chews | ---
+++
@@ -10,7 +10,7 @@
self._config = config
self._cloud_workstations = {}
- self._volumes_by_cws = {}
+ self._volumes = {}
self._build_indexes()
# Only support GCE for now |
ab1e27b3b28e0463f6dd182037a265c9f69fb94f | src/azure/cli/commands/resourcegroup.py | src/azure/cli/commands/resourcegroup.py | from msrest import Serializer
from ..commands import command, description
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
# @option('--tag-name -g <tagName>', L('the resource group's tag name'))
# @option('--tag-value -g ... | from msrest import Serializer
from ..commands import command, description
from ._command_creation import get_service_client
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
# @option('--tag-name -g <tagName>', L('the resou... | Use service client factory method for resource group command | Use service client factory method for resource group command
| Python | mit | samedder/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,QingChenmsft/azure-cli,QingChenmsft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure... | ---
+++
@@ -1,5 +1,6 @@
from msrest import Serializer
from ..commands import command, description
+from ._command_creation import get_service_client
from .._profile import Profile
@command('resource group list')
@@ -13,8 +14,7 @@
ResourceManagementClientConfigurati... |
65d2a5f08ee96e80752362f7545167888599819e | website/addons/figshare/exceptions.py | website/addons/figshare/exceptions.py | from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def renderable_error(self):
return '''
<div class="a... | from website.util.sanitize import escape_html
from website.addons.base.exceptions import AddonEnrichmentError
class FigshareIsDraftError(AddonEnrichmentError):
def __init__(self, file_guid):
self.file_guid = file_guid
@property
def can_delete(self):
return True
@property
def ren... | Allow deletion of figshare drafts | Allow deletion of figshare drafts
| Python | apache-2.0 | zachjanicki/osf.io,DanielSBrown/osf.io,njantrania/osf.io,kushG/osf.io,erinspace/osf.io,GaryKriebel/osf.io,wearpants/osf.io,chrisseto/osf.io,samchrisinger/osf.io,caneruguz/osf.io,petermalcolm/osf.io,doublebits/osf.io,arpitar/osf.io,cldershem/osf.io,Nesiehr/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,mluo613/osf.io,patt... | ---
+++
@@ -8,6 +8,10 @@
self.file_guid = file_guid
@property
+ def can_delete(self):
+ return True
+
+ @property
def renderable_error(self):
return '''
<div class="alert alert-info" role="alert"> |
e492ffe0e8d57917db6b937523abaabe0ee4ff8e | simplehist/__init__.py | simplehist/__init__.py |
#__all__ = ["hists", "binning"]
from .hists import *
#from .converter import ashist |
#__all__ = ["hists", "binning"]
from .hists import *
from .converter import ashist | Include ashist in the general namespace by default | Include ashist in the general namespace by default
| Python | mit | ndevenish/simplehistogram | ---
+++
@@ -2,4 +2,4 @@
#__all__ = ["hists", "binning"]
from .hists import *
-#from .converter import ashist
+from .converter import ashist |
96726f66fb4ac69328e84877ead5adb6c2037e5e | site/cgi/csv-upload.py | site/cgi/csv-upload.py | #!/usr/bin/python
# Based on examples from
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import sys
import cgi
import os
import cgitb
cgitb.enable()
CSV_DIR = '../csv/' # CSV upload directory
form = cgi.FieldStorage()
fileitem = form['filename'] # Get filename
# Check if the file was uploaded
... | #!/usr/bin/python
# Based on examples from
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import cgi
import os
import cgitb
cgitb.enable()
CSV_DIR = '../csv/' # CSV upload directory
form = cgi.FieldStorage()
fileitem = form['filename'] # Get filename
# Check if the file was uploaded
if fileitem... | Remove unused modules, fix HTML response | Remove unused modules, fix HTML response
| Python | agpl-3.0 | alejosanchez/CSVBenford,alejosanchez/CSVBenford | ---
+++
@@ -3,7 +3,6 @@
# Based on examples from
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
-import sys
import cgi
import os
import cgitb
@@ -27,12 +26,12 @@
else:
# Error, send a message
print """\
-Status: 500\r\n
-Content-Type: text/html;charset=UTF-8\n
-<html>
-<body>
- ... |
041d7285b2ec5c6f323c10a4bbfd388c9d1cb216 | skyscanner/__init__.py | skyscanner/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Ardy Dedase'
__email__ = 'ardy.dedase@skyscanner.net'
__version__ = '0.1.0'
from skyscanner import Flights, FlightsCache, Hotels, CarHire | # -*- coding: utf-8 -*-
__author__ = 'Ardy Dedase'
__email__ = 'ardy.dedase@skyscanner.net'
__version__ = '0.1.0'
from .skyscanner import Flights, FlightsCache, Hotels, CarHire | Make it work with Python 3. | Make it work with Python 3.
| Python | apache-2.0 | valery-barysok/skyscanner-python-sdk,Skyscanner/skyscanner-python-sdk,joesarre/skyscanner-python-sdk | ---
+++
@@ -3,4 +3,4 @@
__email__ = 'ardy.dedase@skyscanner.net'
__version__ = '0.1.0'
-from skyscanner import Flights, FlightsCache, Hotels, CarHire
+from .skyscanner import Flights, FlightsCache, Hotels, CarHire |
cb31dcc7be5e89c865686d9a2a07e8a64c9c0179 | gamernews/apps/threadedcomments/views.py | gamernews/apps/threadedcomments/views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | Remove name, url and email from comment form | Remove name, url and email from comment form
| Python | mit | underlost/GamerNews,underlost/GamerNews | ---
+++
@@ -6,6 +6,7 @@
from core.models import Account as User
from django_comments.models import Comment
+from news.models import Blob, BlobInstance
from .models import ThreadedComment
def single_comment(request, id):
@@ -15,12 +16,10 @@
def comment_posted( request ):
if request.GET['c']:
- c... |
5fd5d32a04615656af03e0c1fa71ca7b81a72b1f | conda_env/installers/conda.py | conda_env/installers/conda.py | from __future__ import absolute_import
import sys
from conda.cli import common
from conda import plan
def install(prefix, specs, args, data):
# TODO: do we need this?
common.check_specs(prefix, specs, json=args.json)
# TODO: support all various ways this happens
index = common.get_index_trap()
a... | from __future__ import absolute_import
import sys
from conda.cli import common
from conda import plan
def install(prefix, specs, args, data):
# TODO: do we need this?
common.check_specs(prefix, specs, json=args.json)
# TODO: support all various ways this happens
index = common.get_index_trap(
... | Add support for channels in the spec | Add support for channels in the spec
| Python | bsd-3-clause | conda/conda-env,ESSS/conda-env,phobson/conda-env,asmeurer/conda-env,nicoddemus/conda-env,mikecroucher/conda-env,conda/conda-env,dan-blanchard/conda-env,isaac-kit/conda-env,isaac-kit/conda-env,mikecroucher/conda-env,ESSS/conda-env,nicoddemus/conda-env,phobson/conda-env,dan-blanchard/conda-env,asmeurer/conda-env | ---
+++
@@ -10,7 +10,9 @@
common.check_specs(prefix, specs, json=args.json)
# TODO: support all various ways this happens
- index = common.get_index_trap()
+ index = common.get_index_trap(
+ channel_urls=data.get('channels', ())
+ )
actions = plan.install_actions(prefix, index, specs)... |
08da4c91853b14a264ea07fa5314be437fbce9d4 | src/gui/graphscheme.py | src/gui/graphscheme.py | # -*- coding: utf-8 -*-
from PySide import QtGui
class GraphScheme( QtGui.QGraphicsScene):
""" Graph scheme drawing class
This class inherits from QtGui.QGraphicsScene and add functions
for manage GraphBlocks objects in scheme.
"""
def __init__(self ):
super(GraphSc... | # -*- coding: utf-8 -*-
from PySide import QtGui, QtCore
class GraphScheme( QtGui.QGraphicsScene):
""" Graph scheme drawing class
This class inherits from QtGui.QGraphicsScene and add functions
for manage GraphBlocks objects in scheme.
"""
def __init__(self ):
super... | Add gradient background to GraphScheme | Add gradient background to GraphScheme
| Python | lgpl-2.1 | anton-golubkov/Garland,anton-golubkov/Garland | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
-from PySide import QtGui
+from PySide import QtGui, QtCore
class GraphScheme( QtGui.QGraphicsScene):
""" Graph scheme drawing class
@@ -18,6 +18,10 @@
self.form.setLayout(self.layout)
self.addItem(self.form)
self.form.setPos(0, 0... |
c5742bb27aa8446cb5b4c491df6be9c733a1408f | unitary/examples/tictactoe/enums.py | unitary/examples/tictactoe/enums.py | # Copyright 2022 Google
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | # Copyright 2022 Google
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Add enum for different rulesets | Add enum for different rulesets
| Python | apache-2.0 | quantumlib/unitary,quantumlib/unitary | ---
+++
@@ -20,10 +20,14 @@
X = 1
O = 2
-
class TicTacResult(enum.Enum):
UNFINISHED = 0
X_WINS = 1
O_WINS = 2
DRAW = 3
BOTH_WIN = 4
+
+class TicTacRules(enum.Enum):
+ CLASSICAL = 0
+ MINIMAL_QUANTUM = 1
+ FULLY_QUANTUM = 2 |
1dfb9fd979206af415e20fc58b905c435a187008 | app/soc/models/grading_project_survey.py | app/soc/models/grading_project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Set default taking access for GradingProjectSurvey to org. | Set default taking access for GradingProjectSurvey to org.
This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
| Python | apache-2.0 | MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging | ---
+++
@@ -32,4 +32,4 @@
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
- self.taking_access = 'mentor'
+ self.taking_access = 'org' |
ee37119a4f77eef5c8163936d982e178c42cbc00 | src/adhocracy/lib/machine_name.py | src/adhocracy/lib/machine_name.py |
import platform
class IncludeMachineName(object):
def __init__(self, app, config):
self.app = app
self.config = config
def __call__(self, environ, start_response):
def local_response(status, headers, exc_info=None):
headers.append(('X-Server-Machine', platform.node()))
... |
import os
import platform
class IncludeMachineName(object):
def __init__(self, app, config):
self.app = app
self.config = config
def __call__(self, environ, start_response):
def local_response(status, headers, exc_info=None):
machine_id = '%s:%s (PID %d)' % (
... | Add Server Port and PID to the X-Server-Machine header | Add Server Port and PID to the X-Server-Machine header
Fixes hhucn/adhocracy.hhu_theme#429
| Python | agpl-3.0 | liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielN... | ---
+++
@@ -1,4 +1,5 @@
+import os
import platform
@@ -10,6 +11,8 @@
def __call__(self, environ, start_response):
def local_response(status, headers, exc_info=None):
- headers.append(('X-Server-Machine', platform.node()))
+ machine_id = '%s:%s (PID %d)' % (
+ ... |
60c4534b1d375aecfe39948e27bc06d0f34907f3 | bioagents/resources/trips_ont_manager.py | bioagents/resources/trips_ont_manager.py | import os
from indra.preassembler.hierarchy_manager import HierarchyManager
# Make a TRIPS ontology
_fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf')
trips_ontology = HierarchyManager(_fname, uri_as_name=False)
trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/'
trips_ontology.init... | import os
from indra.preassembler.hierarchy_manager import HierarchyManager
# Make a TRIPS ontology
_fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf')
trips_ontology = HierarchyManager(_fname, uri_as_name=False, build_closure=True)
trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/'... | Build closure for TRIPS ontology | Build closure for TRIPS ontology
| Python | bsd-2-clause | sorgerlab/bioagents,bgyori/bioagents | ---
+++
@@ -3,7 +3,7 @@
# Make a TRIPS ontology
_fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf')
-trips_ontology = HierarchyManager(_fname, uri_as_name=False)
+trips_ontology = HierarchyManager(_fname, uri_as_name=False, build_closure=True)
trips_ontology.relations_prefix = 'http://trips.ih... |
89e2991109447893b06edf363f223c64e9cafb61 | query_result_list.py | query_result_list.py | from query_result_document import QueryResultDocument
class QueryResultList:
def __init__(self, query, result_documents = []):
self.result_documents = result_documents # Guaranteed to be in rank order
self.query = query
def add( self, rank, document ):
self.result_documents.insert( int(rank) - 1, Que... | from query_result_document import QueryResultDocument
class QueryResultList:
def __init__(self, query):
self.result_documents = [] # Guaranteed to be in rank order
self.query = query
def add( self, rank, document ):
self.result_documents.insert( int(rank) - 1, QueryResultDocument( self, rank, documen... | Fix query result list having an empty list default parameter (default parameters get initialized only once!) | Fix query result list having an empty list default parameter (default parameters get initialized only once!)
| Python | mit | fire-uta/iiix-data-parser | ---
+++
@@ -2,8 +2,8 @@
class QueryResultList:
- def __init__(self, query, result_documents = []):
- self.result_documents = result_documents # Guaranteed to be in rank order
+ def __init__(self, query):
+ self.result_documents = [] # Guaranteed to be in rank order
self.query = query
def add( s... |
74a944c47432f707bb8cf6cde421e4927eeeaebb | lib/cretonne/meta/isa/riscv/__init__.py | lib/cretonne/meta/isa/riscv/__init__.py | """
RISC-V Target
-------------
`RISC-V <http://riscv.org/>`_ is an open instruction set architecture
originally developed at UC Berkeley. It is a RISC-style ISA with either a
32-bit (RV32I) or 64-bit (RV32I) base instruction set and a number of optional
extensions:
RV32M / RV64M
Integer multiplication and divisi... | """
RISC-V Target
-------------
`RISC-V <https://riscv.org/>`_ is an open instruction set architecture
originally developed at UC Berkeley. It is a RISC-style ISA with either a
32-bit (RV32I) or 64-bit (RV32I) base instruction set and a number of optional
extensions:
RV32M / RV64M
Integer multiplication and divis... | Use an https URL rather than http. | Use an https URL rather than http.
Found by sphinx's linkcheck.
| Python | apache-2.0 | sunfishcode/cretonne,stoklund/cretonne,stoklund/cretonne,stoklund/cretonne,sunfishcode/cretonne,sunfishcode/cretonne | ---
+++
@@ -2,7 +2,7 @@
RISC-V Target
-------------
-`RISC-V <http://riscv.org/>`_ is an open instruction set architecture
+`RISC-V <https://riscv.org/>`_ is an open instruction set architecture
originally developed at UC Berkeley. It is a RISC-style ISA with either a
32-bit (RV32I) or 64-bit (RV32I) base instr... |
660e38254788f4eae8bb970d4949e93739374383 | src/stratisd_client_dbus/_connection.py | src/stratisd_client_dbus/_connection.py | # Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | Change to connect to Stratisd on the system bus | Change to connect to Stratisd on the system bus
Stratisd is changing to use the system bus, so naturally we need to
also change in order to continue working.
Signed-off-by: Andy Grover <b7d524d2f5cc5aebadb6b92b08d3ab26911cde33@redhat.com>
| Python | mpl-2.0 | trgill/stratisd,trgill/stratisd,stratis-storage/stratisd,stratis-storage/stratisd-client-dbus,mulkieran/stratisd,stratis-storage/stratisd,stratis-storage/stratisd,mulkieran/stratisd | ---
+++
@@ -35,7 +35,7 @@
Get our bus.
"""
if Bus._BUS is None:
- Bus._BUS = dbus.SessionBus()
+ Bus._BUS = dbus.SystemBus()
return Bus._BUS
|
015bc46057db405107799d7214b0fe5264843277 | run_deploy_job_wr.py | run_deploy_job_wr.py | #!/usr/bin/env python
import json
import os
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix='juju-ci/products/version-{}/{}/build-{}'.format... | #!/usr/bin/env python
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix='juju-ci/products/versi... | Fix artifact spec for deploy-job. | Fix artifact spec for deploy-job. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env python
import json
import os
+from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
@@ -22,13 +23,16 @@
with NamedTemporaryFile() as config_file:
json.dump({
'command': command, 'install': {},
- ... |
78f8634ac7ae959cfc7f34188ce4f56156922dcb | pkgpanda/integration-tests/test_fetch.py | pkgpanda/integration-tests/test_fetch.py | import os
from pkgpanda.util import expect_fs
from util import run
fetch_output = """\rFetching: mesos--0.22.0\rFetched: mesos--0.22.0\n"""
def test_fetch(tmpdir):
# NOTE: tmpdir is explicitly empty because we want to be sure a fetch.
# succeeds when there isn't anything yet.
# Start a simpleHTTPServer ... | import os
from pkgpanda.util import expect_fs
from util import run
fetch_output = """\rFetching: mesos--0.22.0\rFetched: mesos--0.22.0\n"""
def test_fetch(tmpdir):
# NOTE: tmpdir is explicitly empty because we want to be sure a fetch.
# succeeds when there isn't anything yet.
# Start a simpleHTTPServer ... | Add integration test for `pkgpanda add` | Add integration test for `pkgpanda add`
| Python | apache-2.0 | mesosphere-mergebot/dcos,vishnu2kmohan/dcos,xinxian0458/dcos,GoelDeepak/dcos,jeid64/dcos,mesosphere-mergebot/dcos,kensipe/dcos,lingmann/dcos,surdy/dcos,mesosphere-mergebot/mergebot-test-dcos,amitaekbote/dcos,amitaekbote/dcos,mnaboka/dcos,surdy/dcos,lingmann/dcos,amitaekbote/dcos,vishnu2kmohan/dcos,jeid64/dcos,mesospher... | ---
+++
@@ -27,3 +27,20 @@
})
# TODO(cmaloney): Test multiple fetches on one line.
# TODO(cmaloney): Test unable to fetch case.
+
+
+def test_add(tmpdir):
+ assert run([
+ "pkgpanda",
+ "add",
+ "{0}/../tests/resources/remote_repo/packages/mesos/mesos--0... |
f1e5e2cc7fd35e0446f105d619dc01d3ba837865 | byceps/blueprints/admin/party/forms.py | byceps/blueprints/admin/party/forms.py | """
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ..... | """
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ..... | Introduce base party form, limit `archived` flag to update form | Introduce base party form, limit `archived` flag to update form
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps | ---
+++
@@ -12,14 +12,17 @@
from ....util.l10n import LocalizedForm
-class UpdateForm(LocalizedForm):
+class _BaseForm(LocalizedForm):
title = StringField('Titel', validators=[Length(min=1, max=40)])
starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()])
ends_at... |
f9a0b8395adcf70c23c975a06e7667d673f74ac5 | stoneridge_uploader.py | stoneridge_uploader.py | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import requests
import stoneridge
class StoneRidgeUploader(object):
""... | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import requests
import stoneridge
class StoneRidgeUploader(object):
""... | Fix uploader when there is nothing to upload | Fix uploader when there is nothing to upload
| Python | mpl-2.0 | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge | ---
+++
@@ -19,6 +19,9 @@
def run(self):
file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json')
upload_files = glob.glob(file_pattern)
+ if not upload_files:
+ # Nothing to do, so forget it!
+ return
files = {os.path.basename(fname): open(fname, 'r... |
32d7921de5768fd74983ebff6fa37212aed24e83 | all/shellenv/_win.py | all/shellenv/_win.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import locale
from ._types import str_cls
_sys_encoding = locale.getpreferredencoding()
def get_env(shell=None):
"""
Return environment variables for the current user
:param shell:
The... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import locale
import sys
import ctypes
from ._types import str_cls
_sys_encoding = locale.getpreferredencoding()
kernel32 = ctypes.windll.kernel32
kernel32.GetEnvironmentStringsW.argtypes = []
kernel32.Get... | Use kernel32 with ST2 on Windows to get unicode environmental variable values | Use kernel32 with ST2 on Windows to get unicode environmental variable values
| Python | mit | codexns/shellenv | ---
+++
@@ -3,11 +3,18 @@
import os
import locale
+import sys
+import ctypes
from ._types import str_cls
_sys_encoding = locale.getpreferredencoding()
+
+kernel32 = ctypes.windll.kernel32
+
+kernel32.GetEnvironmentStringsW.argtypes = []
+kernel32.GetEnvironmentStringsW.restype = ctypes.c_void_p
def g... |
59fc12548422ecaa861f810d0e40b631801e2de0 | interface/backend/static/tests.py | interface/backend/static/tests.py | from django.test import TestCase
from django.urls import reverse
class SmokeTest(TestCase):
def test_landing(self):
url = reverse('static:home')
resp = self.client.get(url)
self.assertContains(resp, 'Concept to Clinic')
self.assertEqual(resp.status_code, 200)
| from django.test import TestCase
from django.urls import reverse
class SmokeTest(TestCase):
def test_landing(self):
url = reverse('static:open_image')
resp = self.client.get(url)
self.assertContains(resp, 'Concept to Clinic')
self.assertEqual(resp.status_code, 200)
| Fix failing test caused by view rename | Fix failing test caused by view rename
| Python | mit | vessemer/concept-to-clinic,antonow/concept-to-clinic,antonow/concept-to-clinic,antonow/concept-to-clinic,antonow/concept-to-clinic,vessemer/concept-to-clinic,vessemer/concept-to-clinic,vessemer/concept-to-clinic | ---
+++
@@ -4,7 +4,7 @@
class SmokeTest(TestCase):
def test_landing(self):
- url = reverse('static:home')
+ url = reverse('static:open_image')
resp = self.client.get(url)
self.assertContains(resp, 'Concept to Clinic')
self.assertEqual(resp.status_code, 200) |
f4aad7a704628e2ecdbc2222e71998bb71cf37ec | wake.py | wake.py | from been.couch import CouchStore
from flask import Flask, render_template
app = Flask(__name__)
app.jinja_env.trim_blocks = True
store = CouchStore()
store.load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.events())
if __name__ == '__main__':
app.run(debug=True)
| #!/usr/bin/env python
from been.couch import CouchStore
from flask import Flask, render_template
app = Flask(__name__)
app.jinja_env.trim_blocks = True
store = CouchStore()
store.load()
@app.route('/')
def wake():
return render_template('stream.html', events=store.events())
if __name__ == '__main__':
app.ru... | Add shebang to main script. | Add shebang to main script.
| Python | bsd-3-clause | chromakode/wake | ---
+++
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
from been.couch import CouchStore
from flask import Flask, render_template
|
3eaf93f2ecee68fafa1ff4f75d4c6e7f09a37043 | api/streams/views.py | api/streams/views.py | from api.streams.models import StreamConfiguration
from django.http import JsonResponse
from django.http.request import HttpRequest
import requests
def get_stream_status(request: HttpRequest, stream_slug: str):
stream = StreamConfiguration.objects.get(slug=stream_slug)
r = requests.get('http://{stream.host}:{... | from api.streams.models import StreamConfiguration
from django.http import JsonResponse
from django.http.request import HttpRequest
import requests
def get_stream_status(request: HttpRequest, stream_slug: str):
stream = StreamConfiguration.objects.get(slug=stream_slug)
r = requests.get('http://{stream.host}:{... | Add timeout to Icecast status request | Add timeout to Icecast status request
| Python | mit | urfonline/api,urfonline/api,urfonline/api | ---
+++
@@ -6,7 +6,7 @@
def get_stream_status(request: HttpRequest, stream_slug: str):
stream = StreamConfiguration.objects.get(slug=stream_slug)
- r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream))
+ r = requests.get('http://{stream.host}:{stream.port}/status-j... |
5f05c1f6e06594328a2b328f6b995288707f593c | src/winton_kafka_streams/kafka_stream.py | src/winton_kafka_streams/kafka_stream.py | """
Primary entrypoint for applications wishing to implement Python Kafka Streams
"""
import logging
import confluent_kafka as kafka
log = logging.getLogger(__name__)
class KafkaStream(object):
"""
Encapsulates stream graph processing units
"""
def __init__(self, topology, kafka_config):
... | """
Primary entrypoint for applications wishing to implement Python Kafka Streams
"""
import logging
import confluent_kafka as kafka
log = logging.getLogger(__name__)
class KafkaStream(object):
"""
Encapsulates stream graph processing units
"""
def __init__(self, topology, kafka_config):
... | Handle None returned from poll() | Handle None returned from poll()
| Python | apache-2.0 | wintoncode/winton-kafka-streams | ---
+++
@@ -41,7 +41,9 @@
running = True
while running:
msg = self.consumer.poll()
- if not msg.error():
+ if msg is None:
+ continue
+ elif not msg.error():
print('Received message: %s' % msg.value().decode('utf-8'))
... |
6adc30c9db58b2372c3d38f516f39faee3b87393 | tests/test_settings.py | tests/test_settings.py | from __future__ import unicode_literals
from os.path import dirname
MIU_TEST_ROOT = dirname(__file__)
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"markitup",
"tests",
"tests.test_migration",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlit... | from __future__ import unicode_literals
from os.path import dirname, abspath, join
BASE_DIR = dirname(abspath(__file__))
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"markitup",
"tests",
"tests.test_migration",
]
DATABASES = {
"default": {
"ENGINE": "djang... | Configure TEMPLATES in test settings. | Configure TEMPLATES in test settings.
| Python | bsd-3-clause | carljm/django-markitup,carljm/django-markitup,zsiciarz/django-markitup,zsiciarz/django-markitup,carljm/django-markitup,zsiciarz/django-markitup | ---
+++
@@ -1,8 +1,8 @@
from __future__ import unicode_literals
-from os.path import dirname
+from os.path import dirname, abspath, join
-MIU_TEST_ROOT = dirname(__file__)
+BASE_DIR = dirname(abspath(__file__))
INSTALLED_APPS = [
"django.contrib.auth",
@@ -18,6 +18,27 @@
}
}
+TEMPLATES = ... |
655f46a10245de0b7f4d9727f816815c6493d230 | tests/test_settings.py | tests/test_settings.py | # -*- coding:utf-8 -*-
import os
try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
from sigal.settings import read_settings
class TestSettings(unittest.TestCase):
"Read a settings file and check that the configuration is well done."
def setUp(self):
"Read the sa... | # -*- coding:utf-8 -*-
import os
try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
from sigal.settings import read_settings, get_thumb
class TestSettings(unittest.TestCase):
"Read a settings file and check that the configuration is well done."
def setUp(self):
"... | Add a test for the get_thumb function. | Add a test for the get_thumb function.
| Python | mit | jdn06/sigal,Ferada/sigal,elaOnMars/sigal,kontza/sigal,kontza/sigal,t-animal/sigal,kontza/sigal,franek/sigal,cbosdo/sigal,cbosdo/sigal,saimn/sigal,saimn/sigal,jasuarez/sigal,xouillet/sigal,t-animal/sigal,muggenhor/sigal,saimn/sigal,elaOnMars/sigal,Ferada/sigal,franek/sigal,muggenhor/sigal,cbosdo/sigal,jdn06/sigal,xouill... | ---
+++
@@ -7,7 +7,7 @@
except ImportError:
import unittest # NOQA
-from sigal.settings import read_settings
+from sigal.settings import read_settings, get_thumb
class TestSettings(unittest.TestCase):
@@ -26,3 +26,9 @@
def test_settings(self):
self.assertEqual(self.settings['thumb_suffix... |
733f2006f84ade6033a4be2fe3334213b8a2ce85 | mepcheck/savemeps.py | mepcheck/savemeps.py | import requests
from bs4 import BeautifulSoup
import pickle
import os
def save_meps():
url = "http://www.votewatch.eu//en/term8-european-parliament-members.html?limit=804"
path = os.path.expanduser("~")
r = requests.get(url)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, "html.parser")
meps... | import requests
from bs4 import BeautifulSoup
import pickle
import os
def save_meps():
# TODO - make this configurable
url = "http://www.votewatch.eu//en/term9-european-parliament-members.html?limit=1000"
path = os.path.expanduser("~")
r = requests.get(url)
r.encoding = 'utf-8'
soup = Beautifu... | Update url for new term | [HOTFIX] Update url for new term
There's a new term, I have to make this configurable | Python | mit | alanmarazzi/mepcheck | ---
+++
@@ -4,7 +4,8 @@
import os
def save_meps():
- url = "http://www.votewatch.eu//en/term8-european-parliament-members.html?limit=804"
+ # TODO - make this configurable
+ url = "http://www.votewatch.eu//en/term9-european-parliament-members.html?limit=1000"
path = os.path.expanduser("~")
r ... |
bba325111b47c9ba7dfc0bc9556a655e3f5afcee | tools/jtag/discover.py | tools/jtag/discover.py | #! /usr/bin/env python
'''
Simplistic chain discovery
'''
import sys
sys.path.append('../..')
from playtag.cables.digilent import Jtagger
from playtag.jtag.discover import Chain
print Chain(Jtagger())
| #! /usr/bin/env python
'''
Simplistic chain discovery
'''
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
from playtag.cables.digilent import Jtagger
from playtag.jtag.discover import Chain
print Chain(Jtagger())
| Make it work when executed from a different directory | Make it work when executed from a different directory | Python | mit | E3V3A/playtag,proteus-cpi/playtag | ---
+++
@@ -4,7 +4,9 @@
'''
import sys
-sys.path.append('../..')
+import os
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
from playtag.cables.digilent import Jtagger
from playtag.jtag.discover import Chain |
78351e785f413f44e07faa0b8a856639296a5591 | examples/drawing/ego_graph.py | examples/drawing/ego_graph.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example using the NetworkX ego_graph() function to return the main egonet of
the largest hub in a Barabási-Albert network.
"""
__author__="""Drew Conway (drew.conway@nyu.edu)"""
from operator import itemgetter
import networkx as nx
import matplotlib.pyplot as plt
if... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example using the NetworkX ego_graph() function to return the main egonet of
the largest hub in a Barabási-Albert network.
"""
__author__="""Drew Conway (drew.conway@nyu.edu)"""
from operator import itemgetter
import networkx as nx
import matplotlib.pyplot as plt
if... | Change name of output file in example | Change name of output file in example
--HG--
extra : convert_revision : svn%3A3ed01bd8-26fb-0310-9e4c-ca1a4053419f/networkx/trunk%401549
| Python | bsd-3-clause | RMKD/networkx,RMKD/networkx,jni/networkx,kernc/networkx,sharifulgeo/networkx,debsankha/networkx,kai5263499/networkx,farhaanbukhsh/networkx,jfinkels/networkx,NvanAdrichem/networkx,jakevdp/networkx,dmoliveira/networkx,jni/networkx,jakevdp/networkx,SanketDG/networkx,kernc/networkx,beni55/networkx,sharifulgeo/networkx,dhim... | ---
+++
@@ -26,5 +26,5 @@
nx.draw(hub_ego,pos,node_color='b',node_size=50,with_labels=False)
# Draw ego as large and red
nx.draw_networkx_nodes(hub_ego,pos,nodelist=[largest_hub],node_size=300,node_color='r')
- plt.savefig('main_ego.png')
+ plt.savefig('ego_graph.png')
plt.show() |
6ecbcfd1b132b0c4acd2d413818348a2fe2b6bfe | Cauldron/utils/referencecompat.py | Cauldron/utils/referencecompat.py | # -*- coding: utf-8 -*-
try:
from __builtins__ import ReferenceError
except (NameError, ImportError): # pragma: no cover
from weakref import ReferenceError
__all__ = ['ReferenceError']
| # -*- coding: utf-8 -*-
import sys
try:
if sys.version_info[0] < 3:
from __builtins__ import ReferenceError
else:
from builtins import ReferenceError
except (NameError, ImportError): # pragma: no cover
from weakref import ReferenceError
__all__ = ['ReferenceError']
| Fix a py3 bug in reference compatibility | Fix a py3 bug in reference compatibility
| Python | bsd-3-clause | alexrudy/Cauldron | ---
+++
@@ -1,7 +1,10 @@
# -*- coding: utf-8 -*-
-
+import sys
try:
- from __builtins__ import ReferenceError
+ if sys.version_info[0] < 3:
+ from __builtins__ import ReferenceError
+ else:
+ from builtins import ReferenceError
except (NameError, ImportError): # pragma: no cover
from we... |
492004049da87744cd96a6e6afeb9a6239a8ac44 | ocradmin/lib/nodetree/registry.py | ocradmin/lib/nodetree/registry.py | """
Registry class and global node registry.
"""
class NotRegistered(KeyError):
pass
__all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node in the node registry.
The node will be automatically instantiat... | """
Registry class and global node registry.
"""
import inspect
class NotRegistered(KeyError):
pass
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node class in the node registry."""
self[node.name] = inspect.isclass(node) and node or nod... | Fix missing import. Add method to get all nodes with a particular attribute | Fix missing import. Add method to get all nodes with a particular attribute
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -2,24 +2,18 @@
Registry class and global node registry.
"""
+import inspect
+
class NotRegistered(KeyError):
pass
-
-
-__all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
- """Register a node in the node reg... |
0225177c39df95bc12d9d9b53433f310d083905f | tests/test_heroku.py | tests/test_heroku.py | """Tests for the Wallace API."""
import subprocess
import re
import os
import requests
class TestHeroku(object):
"""The Heroku test class."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
os.environ['app_id'] = re.search(
'... | """Tests for the Wallace API."""
import subprocess
import re
import os
import requests
class TestHeroku(object):
"""The Heroku test class."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
os.environ['app_id'] = re.search(
'... | Add test for correct error for nonexistent routes | Add test for correct error for nonexistent routes
| Python | mit | berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dalli... | ---
+++
@@ -35,3 +35,9 @@
app_id = os.environ['app_id']
r = requests.get("http://{}.herokuapp.com/robots.txt".format(app_id))
assert r.status_code == 200
+
+ def test_nonexistent_route(self):
+ """Ensure that a nonexistent route returns a 500 error."""
+ app_id = os.environ... |
f97d9d6462ce9e60c1811bd40428a1f30835ce95 | hb_res/storage/FileExplanationStorage.py | hb_res/storage/FileExplanationStorage.py | from hb_res.storage import ExplanationStorage
__author__ = 'skird'
import codecs
from hb_res.explanations.Explanation import Explanation
class FileExplanationStorage(ExplanationStorage):
"""
Class representing explanation resource connected with some text file
"""
def __init__(self, path_to_file):
... | from hb_res.storage import ExplanationStorage
from hb_res.explanations.Explanation import Explanation
__author__ = 'skird'
class FileExplanationStorage(ExplanationStorage):
"""
Class representing explanation resource connected with some text file
"""
def __init__(self, path_to_file):
self.fi... | Fix permission-denied error in read-only context | Fix permission-denied error in read-only context
| Python | mit | hatbot-team/hatbot_resources | ---
+++
@@ -1,9 +1,7 @@
from hb_res.storage import ExplanationStorage
+from hb_res.explanations.Explanation import Explanation
__author__ = 'skird'
-
-import codecs
-from hb_res.explanations.Explanation import Explanation
class FileExplanationStorage(ExplanationStorage):
@@ -13,21 +11,28 @@
def __init... |
c471a5d6421e32e9c6e3ca2db0f07eae45a85408 | fuckit_commit.py | fuckit_commit.py | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
def set_configuration():
'''
Set Twilio configuration
'''
pass
def get_twilio_client():
'''
Connect to Twilio Client
'''
pas... | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
def get_configuration():
'''
Set Twilio configuration
'''
pass
def get_twilio_client(config):
'... | Add code to send sms | Add code to send sms
| Python | mit | ueg1990/fuckit_commit | ---
+++
@@ -4,27 +4,30 @@
'''
import requests
+from twilio.rest import TwilioRestClient
-def set_configuration():
+def get_configuration():
'''
Set Twilio configuration
'''
pass
-def get_twilio_client():
+def get_twilio_client(config):
'''
Connect to Twilio Client
'''
- p... |
048994463cda7df1bbaf502bef2bf84036e73403 | i18n/loaders/python_loader.py | i18n/loaders/python_loader.py | import os.path
import sys
from .loader import Loader, I18nFileLoadError
class PythonLoader(Loader):
"""class to load python files"""
def __init__(self):
super(PythonLoader, self).__init__()
def load_file(self, filename):
path, name = os.path.split(filename)
module_name, ext = os.p... | import os.path
import sys
from .loader import Loader, I18nFileLoadError
class PythonLoader(Loader):
"""class to load python files"""
def __init__(self):
super(PythonLoader, self).__init__()
def load_file(self, filename):
path, name = os.path.split(filename)
module_name, ext = os.... | Fix bug in python loader. | Fix bug in python loader.
| Python | mit | tuvistavie/python-i18n | ---
+++
@@ -2,6 +2,7 @@
import sys
from .loader import Loader, I18nFileLoadError
+
class PythonLoader(Loader):
"""class to load python files"""
@@ -15,8 +16,8 @@
sys.path.append(path)
try:
return __import__(module_name)
- except ImportError as e:
- rais... |
7bc247550f136c5f0e34f411b868f9e5949e1ec4 | api/tests/destinations/endpoint_tests.py | api/tests/destinations/endpoint_tests.py | import unittest
from peewee import SqliteDatabase
from playhouse.test_utils import test_database
import api.tests.helpers as helpers
from api.destinations.endpoint import *
from api.destinations.endpoint import _get_destinations
test_db = SqliteDatabase(':memory:')
class DestinationsTests(unittest.TestCase):
... | from peewee import SqliteDatabase
from api.destinations.endpoint import _get_destinations
from api.tests.dbtestcase import DBTestCase
test_db = SqliteDatabase(':memory:')
class DestinationsTests(DBTestCase):
def test_get_destinations_filters_zone(self):
self.assertEqual(2, len(_get_destinations()))
... | Update destination endpoint tests to work with new version of peewee | Update destination endpoint tests to work with new version of peewee
| Python | mit | mdowds/commutercalculator,mdowds/commutercalculator,mdowds/commutercalculator | ---
+++
@@ -1,28 +1,12 @@
-import unittest
+from peewee import SqliteDatabase
-from peewee import SqliteDatabase
-from playhouse.test_utils import test_database
-
-import api.tests.helpers as helpers
-from api.destinations.endpoint import *
from api.destinations.endpoint import _get_destinations
+from api.tests.db... |
0e14aaba251e3257bc298561a9004d88e0d8e3b6 | turbasen/__init__.py | turbasen/__init__.py | # encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
# Import the models we want directly available through the root module
from .models import \
Gruppe, \
Omrade, \
Sted
# Make configure directly available through the root module
from .settings import confi... | # encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
# Import the models we want directly available through the root module
from .models import (
Gruppe,
Omrade,
Sted,
)
# Make configure directly available through the root module
from .settings import config... | Apply parentheses for group import | Apply parentheses for group import
| Python | mit | Turbasen/turbasen.py | ---
+++
@@ -2,10 +2,11 @@
from __future__ import absolute_import, division, print_function, unicode_literals
# Import the models we want directly available through the root module
-from .models import \
- Gruppe, \
- Omrade, \
- Sted
+from .models import (
+ Gruppe,
+ Omrade,
+ Sted,
+)
# Mak... |
4f9569037ad835b852e6389b082155d45a88774c | kokki/cookbooks/nginx/recipes/default.py | kokki/cookbooks/nginx/recipes/default.py |
from kokki import *
Package("nginx")
Directory(env.config.nginx.log_dir,
mode = 0755,
owner = env.config.nginx.user,
action = 'create')
for nxscript in ('nxensite', 'nxdissite'):
File("/usr/sbin/%s" % nxscript,
content = Template("nginx/%s.j2" % nxscript),
mode = 0755,
owner ... |
from kokki import *
Package("nginx")
Directory(env.config.nginx.log_dir,
mode = 0755,
owner = env.config.nginx.user,
action = 'create')
for nxscript in ('nxensite', 'nxdissite'):
File("/usr/sbin/%s" % nxscript,
content = Template("nginx/%s.j2" % nxscript),
mode = 0755,
owner ... | Add silverline environment to nginx | Add silverline environment to nginx
| Python | bsd-3-clause | samuel/kokki | ---
+++
@@ -34,3 +34,14 @@
supports_reload = True,
action = "start",
subscribes = [("reload", env.resources["File"]["nginx.conf"])])
+
+if "librato.silverline" in env.included_recipes:
+ File("/etc/default/nginx",
+ owner = "root",
+ gorup = "root",
+ mode = 0644,
+ conte... |
c1889a71be161400a42ad6b7c72b2559a84f69bf | src/nodeconductor_assembly_waldur/invoices/tests/test_report.py | src/nodeconductor_assembly_waldur/invoices/tests/test_report.py | from django.test import TestCase
from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv
from .. import models
from . import fixtures
class TestReportFormatter(TestCase):
def test_invoice_items_are_properly_formatted(self):
fixture = fixtures.InvoiceFixture()
package = fixtur... | from django.test import TestCase
from nodeconductor_assembly_waldur.invoices.tasks import format_invoice_csv
from .. import models
from . import fixtures
class TestReportFormatter(TestCase):
def setUp(self):
fixture = fixtures.InvoiceFixture()
package = fixture.openstack_package
invoice ... | Add unit test for report formatter | Add unit test for report formatter [WAL-905]
| Python | mit | opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -7,9 +7,20 @@
class TestReportFormatter(TestCase):
- def test_invoice_items_are_properly_formatted(self):
+ def setUp(self):
fixture = fixtures.InvoiceFixture()
package = fixture.openstack_package
invoice = models.Invoice.objects.get(customer=package.tenant.service_pro... |
11c30f5dd765475a9f5f0f847f31c47af8c40a39 | user_agent/device.py | user_agent/device.py | import os.path
import json
PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
SMARTPHONE_DEV_IDS = json.load(open(f))
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
TABLET_DEV_IDS = json.load(open())
| import os.path
import json
PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
SMARTPHONE_DEV_IDS = json.load(f)
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
TABLET_DEV_IDS = json.load(f)
| Fix uses of file objects | Fix uses of file objects | Python | mit | lorien/user_agent | ---
+++
@@ -4,6 +4,6 @@
PACKAGE_DIR = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_DIR, 'data/smartphone_dev_id.json')) as f:
- SMARTPHONE_DEV_IDS = json.load(open(f))
+ SMARTPHONE_DEV_IDS = json.load(f)
with open(os.path.join(PACKAGE_DIR, 'data/tablet_dev_id.json')) as f:
- ... |
2158edb92cba6c19fa258f19445191d0308c4153 | utils/async_tasks.py | utils/async_tasks.py | from utils.redis_store import store
def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60):
# Get task results previously stored in store
output, elapsed_time = store.get(store_key, include_elapsed_time=True)
# If there are no previously stored results (elapsed_time will ... | from utils.redis_store import store
from celery.signals import task_postrun, task_prerun
def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60, run_once=True):
# Get task results previously stored in store
output, elapsed_time = store.get(store_key, include_elapsed_time=True)... | Add option to run async tasks only on at a time | Add option to run async tasks only on at a time
This is implemented with a simple lock like mechanism using redis.
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | ---
+++
@@ -1,13 +1,37 @@
from utils.redis_store import store
+from celery.signals import task_postrun, task_prerun
-def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60):
+def data_from_async_task(task_func, task_args, task_kwargs, store_key, refresh_time=60, run_once=True):
+
... |
43e86a3ac5f63c702ce409c45e3aaaac60990fe9 | python/ensure_haddock_coverage.py | python/ensure_haddock_coverage.py | #!/usr/bin/env python
"""
Tiny utility script to check that coverage statistics output by stack haddock
are all 100%.
"""
import sys
import re
def main():
"""Entry point to ensure-haddock-coverage.py."""
# Verify that the number of arguments is correct.
if len(sys.argv) != 2:
print("Usage: ./ensure... | #!/usr/bin/env python
"""
Tiny utility script to check that coverage statistics output by stack haddock
are all 100%.
"""
import sys
import re
def main():
"""Entry point to ensure-haddock-coverage.py."""
# Verify that the number of arguments is correct.
if len(sys.argv) != 2:
print("Usage: ./ensure... | Check for number of modules in haddock-checking script | Check for number of modules in haddock-checking script
| Python | mit | gibiansky/jupyter-haskell | ---
+++
@@ -34,6 +34,14 @@
.format(name, coverage))
insufficient_coverage = True
+ if len(stats) < 8:
+ print(("Expecting at least 8 Haddock-covered modules.\n"
+ "Possibly Haddock output nothing, or number of modules "
+ "has decreased.\nIf numb... |
8b9ebbad9e87af3f56570ba3c32dcdb2d7ca4a39 | django_iceberg/models/base_models.py | django_iceberg/models/base_models.py |
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod")
class IcebergBaseModel(models.Model):
ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sa... |
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
DEFAULT_ICEBERG_ENV = getattr(settings, 'ICEBERG_DEFAULT_ENVIRO', "prod")
class IcebergBaseModel(models.Model):
ICEBERG_PROD, ICEBERG_SANDBOX, ICEBERG_STAGE, ICEBERG_SANDBOX_STAGE = "prod", "sa... | Add app_name for django < 1.7 compatibility | Add app_name for django < 1.7 compatibility
| Python | mit | izberg-marketplace/django-izberg,izberg-marketplace/django-izberg,Iceberg-Marketplace/django-iceberg,Iceberg-Marketplace/django-iceberg | ---
+++
@@ -22,6 +22,7 @@
API_RESOURCE_NAME = None
class Meta:
+ app_label = "django_iceberg"
abstract = True
def iceberg_sync(self, api_handler): |
9535234db263f0155f515236457ee7ba5e9e1e0e | punic/cartfile.py | punic/cartfile.py | from __future__ import division, absolute_import, print_function
__all__ = ['Cartfile']
import re
from pathlib2 import Path
from .basic_types import *
from .errors import *
class Cartfile(object):
def __init__(self, specifications=None, overrides=None):
self.specifications = specifications if specificat... | from __future__ import division, absolute_import, print_function
__all__ = ['Cartfile']
import re
from pathlib2 import Path
from .basic_types import *
from .errors import *
class Cartfile(object):
def __init__(self, specifications=None, overrides=None):
self.specifications = specifications if specificat... | Fix processing of empty lines. | Fix processing of empty lines.
| Python | mit | schwa/punic | ---
+++
@@ -24,6 +24,8 @@
# TODO: This is of course super feeble parsing. URLs with #s in them can break for example
lines = [line.rstrip() for line in source.splitlines()]
lines = [re.sub(r'\#.+', '', line) for line in lines]
+ lines = [line.strip() for line in lines]
+ lines... |
0c186d8e0fb5bd7170ec55943e546f1e4e335839 | masters/master.tryserver.chromium/master_site_config.py | masters/master.tryserver.chromium/master_site_config.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class TryServer(Master.Master4):
project_name = 'Chromium Try Server'
master_port = ... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class TryServer(Master.Master4):
project_name = 'Chromium Try Server'
master_port = ... | Remove last good URL for tryserver.chromium | Remove last good URL for tryserver.chromium
The expected behavior of this change is that the tryserver master no longer tries
to resolve revisions to LKGR when trying jobs.
BUG=372499, 386667
Review URL: https://codereview.chromium.org/394653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283469 0039d316-1... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -17,7 +17,7 @@
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
- last_good_url = base_app_url + '/lkgr'
- last_good_blink_url = 'http://blink-status.appspot.com/lkgr'
+ last_good_url = None
+ last... |
94e344b48161e20fec5023fbeea4a14cdc736158 | pynuts/filters.py | pynuts/filters.py | # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Field data beautifier.
QuerySelectMultipleField
Renders comma-separated data.
QuerySelectField... | # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Field data beautifier.
QuerySelectMultipleField
Renders comma-separated data.
QuerySelectField... | Return an "empty sequence" character instead of an empty list for empty select fields | Return an "empty sequence" character instead of an empty list for empty select fields
| Python | bsd-3-clause | Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts | ---
+++
@@ -28,6 +28,8 @@
if field.data:
return escape(
u', '.join(field.get_label(data) for data in field.data))
+ else:
+ return u'∅'
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data)... |
7111860577c921dc3d1602fa16b22ddfb45b69ed | lots/migrations/0002_auto_20170717_2115.py | lots/migrations/0002_auto_20170717_2115.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
LotType(name="Casa").save()
LotType(name="Lote").save()
class Migrat... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations
from lots.models import LotType
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
LotType(name="Casa").save()
LotType(n... | Add reverse action to importing default lot types | Add reverse action to importing default lot types
| Python | mpl-2.0 | jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django | ---
+++
@@ -3,6 +3,8 @@
from __future__ import unicode_literals
from django.db import models, migrations
+
+from lots.models import LotType
def load_data(apps, schema_editor):
@@ -10,6 +12,9 @@
LotType(name="Casa").save()
LotType(name="Lote").save()
+
+def remove_data(apps, schema_editor):
+ L... |
78f55cf57d88378e59cf1399d7ef80082d3f9555 | bluebottle/partners/serializers.py | bluebottle/partners/serializers.py | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer
from rest_framework import serializers
# This is a bit of a hack. We have an existing Proje... | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationPreviewSerializer(serializers.ModelSerializer):
id = se... | Fix partner project serializer. (The comment was outdated btw) | Fix partner project serializer. (The comment was outdated btw)
| Python | bsd-3-clause | onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -1,28 +1,7 @@
from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
-from bluebottle.projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer
+from bluebottle.projects.serializers import ProjectPreviewSeri... |
b973a1686f269044e670704b56c07ca79336c29c | mythril/laser/ethereum/strategy/basic.py | mythril/laser/ethereum/strategy/basic.py | class DepthFirstSearchStrategy:
def __init__(self, content, max_depth):
self.content = content
self.max_depth = max_depth
def __iter__(self):
return self
def __next__(self):
try:
global_state = self.content.pop(0)
if global_state.mstate.depth >= sel... | """
This module implements basic symbolic execution search strategies
"""
class DepthFirstSearchStrategy:
"""
Implements a depth first search strategy
I.E. Follow one path to a leaf, and then continue to the next one
"""
def __init__(self, work_list, max_depth):
self.work_list = work_list
... | Add documentation and fix pop | Add documentation and fix pop
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | ---
+++
@@ -1,17 +1,29 @@
+"""
+This module implements basic symbolic execution search strategies
+"""
+
+
class DepthFirstSearchStrategy:
-
- def __init__(self, content, max_depth):
- self.content = content
+ """
+ Implements a depth first search strategy
+ I.E. Follow one path to a leaf, and the... |
052c0cfd1ce21b36c9c9a44193e3a9c89ca871f1 | ciscripts/coverage/bii/coverage.py | ciscripts/coverage/bii/coverage.py | # /ciscripts/coverage/bii/coverage.py
#
# Submit coverage totals for a bii project to coveralls
#
# See /LICENCE.md for Copyright information
"""Submit coverage totals for a bii project to coveralls."""
import errno
import os
from contextlib import contextmanager
@contextmanager
def _bii_deps_in_place(cont):
"... | # /ciscripts/coverage/bii/coverage.py
#
# Submit coverage totals for a bii project to coveralls
#
# See /LICENCE.md for Copyright information
"""Submit coverage totals for a bii project to coveralls."""
import errno
import os
from contextlib import contextmanager
def _move_ignore_enoent(src, dst):
"""Move src ... | Make _bii_deps_in_place actually behave like a context manager | bii: Make _bii_deps_in_place actually behave like a context manager
| Python | mit | polysquare/polysquare-ci-scripts,polysquare/polysquare-ci-scripts | ---
+++
@@ -12,6 +12,15 @@
from contextlib import contextmanager
+def _move_ignore_enoent(src, dst):
+ """Move src to dst, ignoring ENOENT."""
+ try:
+ os.rename(src, dst)
+ except OSError as error:
+ if error.errno != errno.ENOENT:
+ raise error
+
+
@contextmanager
def _bii_d... |
08300895dc8d2abb740dd71b027e9acda8bb84dd | chatterbot/ext/django_chatterbot/views.py | chatterbot/ext/django_chatterbot/views.py | from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
class ChatterBotView(View):
def post(self, request, *args, **kwargs):
input_statement = request.POST.get('text')
response_data = settings.CHATTERBOT.get_response(input_statement)
... | from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
from chatterbot import ChatBot
class ChatterBotView(View):
chatterbot = ChatBot(
settings.CHATTERBOT['NAME'],
storage_adapter='chatterbot.adapters.storage.DjangoStorageAdapter',
inp... | Initialize ChatterBot in django view module instead of settings. | Initialize ChatterBot in django view module instead of settings.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot | ---
+++
@@ -1,14 +1,23 @@
from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
+from chatterbot import ChatBot
class ChatterBotView(View):
+ chatterbot = ChatBot(
+ settings.CHATTERBOT['NAME'],
+ storage_adapter='chatterbot.adapters.sto... |
5c0c2f470451c69a2b4cbba3746d26207c6b17a9 | lang/__init__.py | lang/__init__.py | from . import tokenizer, ast, codegen
import sys, os, subprocess
TRIPLES = {
'darwin': 'x86_64-apple-darwin11.0.0',
'linux2': 'x86_64-pc-linux-gnu',
}
def llir(fn, full=True):
src = codegen.source(ast.parse(tokenizer.tokenize(open(fn))))
if not full:
return src
std = []
for fn in sorted(os.listdir('rt')):... | from . import tokenizer, ast, codegen
import sys, os, subprocess
BASE = os.path.dirname(__path__[0])
RT_DIR = os.path.join(BASE, 'rt')
TRIPLES = {
'darwin': 'x86_64-apple-darwin11.0.0',
'linux2': 'x86_64-pc-linux-gnu',
}
def llir(fn, full=True):
src = codegen.source(ast.parse(tokenizer.tokenize(open(fn))))
if ... | Fix up path to runtime library directory. | Fix up path to runtime library directory.
| Python | mit | djc/runa,djc/runa,djc/runa,djc/runa | ---
+++
@@ -1,5 +1,8 @@
from . import tokenizer, ast, codegen
import sys, os, subprocess
+
+BASE = os.path.dirname(__path__[0])
+RT_DIR = os.path.join(BASE, 'rt')
TRIPLES = {
'darwin': 'x86_64-apple-darwin11.0.0',
@@ -13,8 +16,8 @@
return src
std = []
- for fn in sorted(os.listdir('rt')):
- with open(... |
4c00c394e4015a7cae5c5de574d996b20252ea3f | corgi/numpy_utils.py | corgi/numpy_utils.py | def remove_low_variance(X, low_variance_threshold=1e-4, axis=0):
low_variance = X.var(axis=axis) < low_variance_threshold
X[:, ~low_variance]
return X
def normalize(X):
zero_mean = X - X.mean()
return (zero_mean + zero_mean.min()) / X.max()
| def remove_low_variance(X, low_variance_threshold=1e-4, axis=0):
low_variance = X.var(axis=axis) < low_variance_threshold
X[:, ~low_variance]
return X
def normalize(X):
zero_mean = X - X.mean()
return (zero_mean + zero_mean.min()) / X.max()
def independent_columns(A, tol=1e-05):
"""
Retu... | Add a function for removing & finding independent columns from an array | Add a function for removing & finding independent columns from an array
| Python | mit | log0ymxm/corgi | ---
+++
@@ -7,3 +7,33 @@
def normalize(X):
zero_mean = X - X.mean()
return (zero_mean + zero_mean.min()) / X.max()
+
+
+def independent_columns(A, tol=1e-05):
+ """
+ Return an array composed of independent columns of A.
+
+ Note the answer may not be unique; this function returns one of many
+ ... |
129cd22de51d58cc956ca5586fc15cd2e247446b | gpkitmodels/GP/aircraft/prop/propeller.py | gpkitmodels/GP/aircraft/prop/propeller.py | " propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
"""
def setup(self):
exec parse_variables(Propeller._... | " propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
W 10 [lbf] prop weight
"""
def ... | Add prop structure and performance models | Add prop structure and performance models
| Python | mit | convexengineering/gplibrary,convexengineering/gplibrary | ---
+++
@@ -8,6 +8,7 @@
Variables
---------
R 10 [m] prop radius
+ W 10 [lbf] prop weight
"""
def setup(self):
@@ -35,12 +36,12 @@
def helper(self, c):
return 2. - 1./c[self.etaadd]
- def setup(self, state):
+ def... |
085a61894143b525a8cf8fe7f2029e4993a4279a | lib/exp/filters/ransac.py | lib/exp/filters/ransac.py | import numpy as np
import cv2
from core import KpFilter
class Ransac(KpFilter):
def __init__(self, data):
KpFilter.__init__(self, data)
def __good_pts(self, kps, mps):
rr = [kps[m].pt for m in mps]
return np.float32(rr).reshape(-1, 1, 2)
def __compute(self, good, skp, vkp, min_ma... | import numpy as np
import cv2
from core import KpFilter
class Ransac(KpFilter):
def __init__(self, data):
KpFilter.__init__(self, data)
def __good_pts(self, kps, mps):
rr = [kps[m].pt for m in mps]
return np.float32(rr).reshape(-1, 1, 2)
def __compute(self, good, skp, vkp, min_ma... | Fix filter_ method calling parent method bug | Fix filter_ method calling parent method bug
| Python | agpl-3.0 | speed-of-light/pyslider | ---
+++
@@ -34,7 +34,7 @@
"""
Returned by-product: M, the homography boundary
"""
- good, skp, fkp = KpFilter.filter_()
+ good, skp, fkp = KpFilter.filter_(self)
M, mask = self.__compute(good, skp, fkp, min_matches=min_matches)
self.data['matches']['keep'] = ... |
570bbe3add6a19a7ec6c14adfa04da76d14aa740 | common/templatetags/lutris.py | common/templatetags/lutris.py | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... | Fix bug in download links | Fix bug in download links
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website | ---
+++
@@ -14,7 +14,7 @@
main_download = None
for system in systems:
if system in user_agent:
- main_download = {system: settings.DOWNLOADS[system]}
+ main_download = {system: downloads[system]}
downloads.pop(system)
if not main_download:
main_downl... |
2c63efeb705637a068c909be7dc72f18e90561bf | cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py | cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | Update resource group unit test | Update resource group unit test
| Python | mit | ms-azure-cloudbroker/cloudbridge | ---
+++
@@ -9,12 +9,12 @@
resource_group_params)
print("Create Resource - " + str(rg))
self.assertTrue(
- rg.name == "cloudbridge",
- "Resource Group should be Cloudbridge")
+ rg.name == self.provider.resource_group,
+ "R... |
276f74dfef46f5fa0913ddd3759d682eb58c7cec | chmvh_website/gallery/tasks.py | chmvh_website/gallery/tasks.py | from io import BytesIO
from django.conf import settings
from django.core.files.base import ContentFile
from PIL import Image
from chmvh_website import celery_app
@celery_app.task
def create_thumbnail(patient):
image = Image.open(patient.picture.path)
pil_type = image.format
if pil_type == 'JPEG':
... | from io import BytesIO
from celery.utils.log import get_task_logger
from django.conf import settings
from django.core.files.base import ContentFile
from PIL import Image
from chmvh_website import celery_app
_INVALID_FORMAT_ERROR = ("Can't generate thumbnail for {type} filetype. "
"(Path: ... | Add logging to thumbnail creation task. | Add logging to thumbnail creation task.
| Python | mit | cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website | ---
+++
@@ -1,4 +1,6 @@
from io import BytesIO
+
+from celery.utils.log import get_task_logger
from django.conf import settings
from django.core.files.base import ContentFile
@@ -8,8 +10,16 @@
from chmvh_website import celery_app
+_INVALID_FORMAT_ERROR = ("Can't generate thumbnail for {type} filetype. "
+ ... |
d535cf76b3129c0e5b6908a720bdf3e3a804e41b | mopidy/mixers/gstreamer_software.py | mopidy/mixers/gstreamer_software.py | import multiprocessing
from mopidy.mixers import BaseMixer
from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*arg... | from mopidy.mixers import BaseMixer
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
return self.backend.output... | Update GStreamer software mixer to use new output API | Update GStreamer software mixer to use new output API
| Python | apache-2.0 | SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,ali/mopidy,quartz55/mopidy,adamcik/mopidy,liamw9534/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,abarisain/mopidy,swak/mopidy,mopidy/mopidy,pacificIT/mopidy,swak/mopidy,diandiankan/mopidy,adamcik/mopidy,bencevans/mopidy,hkariti/mopidy,glogiotatidis/mopidy,vrs01/mopidy,... | ---
+++
@@ -1,7 +1,4 @@
-import multiprocessing
-
from mopidy.mixers import BaseMixer
-from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
@@ -10,16 +7,7 @@
super(GStreamerSoftwareMixer, self).__i... |
104c136488d468f26c7fe247d0548636cbf3c6fe | random_4.py | random_4.py | """ How to generate a random 4 digit number not starting with 0 and having unique digits in python? """
import random
l = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(l)
if l[0] == 0:
print(''.join(map(str, l[1:5])))
else:
print(''.join(map(str, l[0:4])))
| """ How to generate a random 4 digit number not starting with 0 and having unique digits in python? """
import random
# 1.
l = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(l)
if l[0] == 0:
pos = random.choice(range(1, len(l)))
l[0], l[pos] = l[pos], l[0]
print(''.join(map(str, l[0:4])))
# 2.
# We create a set of dig... | Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions. | Fix of shuffle. There should be random swap of leading zero with one from nine (non-zero) positions.
| Python | mit | foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard | ---
+++
@@ -1,9 +1,28 @@
""" How to generate a random 4 digit number not starting with 0 and having unique digits in python? """
import random
+
+# 1.
l = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(l)
if l[0] == 0:
- print(''.join(map(str, l[1:5])))
-else:
- print(''.join(map(str, l[0:4])))
+ pos = random.c... |
863b12e503559b24de29407cd674d432bdcbbfc0 | cs251tk/referee/send_email.py | cs251tk/referee/send_email.py | import smtplib
def send_email(msg):
# Send the message via our own SMTP server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
# s.starttls()
s.set_debuglevel(2)
s.send_message(msg)
| import smtplib
def send_email(msg):
# Send the message via our own SMTP server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
s.send_message(msg)
| Remove somore more lines related to email | Remove somore more lines related to email
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit | ---
+++
@@ -4,6 +4,4 @@
def send_email(msg):
# Send the message via our own SMTP server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
- # s.starttls()
- s.set_debuglevel(2)
s.send_message(msg) |
1c0d42889b721cf68deb199711d8ae7700c40b66 | marcottimls/tools/logsetup.py | marcottimls/tools/logsetup.py | import os
import json
import logging
import logging.config
def setup_logging(log_path, settings_path="logging.json", default_level=logging.INFO):
"""Setup logging configuration"""
path = settings_path
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
co... | import os
import json
import logging
import logging.config
def setup_logging(settings_path="logging.json", default_level=logging.INFO):
"""Setup logging configuration"""
path = settings_path
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.conf... | Remove kludge from setup_logging as no longer necessary | Remove kludge from setup_logging as no longer necessary
| Python | mit | soccermetrics/marcotti-mls | ---
+++
@@ -4,13 +4,12 @@
import logging.config
-def setup_logging(log_path, settings_path="logging.json", default_level=logging.INFO):
+def setup_logging(settings_path="logging.json", default_level=logging.INFO):
"""Setup logging configuration"""
path = settings_path
if os.path.exists(path):
... |
93be3585d269360641091f18a6443979eb8f1f98 | cito/dump_db.py | cito/dump_db.py | """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.AS... | """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.AS... | Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing. | BUG: Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing.
| Python | bsd-3-clause | tunnell/wax,tunnell/wax,tunnell/wax | ---
+++
@@ -37,11 +37,10 @@
# are no documents in the collection...
print('Using index:', cursor.explain()['indexOnly'])
- # Stats on how the delete worked. Write concern (w=1) is on.
+ # Stats on how the delete worked. Write concern is on.
print(json.du... |
44ed4ceffcbf95ed42e4bdebcc87a7137a97de50 | been/source/markdown.py | been/source/markdown.py | from been.core import DirectorySource, source_registry
class Markdown(DirectorySource):
kind = 'markdown'
def process_event(self, event):
lines = event['content'].splitlines()
event['title'] = lines[0]
event['content'] = "\n".join(lines[1:])
event['summary'] = event['content']
... | from been.core import DirectorySource, source_registry
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
lines = event['content'].splitlines()
event['title'] = lines[0]
event['content'] = "\n".join(lines[1:])
event['summary'] = event['co... | Rename Markdown source to MarkdownDirectory. | Rename Markdown source to MarkdownDirectory.
| Python | bsd-3-clause | chromakode/been | ---
+++
@@ -1,6 +1,6 @@
from been.core import DirectorySource, source_registry
-class Markdown(DirectorySource):
+class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
lines = event['content'].splitlines()
@@ -8,4 +8,4 @@
event['content'] = "\n".joi... |
a28f6a45f37d906a9f9901d46d683c3ca5406da4 | code/csv2map.py | code/csv2map.py | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | Add infos about MAP file | Add infos about MAP file
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan | ---
+++
@@ -10,7 +10,7 @@
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlle... |
b1f06fc602f2d787b9d564a99d8c92f731ab104c | twext/internet/test/__init__.py | twext/internet/test/__init__.py | ##
# Copyright (c) 2005-2007 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | Build system doesn't approve of empty files | Build system doesn't approve of empty files
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6616 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver | ---
+++
@@ -0,0 +1,15 @@
+##
+# Copyright (c) 2005-2007 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
... | |
75225c176135b6d17c8f10ea67dabb4b0fc02505 | nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py | nodeconductor/iaas/migrations/0009_add_min_ram_and_disk_to_image.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [
('iaas', '0008_add_instance_restarting_state'),
]
operations = [
migrations.AddField(
model_name... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [
('iaas', '0008_add_instance_restarting_state'),
]
operations = [
migrations.AddField(
model_name... | Remove field duplication from migrations(nc-301) | Remove field duplication from migrations(nc-301)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -24,10 +24,4 @@
field=models.PositiveIntegerField(default=0, help_text='Minimum memory size in MiB'),
preserve_default=True,
),
- migrations.AlterField(
- model_name='instance',
- name='state',
- field=django_fsm.FSMIntegerField(def... |
496fc83101155bd0cd2fb4256e2878007aec8eaa | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Use source key instead of meta and detail fields | Use source key instead of meta and detail fields
| Python | apache-2.0 | asanfilippo7/osf.io,emetsger/osf.io,rdhyee/osf.io,cosenal/osf.io,haoyuchen1992/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,doublebits/osf.io,mluke93/osf.io,amyshi188/osf.io,monikagrabowska/osf.io,doublebits/osf.io,icereval/osf.io,sloria/osf.io,pattisdr/osf.io,ZobairAlijan/osf.io,adlius/osf.io,hmoco/osf.io,Johnetord... | ---
+++
@@ -23,9 +23,9 @@
else:
if isinstance(value, list):
for reason in value:
- errors.append({'detail': reason, 'meta': {'field': key}})
+ errors.append({'source': {key: reason}})
... |
0223b6fc332bdbc8a641832ebd06b79969b65853 | pyfibot/modules/module_btc.py | pyfibot/modules/module_btc.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals, print_function, division
def command_btc(bot, user, channel, args):
"""Display BTC exchange rates"""
r = bot.get_url("http://bitcoincharts.com/t/weighted_prices.json")
data = r.json()
eur_rate = float(data['EUR']['24h'])
usd_rate ... | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals, print_function, division
def command_btc(bot, user, channel, args):
"""Display current BTC exchange rates from mtgox"""
r = bot.get_url("http://data.mtgox.com/api/1/BTCUSD/ticker")
btcusd = r.json()['return']['avg']['display_short']
r... | Use mtgox as data source | Use mtgox as data source
| Python | bsd-3-clause | rnyberg/pyfibot,lepinkainen/pyfibot,EArmour/pyfibot,huqa/pyfibot,aapa/pyfibot,huqa/pyfibot,rnyberg/pyfibot,EArmour/pyfibot,lepinkainen/pyfibot,aapa/pyfibot | ---
+++
@@ -3,11 +3,11 @@
def command_btc(bot, user, channel, args):
- """Display BTC exchange rates"""
+ """Display current BTC exchange rates from mtgox"""
- r = bot.get_url("http://bitcoincharts.com/t/weighted_prices.json")
- data = r.json()
- eur_rate = float(data['EUR']['24h'])
- usd_rat... |
0868bbd0e445cb39217351cd13d2c3f7a173416c | mws/__init__.py | mws/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .mws import MWS, MWSError
from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\
OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\
Reports, Sellers
__all__ = [
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .mws import MWS, MWSError
from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\
OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\
Reports, Sellers, Subscriptio... | Include the new Subscriptions stub | Include the new Subscriptions stub | Python | unlicense | GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws | ---
+++
@@ -4,7 +4,7 @@
from .mws import MWS, MWSError
from .apis import Feeds, Finances, InboundShipments, Inventory, MerchantFulfillment,\
OffAmazonPayments, Orders, OutboundShipments, Products, Recommendations,\
- Reports, Sellers
+ Reports, Sellers, Subscript... |
a91a81c16a27d72cdc41de322130e97889657561 | marbaloo_mako/__init__.py | marbaloo_mako/__init__.py | import cherrypy
from mako.lookup import TemplateLookup
class Tool(cherrypy.Tool):
_lookups = {}
def __init__(self):
cherrypy.Tool.__init__(self, 'before_handler',
self.callable,
priority=40)
def callable(self,
filenam... | import cherrypy
from mako.lookup import TemplateLookup
class Tool(cherrypy.Tool):
_lookups = {}
def __init__(self):
cherrypy.Tool.__init__(self, 'before_handler',
self.callable,
priority=40)
def callable(self,
filenam... | Load template from `cherrypy.request.template` in handler. | Load template from `cherrypy.request.template` in handler.
| Python | mit | marbaloo/marbaloo_mako | ---
+++
@@ -29,13 +29,13 @@
input_encoding='utf8')
self._lookups[key] = lookup
cherrypy.request.lookup = lookup
+ cherrypy.request.template = lookup.get_template(filename)
+
# Replace the current handler.
- cherrypy.request.template = t... |
90a94b1d511aa17f167d783992fe0f874ad529c1 | examples/python_interop/python_interop.py | examples/python_interop/python_interop.py | #!/usr/bin/env python
# Copyright 2017 Stanford University
#
# 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 applicabl... | #!/usr/bin/env python
# Copyright 2017 Stanford University
#
# 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 applicabl... | Test Python support for arguments. | examples: Test Python support for arguments.
| Python | apache-2.0 | StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLegion/legion | ---
+++
@@ -20,10 +20,10 @@
import legion
@legion.task
-def f(ctx):
- print("inside task f")
+def f(ctx, *args):
+ print("inside task f%s" % (args,))
@legion.task
def main_task(ctx):
- print("%x" % legion.c.legion_runtime_get_executing_processor(ctx.runtime, ctx.context).id)
- f(ctx)
+ print("i... |
f1fcce8f0c2022948fb310268a7769d9c9ef04ad | runtests.py | runtests.py | #!/usr/bin/env python
import sys
import logging
from optparse import OptionParser
from coverage import coverage
from tests.config import configure
logging.disable(logging.CRITICAL)
def run_tests(options, *test_args):
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=opt... | #!/usr/bin/env python
import sys
import logging
from optparse import OptionParser
from tests.config import configure
logging.disable(logging.CRITICAL)
def run_tests(*test_args):
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner()
if not test_args:
test_args = ['tests'... | Rework test runner to generate coverage stats correctly. | Rework test runner to generate coverage stats correctly.
Nose seems to pick up argv automatically - which is annoying. Will need
to look into at some point.
| Python | bsd-3-clause | michaelkuty/django-oscar,WillisXChen/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,sasha0/django-oscar,okfish/django-oscar,nickpack/django-oscar,rocopartners/django-oscar,django-oscar/django-oscar,WillisXChen/django-oscar,makielab/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,jinnykoo/wuyisj.com,nf... | ---
+++
@@ -2,18 +2,15 @@
import sys
import logging
from optparse import OptionParser
-from coverage import coverage
from tests.config import configure
logging.disable(logging.CRITICAL)
-def run_tests(options, *test_args):
+def run_tests(*test_args):
from django_nose import NoseTestSuiteRunner
- ... |
3c833053f6da71d1eed6d1a0720a1a8cb1997de7 | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
R... | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
| Python | mit | extertioner/django-localeurl,gonnado/django-localeurl,carljm/django-localeurl | ---
+++
@@ -10,6 +10,7 @@
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
+ 'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
) |
d873380a3ad382ac359ebf41f3f775f585b674f8 | mopidy_gmusic/__init__.py | mopidy_gmusic/__init__.py | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file... | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file... | Use new extension setup() API | Use new extension setup() API
| Python | apache-2.0 | Tilley/mopidy-gmusic,jodal/mopidy-gmusic,mopidy/mopidy-gmusic,jaibot/mopidy-gmusic,hechtus/mopidy-gmusic,elrosti/mopidy-gmusic,jaapz/mopidy-gmusic | ---
+++
@@ -25,6 +25,6 @@
schema['deviceid'] = config.String(optional=True)
return schema
- def get_backend_classes(self):
+ def setup(self, registry):
from .actor import GMusicBackend
- return [GMusicBackend]
+ registry.add('backend', GMusicBackend) |
07135d2e24eab7855c55c9213b0653dec23ccbcf | authomatic/__init__.py | authomatic/__init__.py | # -*- coding: utf-8 -*-
"""
This is the only interface that you should ever need to get a **user** logged in, get
**his/her** info and credentials, deserialize the credentials
and access **his/her protected resources**.
.. autosummary::
:nosignatures:
authomatic.setup
authomatic.login
authomatic.p... | # -*- coding: utf-8 -*-
"""
This is the only interface that you should ever need to get a **user** logged in, get
**his/her** info and credentials, deserialize the credentials
and access **his/her protected resources**.
.. autosummary::
:nosignatures:
authomatic.setup
authomatic.login
authomatic.p... | Correct six local import for python3 compatibility | Correct six local import for python3 compatibility | Python | mit | liorshahverdi/authomatic,authomatic/authomatic,kshitizanand/authomatic,artitj/authomatic,farcaz/authomatic,liorshahverdi/authomatic,scorphus/authomatic,leadbrick/authomatic,erasanimoulika/authomatic,c24b/authomatic,authomatic/authomatic,erasanimoulika/authomatic,dougchestnut/authomatic,scorphus/authomatic,vivek8943/aut... | ---
+++
@@ -18,5 +18,5 @@
"""
-import six
+from . import six
from .core import Authomatic, setup, login, provider_id, access, async_access, credentials, request_elements, backend |
13f4373fc415faba717033f0e8b87a7c5cd83033 | slackclient/_slackrequest.py | slackclient/_slackrequest.py | import json
import requests
import six
class SlackRequest(object):
@staticmethod
def do(token, request="?", post_data=None, domain="slack.com"):
post_data = post_data or {}
for k, v in six.iteritems(post_data):
if not isinstance(v, six.string_types):
post_data[k]... | import json
import requests
import six
class SlackRequest(object):
@staticmethod
def do(token, request="?", post_data=None, domain="slack.com"):
post_data = post_data or {}
for k, v in six.iteritems(post_data):
if not isinstance(v, six.string_types):
post_data[k]... | Add support for files.upload API call. | Add support for files.upload API call.
Closes #64, #88.
| Python | mit | slackapi/python-slackclient,slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient | ---
+++
@@ -16,5 +16,6 @@
url = 'https://{0}/api/{1}'.format(domain, request)
post_data['token'] = token
+ files = {'file': post_data.pop('file')} if 'file' in post_data else None
- return requests.post(url, data=post_data)
+ return requests.post(url, data=post_data, files=f... |
04640beab352f8797d68c33f940e920d2ed9ca6b | nolang/objects/list.py | nolang/objects/list.py | from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(sel... | from nolang.error import AppError
from nolang.objects.root import W_Root
class W_ListObject(W_Root):
def __init__(self, w_items):
self._w_items = w_items
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._w_items]) + ']'
def len(self, space):
return len(sel... | Use is instead of == for types. | Use is instead of == for types.
| Python | mit | fijal/quill | ---
+++
@@ -16,7 +16,7 @@
try:
i = space.int_w(w_index)
except AppError as ae:
- if space.type(ae.w_exception) == space.w_typeerror:
+ if space.type(ae.w_exception) is space.w_typeerror:
raise space.apperr(space.w_typeerror, 'list index must be int... |
0676485054c01abb41b95901c1af0af63fdcb650 | AFQ/utils/volume.py | AFQ/utils/volume.py | import scipy.ndimage as ndim
from skimage.filters import gaussian
def patch_up_roi(roi, sigma=0.5):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
fix that up.
Parameters
----------
roi : 3D... | import scipy.ndimage as ndim
from skimage.filters import gaussian
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
fix that up.
Parameters
----------
... | Truncate ROI-smoothing Gaussian at 2 STD per default. | Truncate ROI-smoothing Gaussian at 2 STD per default.
| Python | bsd-2-clause | yeatmanlab/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ,arokem/pyAFQ | ---
+++
@@ -2,7 +2,7 @@
from skimage.filters import gaussian
-def patch_up_roi(roi, sigma=0.5):
+def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
@@ -16,10... |
11528044c054ac8f1d65c1b64c2e76fbe22dad20 | lpthw/ex24.py | lpthw/ex24.py | print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
poem = """
\t the lovely world
wtih logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print ... | print "Let's practice everything."
print "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
poem = """
\t the lovely world
wtih logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print ... | Change single quote to double quote to make it run -.- | Change single quote to double quote to make it run -.-
| Python | mit | jaredmanning/learning,jaredmanning/learning | ---
+++
@@ -1,5 +1,5 @@
print "Let's practice everything."
-print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
+print "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
poem = """
\t the lovely world |
a24fe6cb58439d295455116574463ebdaf621f2c | mgsv_names.py | mgsv_names.py | import random, os
global adjectives, animals, rares
with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f:
adjectives = f.readlines()
with open(os.path.join(os.path.dirname(__file__), 'animals.txt')) as f:
animals = f.readlines()
with open(os.path.join(os.path.dirname(__file__), 'rares.t... | from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select = 'select {} from {} order by random() limit 1'
_uncommon_select = 'select value from uncommons where key=?'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn... | Replace text files with database access. | Replace text files with database access.
| Python | unlicense | rotated8/mgsv_names | ---
+++
@@ -1,42 +1,28 @@
-import random, os
+from __future__ import unicode_literals, print_function
+import sqlite3, os, random
-global adjectives, animals, rares
-
-with open(os.path.join(os.path.dirname(__file__), 'adjectives.txt')) as f:
- adjectives = f.readlines()
-
-with open(os.path.join(os.path.dirname... |
33903a72a48a6d36792cec0f1fb3a6999c04b486 | blendergltf/exporters/base.py | blendergltf/exporters/base.py | import json
def _is_serializable(value):
try:
json.dumps(value)
return True
except TypeError:
return False
_IGNORED_CUSTOM_PROPS = [
'_RNA_UI',
'cycles',
'cycles_visibility',
]
# pylint: disable=unused-argument
class BaseExporter:
gltf_key = ''
blender_key = ''
... | import json
def _is_serializable(value):
try:
json.dumps(value)
return True
except TypeError:
return False
_IGNORED_CUSTOM_PROPS = [
'_RNA_UI',
'cycles',
'cycles_visibility',
]
# pylint: disable=unused-argument
class BaseExporter:
gltf_key = ''
blender_key = ''
... | Convert custom properties before checking for serializability | Convert custom properties before checking for serializability
| Python | apache-2.0 | Kupoman/blendergltf | ---
+++
@@ -23,10 +23,18 @@
@classmethod
def get_custom_properties(cls, blender_data):
- return {
- k: v.to_list() if hasattr(v, 'to_list') else v for k, v in blender_data.items()
- if k not in _IGNORED_CUSTOM_PROPS and _is_serializable(v)
+ custom_props = {
+ ... |
fc97832d0d96017ac71da125c3a7f29caceface6 | app/mod_budget/model.py | app/mod_budget/model.py | from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Entry(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry.... | from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Entry(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry.... | Make category an optional field for an entry. | Make category an optional field for an entry.
Income entries should not have a category. So the field should
be made optional.
| Python | mit | Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault | ---
+++
@@ -17,4 +17,4 @@
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
- category = db.ReferenceField(Category, required = True)
+ category = db.ReferenceField(Category) |
094cb428316ac0fceb0178d5a507e746550f4509 | bin/task_usage_index.py | bin/task_usage_index.py | #!/usr/bin/env python3
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import glob, json
import numpy as np
import task_usage
def main(data_path, index_path):
count = 0
index = []
for path in sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))):
data = task... | #!/usr/bin/env python3
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import glob, json
import numpy as np
import task_usage
def main(data_path, index_path, report_each=10000):
print('Looking for data in "{}"...'.format(data_path))
paths = sorted(glob.glob('{}/**/*.sqli... | Print progress from the indexing script | Print progress from the indexing script
| Python | mit | learning-on-chip/google-cluster-prediction | ---
+++
@@ -8,21 +8,25 @@
import task_usage
-def main(data_path, index_path):
+def main(data_path, index_path, report_each=10000):
+ print('Looking for data in "{}"...'.format(data_path))
+ paths = sorted(glob.glob('{}/**/*.sqlite3'.format(data_path)))
+ print('Processing {} databases...'.format(len(pat... |
9ca46da9d0cf8b5f4b4a6e9234d7089665df5e8b | chef/tests/__init__.py | chef/tests/__init__.py | import os
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
"""Base cla... | import os
import random
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
... | Add a method to generate random names for testing. | Add a method to generate random names for testing. | Python | apache-2.0 | jarosser06/pychef,dipakvwarade/pychef,coderanger/pychef,jarosser06/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,Scalr/pychef,coderanger/pychef,cread/pychef | ---
+++
@@ -1,4 +1,5 @@
import os
+import random
from unittest2 import TestCase
@@ -17,3 +18,6 @@
super(ChefTestCase, self).setUp()
self.api = test_chef_api
self.api.set_default()
+
+ def random(self, length=8, alphabet='0123456789abcdef'):
+ return ''.join(random.choice(alp... |
86a992dc15482087773f1591752a667a6014ba5d | docker/settings/celery.py | docker/settings/celery.py | from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
pass
CeleryDevSettings.load_settings(__name__)
| from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
# Since we can't properly set CORS on Azurite container
# (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
# trying to fetch ``objects.inv`` from celery container fails because the
# URL ... | Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME | Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME
We can't access docs.dev.readthedocs.io from celery container because
that domain points to 127.0.0.1 and we don't have the storage in that
IP. So, we need to override the AZURE_MEDIA_STORAGE_HOSTNAME in the
celery container to point to the storage.
We should do this... | Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | ---
+++
@@ -2,6 +2,14 @@
class CeleryDevSettings(DockerBaseSettings):
- pass
+ # Since we can't properly set CORS on Azurite container
+ # (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
+ # trying to fetch ``objects.inv`` from celery container fails because the
+ # URL is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.