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 |
|---|---|---|---|---|---|---|---|---|---|---|
391ff28186e40bee9ba7966b739090d67d61b2a6 | APITaxi/models/security.py | APITaxi/models/security.py | # -*- coding: utf8 -*-
from flask.ext.security import UserMixin, RoleMixin
from ..models import db
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id =... | # -*- coding: utf8 -*-
from flask.ext.security import UserMixin, RoleMixin
from ..models import db
from uuid import uuid4
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Mod... | Add apikey when creating a user | Add apikey when creating a user
| Python | agpl-3.0 | odtvince/APITaxi,l-vincent-l/APITaxi,l-vincent-l/APITaxi,openmaraude/APITaxi,odtvince/APITaxi,odtvince/APITaxi,odtvince/APITaxi,openmaraude/APITaxi | ---
+++
@@ -1,6 +1,8 @@
# -*- coding: utf8 -*-
from flask.ext.security import UserMixin, RoleMixin
from ..models import db
+from uuid import uuid4
+
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
@@ -21,6 +23,10 @@
backre... |
8090fa9c072656497ff383e9b76d49af2955e420 | examples/hopv/hopv_graph_conv.py | examples/hopv/hopv_graph_conv.py | """
Script that trains graph-conv models on HOPV dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as... | """
Script that trains graph-conv models on HOPV dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
fr... | Fix GraphConvTensorGraph to GraphConvModel in hopv example | Fix GraphConvTensorGraph to GraphConvModel in hopv example
| Python | mit | Agent007/deepchem,lilleswing/deepchem,lilleswing/deepchem,Agent007/deepchem,peastman/deepchem,miaecle/deepchem,peastman/deepchem,ktaneishi/deepchem,miaecle/deepchem,Agent007/deepchem,deepchem/deepchem,ktaneishi/deepchem,deepchem/deepchem,ktaneishi/deepchem,miaecle/deepchem,lilleswing/deepchem | ---
+++
@@ -7,7 +7,7 @@
import numpy as np
-from models import GraphConvTensorGraph
+from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
@@ -30,7 +30,7 @@
n_feat = 75
# Batch size of models
batch_size = 50
-model = GraphConvTensorGraph(
+model = GraphConvModel(
len(hopv_task... |
66f06164a5654f2925fb16a1ce28638fd57e3a9e | issue_tracker/accounts/urls.py | issue_tracker/accounts/urls.py | from django.conf.urls.defaults import *
from django.contrib.auth.views import logout_then_login, login
from django.contrib.auth.forms import AuthenticationForm
urlpatterns = patterns('',
(r'^login/$', login, {}, 'login' ),
(r'^logout/$', logout_then_login, {}, 'logout'),
)
| from django.conf.urls.defaults import *
from django.contrib.auth.views import logout_then_login, login
from accounts.views import register
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
urlpatterns = patterns('',
(r'^register/$', register, {}, 'regis... | Add url mapping to register. | Add url mapping to register.
| Python | mit | hfrequency/django-issue-tracker | ---
+++
@@ -1,8 +1,11 @@
from django.conf.urls.defaults import *
from django.contrib.auth.views import logout_then_login, login
+from accounts.views import register
+from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
urlpatterns = patterns('',
+ (r... |
e0d510b51f44b421696958660f2ca32ee41413bd | click/globals.py | click/globals.py | from threading import local
_local = local()
def get_current_context(silent=False):
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
prima... | from threading import local
_local = local()
def get_current_context(silent=False):
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
prima... | Fix get_current_context typo in docstring | Fix get_current_context typo in docstring
| Python | bsd-3-clause | pallets/click,mitsuhiko/click | ---
+++
@@ -15,7 +15,7 @@
.. versionadded:: 5.0
- :param silent: is set to `True` the return value is `None` if no context
+ :param silent: if set to `True` the return value is `None` if no context
is available. The default behavior is to raise a
:exc:`RuntimeEr... |
1ad453f6d01d4007662fa63d59508d27bac029d5 | keras/utils/model_utils.py | keras/utils/model_utils.py | from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to ... | from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to ... | Add check to print_layer_shapes to fail explicitely on model used connected to other models. | Add check to print_layer_shapes to fail explicitely on model used connected to other models. | Python | apache-2.0 | asampat3090/keras,xurantju/keras,keras-team/keras,cheng6076/keras,rudaoshi/keras,bottler/keras,ashhher3/keras,wxs/keras,nzer0/keras,rodrigob/keras,pthaike/keras,EderSantana/keras,zxsted/keras,abayowbo/keras,zxytim/keras,danielforsyth/keras,hhaoyan/keras,jalexvig/keras,chenych11/keras,brainwater/keras,amy12xx/keras,davi... | ---
+++
@@ -11,6 +11,16 @@
model: An instance of models.Model
input_shape: The shape of the input you will provide to the model.
"""
+ # This is to handle the case where a model has been connected to a previous
+ # layer (and therefore get_input would recurse into previous layer's
+ # ... |
fb1422c22e570da21279edee0ea79605e74f7a92 | crispy/__init__.py | crispy/__init__.py | import logging
logging.basicConfig(level=logging.WARNING)
| import logging
# These are required to activate the cx_Freeze hooks
import matplotlib
import matplotlib.backends.backend_qt5agg
import PyQt5.QtPrintSupport
logging.basicConfig(level=logging.WARNING)
| Add imports imports to trigger cx_Freeze hooks | Add imports imports to trigger cx_Freeze hooks
| Python | mit | mretegan/crispy,mretegan/crispy | ---
+++
@@ -1,3 +1,8 @@
import logging
+# These are required to activate the cx_Freeze hooks
+import matplotlib
+import matplotlib.backends.backend_qt5agg
+import PyQt5.QtPrintSupport
+
logging.basicConfig(level=logging.WARNING) |
d6a03fad6c9280981ae3beee24de89bd6361bcc9 | dumbrepl.py | dumbrepl.py | if __name__ == "__main__":
import pycket.test.testhelper as th
th.dumb_repl()
| if __name__ == "__main__":
import pycket.values
import pycket.config
from pycket.env import w_global_config
#w_global_config.set_linklet_mode_off()
import pycket.test.testhelper as th
th.dumb_repl()
| Make sure things are loaded right. | Make sure things are loaded right.
| Python | mit | samth/pycket,pycket/pycket,pycket/pycket,samth/pycket,samth/pycket,pycket/pycket | ---
+++
@@ -1,4 +1,8 @@
if __name__ == "__main__":
+ import pycket.values
+ import pycket.config
+ from pycket.env import w_global_config
+ #w_global_config.set_linklet_mode_off()
import pycket.test.testhelper as th
th.dumb_repl()
|
bd69ad0bf57876cef01cc8f7cdce49a301eb2444 | bin/remotePush.py | bin/remotePush.py | import json,httplib
config_data = json.load(open('conf/net/ext_service/parse.json'))
silent_push_msg = {
"where": {
"deviceType": "ios"
},
"data": {
# "alert": "The Mets scored! The game is now tied 1-1.",
"content-available": 1,
"sound": "",
}
}
parse_headers = {
"X-Parse-Applicat... | import json,httplib
import sys
config_data = json.load(open('conf/net/ext_service/parse.json'))
interval = sys.argv[1]
print "pushing for interval %s" % interval
silent_push_msg = {
"where": {
"deviceType": "ios"
},
"channels": [
interval
],
"data": {
# "alert": "The Mets scored! The ga... | Make the remote push script take in the interval as an argument | Make the remote push script take in the interval as an argument
We will use the interval as the channel
| Python | bsd-3-clause | shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-ser... | ---
+++
@@ -1,11 +1,18 @@
import json,httplib
+import sys
config_data = json.load(open('conf/net/ext_service/parse.json'))
+
+interval = sys.argv[1]
+print "pushing for interval %s" % interval
silent_push_msg = {
"where": {
"deviceType": "ios"
},
+ "channels": [
+ interval
+ ],
"data"... |
3794fe611e5fbbe55506a7d2e59b2f3f872d8733 | backend/controllers/file_controller.py | backend/controllers/file_controller.py | import os
from werkzeug.utils import secure_filename
import config
from flask_restful import Resource
from flask import request, abort
def allowed_file(filename):
return ('.' in filename and
filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS)
class File(Resource):
def post(self):
... | import os
from werkzeug.utils import secure_filename
import config
from flask_restful import Resource
from flask import request, abort
def allowed_file(filename):
return ('.' in filename and
filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS)
class File(Resource):
def post(self):
... | Change status codes and messages | Change status codes and messages
| Python | apache-2.0 | googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer | ---
+++
@@ -13,16 +13,18 @@
class File(Resource):
def post(self):
if 'uploaded_data' not in request.files:
- abort(500)
+ abort(400, 'Uploaded_data is required for the request')
file = request.files['uploaded_data']
if file.filename == '':
- abort(500)... |
123875153e81253a44d0e8b2d8de5abee195362a | backend/shmitter/tweets/serializers.py | backend/shmitter/tweets/serializers.py | from rest_framework import serializers
from shmitter.likes import services as likes_services
from .models import Tweet
from . import services as tweets_services
class TweetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
is_fan = serializers.SerializerMetho... | from rest_framework import serializers
from shmitter.likes import services as likes_services
from .models import Tweet
from . import services as tweets_services
class TweetSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
is_fan = serializers.SerializerMetho... | Add total retweets to the serializer | Add total retweets to the serializer
| Python | mit | apirobot/shmitter,apirobot/shmitter,apirobot/shmitter | ---
+++
@@ -20,6 +20,7 @@
'is_fan',
'is_retweeted',
'total_likes',
+ 'total_retweets',
'created',
)
|
28a4f4ab9d6b7c3ea14d48c002273acfe05d7246 | bumblebee/util.py | bumblebee/util.py | import shlex
import exceptions
import subprocess
def bytefmt(num):
for unit in [ "", "Ki", "Mi", "Gi" ]:
if num < 1024.0:
return "{:.2f}{}B".format(num, unit)
num /= 1024.0
return "{:05.2f%}{}GiB".format(num)
def durationfmt(duration):
minutes, seconds = divmod(duration, 60)
... | import shlex
import subprocess
try:
from exceptions import RuntimeError
except ImportError:
# Python3 doesn't require this anymore
pass
def bytefmt(num):
for unit in [ "", "Ki", "Mi", "Gi" ]:
if num < 1024.0:
return "{:.2f}{}B".format(num, unit)
num /= 1024.0
return "{:0... | Fix import error for Python3 | [core] Fix import error for Python3
Import exceptions module only for Python2.
fixes #22
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -1,6 +1,10 @@
import shlex
-import exceptions
import subprocess
+try:
+ from exceptions import RuntimeError
+except ImportError:
+ # Python3 doesn't require this anymore
+ pass
def bytefmt(num):
for unit in [ "", "Ki", "Mi", "Gi" ]:
@@ -23,4 +27,4 @@
out = p.communicate()
if ... |
81b7089633b9d43b05566a1e23f93fb59678fe1e | plugins/unicode_plugin.py | plugins/unicode_plugin.py | import string
import textwrap
import binascii
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class DecodeHexPlugin(BasePlugin):
short_description = 'Decode hex string to encodings:'
default = True
description = textwrap.dedent('''
This plugin tries to ... | import string
import textwrap
import binascii
import unicodedata
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class DecodeHexPlugin(BasePlugin):
short_description = 'Decode hex string to encodings:'
default = True
description = textwrap.dedent('''
Th... | Remove control characters from printed string to prevent terminal breakage | Remove control characters from printed string to prevent terminal breakage
| Python | mit | Sakartu/stringinfo | ---
+++
@@ -1,6 +1,7 @@
import string
import textwrap
import binascii
+import unicodedata
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
@@ -11,7 +12,8 @@
short_description = 'Decode hex string to encodings:'
default = True
description = textwrap.dedent('''
- This ... |
e999e9b9480d31c45bf13882081e36bd7e2c4c63 | download.py | download.py | #!/usr/bin/env python
import data
s = data.Session()
for video in s.query(data.Video):
print u'+++ Downloading {} +++'.format(video.title)
video.download()
del s
| #!/usr/bin/env python
import data
s = data.Session()
for video in s.query(data.Video):
print u'+++ Downloading "{}" +++'.format(video.title)
video.download()
del s
| Print video title in quotes | Print video title in quotes
| Python | mit | drkitty/metatube,drkitty/metatube | ---
+++
@@ -5,6 +5,6 @@
s = data.Session()
for video in s.query(data.Video):
- print u'+++ Downloading {} +++'.format(video.title)
+ print u'+++ Downloading "{}" +++'.format(video.title)
video.download()
del s |
c0596310d9281fc07d4db6e6fd2ed8433335edb9 | examples/build_examples.py | examples/build_examples.py | #!/usr/bin/env python
import glob
import os
import platform
import subprocess
import sys
cx_path = sys.argv[1] if len(sys.argv) > 1 else "cx"
os.chdir(os.path.dirname(__file__))
for file in glob.glob("*.cx"):
if platform.system() == "Windows" and file == "tree.cx":
continue
extension = ".out" if pl... | #!/usr/bin/env python
import glob
import os
import platform
import subprocess
import sys
cx_path = sys.argv[1] if len(sys.argv) > 1 else "cx"
os.chdir(os.path.dirname(__file__))
for file in glob.glob("*.cx"):
if platform.system() == "Windows" and file == "tree.cx":
continue
extension = ".out" if pl... | Use -Werror for code examples | Use -Werror for code examples
| Python | mit | delta-lang/delta,delta-lang/delta,delta-lang/delta,delta-lang/delta | ---
+++
@@ -16,7 +16,7 @@
extension = ".out" if platform.system() != "Windows" else ".exe"
output = os.path.splitext(file)[0] + extension
- exit_status = subprocess.call([cx_path, file, "-o", output])
+ exit_status = subprocess.call([cx_path, file, "-o", output, "-Werror"])
if exit_status != 0:... |
19326b0b96e053c4b4fab402a379a03c39fbe46d | apps/homepage/templatetags/homepage_tags.py | apps/homepage/templatetags/homepage_tags.py | from django import template
from homepage.models import Tab
register = template.Library()
@register.tag(name="get_tabs")
def get_tabs(parser, token):
return GetElementNode()
class GetElementNode(template.Node):
def __init__(self):
pass
def render(self, cont... | from django import template
from homepage.models import Tab
register = template.Library()
@register.tag(name="get_tabs")
def get_tabs(parser, token):
return GetElementNode()
class GetElementNode(template.Node):
def __init__(self):
pass
def render(self, cont... | Reduce queries on all pages by using select_related in the get_tabs template tag. | Reduce queries on all pages by using select_related in the get_tabs template tag.
| Python | mit | cartwheelweb/packaginator,nanuxbe/djangopackages,miketheman/opencomparison,audreyr/opencomparison,audreyr/opencomparison,cartwheelweb/packaginator,QLGu/djangopackages,pydanny/djangopackages,cartwheelweb/packaginator,benracine/opencomparison,nanuxbe/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djang... | ---
+++
@@ -15,5 +15,5 @@
pass
def render(self, context):
- context['tabs'] = Tab.objects.all()
+ context['tabs'] = Tab.objects.all().select_related('grid')
return '' |
6b0049978f2a7e59146abbc9b6a265061bbe00c4 | conda_verify/errors.py | conda_verify/errors.py | from collections import namedtuple
class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])):
"""Error class creates error codes to be shown to the user."""
def __repr__(self):
"""Override namedtuple's __repr__ so that error codes are readable."""
return '{}:{}: {} {}' .for... | Add Error class as base for error codes | Add Error class as base for error codes
Add docstrings to error class
| Python | bsd-3-clause | mandeep/conda-verify | ---
+++
@@ -0,0 +1,9 @@
+from collections import namedtuple
+
+
+class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])):
+ """Error class creates error codes to be shown to the user."""
+
+ def __repr__(self):
+ """Override namedtuple's __repr__ so that error codes are readable."""
... | |
5aff8defb8baf83176ea861b03de04a9d6ac8a31 | bundles/views.py | bundles/views.py | from django.views.generic import DetailView, ListView
from rest_framework import filters, generics, permissions
from rest_framework.response import Response
from . import models, serializers
class BundleList(ListView):
model = models.Bundle
context_object_name = 'bundles'
paginate_by = 25
class Bundle... | from django.views.generic import DetailView, ListView
from rest_framework import filters, generics, permissions
from rest_framework.response import Response
from . import models, serializers
class BundleList(ListView):
model = models.Bundle
context_object_name = 'bundles'
paginate_by = 25
class Bundle... | Make bundle view accessible to anyone | Make bundle view accessible to anyone
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,lutris/website | ---
+++
@@ -19,7 +19,6 @@
class BundleView(generics.RetrieveAPIView):
serializer_class = serializers.BundleSerializer
- permission_classes = [permissions.IsAuthenticated]
def get(self, request, slug):
try: |
b3391187cb87ae33d4b8dd6e55f5edfdb695ea53 | mapbox_vector_tile/__init__.py | mapbox_vector_tile/__init__.py | from . import encoder
from . import decoder
def decode(tile, y_coord_down=False):
vector_tile = decoder.TileData()
message = vector_tile.getMessage(tile, y_coord_down)
return message
def encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096,
on_invalid_geometry=None, round_fn=... | from . import encoder
from . import decoder
# Enable Shapely "speedups" if available
# http://toblerity.org/shapely/manual.html#performance
from shapely import speedups
if speedups.available:
speedups.enable()
def decode(tile, y_coord_down=False):
vector_tile = decoder.TileData()
message = vector_tile.g... | Enable Shapely speedups when available. | Enable Shapely speedups when available.
http://toblerity.org/shapely/manual.html#performance
| Python | mit | mapzen/mapbox-vector-tile | ---
+++
@@ -1,5 +1,12 @@
from . import encoder
from . import decoder
+
+
+# Enable Shapely "speedups" if available
+# http://toblerity.org/shapely/manual.html#performance
+from shapely import speedups
+if speedups.available:
+ speedups.enable()
def decode(tile, y_coord_down=False): |
e53e214b97a9a4c7ad2dbca88b01798dcc614b6a | auth0/v2/authentication/social.py | auth0/v2/authentication/social.py | from .base import AuthenticationBase
class Social(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def login(self, client_id, access_token, connection):
"""Login using a social provider's access token
Given the social provider's access_token and the connection s... | from .base import AuthenticationBase
class Social(AuthenticationBase):
"""Social provider's endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def login(self, client_id, access_token, connection):
... | Add class docstring to Social | Add class docstring to Social
| Python | mit | auth0/auth0-python,auth0/auth0-python | ---
+++
@@ -2,6 +2,12 @@
class Social(AuthenticationBase):
+
+ """Social provider's endpoints.
+
+ Args:
+ domain (str): Your auth0 domain (e.g: username.auth0.com)
+ """
def __init__(self, domain):
self.domain = domain |
1608134ea633c0fe8cd4636b11dc5a931d02e024 | intercom.py | intercom.py | import configparser
import time
import RPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.send_in... | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.sen... | Change to rpio and add clean | Change to rpio and add clean
| Python | mit | pkronstrom/intercom | ---
+++
@@ -1,6 +1,6 @@
import configparser
import time
-import RPIO as GPIO
+import RPi.GPIO as GPIO
from client import MumbleClient
@@ -12,6 +12,7 @@
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.send_input = False
+
if config['general'... |
05e568571c2f6891ed7be6198b8cf5e4e540d674 | dev_tools/run_tests.py | dev_tools/run_tests.py | #!/usr/bin/env python3
"""Run tests under a consistent environment...
Whether run from the terminal, in CI or from the editor this file makes sure
the tests are run in a consistent environment.
"""
#------------------------------------------------------------------------------
# Py2C - A Python to C++ compiler
# Copy... | #!/usr/bin/env python3
"""Run tests under a consistent environment...
Whether run from the terminal, in CI or from the editor this file makes sure
the tests are run in a consistent environment.
"""
#------------------------------------------------------------------------------
# Py2C - A Python to C++ compiler
# Copy... | Move all imports to top-of-module, don't hide cleanup output. | [RUN_TESTS] Move all imports to top-of-module, don't hide cleanup output.
| Python | bsd-3-clause | pradyunsg/Py2C,pradyunsg/Py2C | ---
+++
@@ -10,18 +10,19 @@
# Copyright (C) 2014 Pradyun S. Gedam
#------------------------------------------------------------------------------
+# Local modules
+import cleanup
+
+# Standard library
import sys
from os.path import join, realpath, dirname
-
-# Local modules
-import cleanup
-cleanup.REMOVE_GENER... |
0fe30bb04e9b3d981cd1f6264485d98ca56a2fb8 | events/migrations/0035_add_n_events_to_keyword.py | events/migrations/0035_add_n_events_to_keyword.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclu... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclu... | Add logging to keyword data migration | Add logging to keyword data migration
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents | ---
+++
@@ -10,6 +10,7 @@
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None):
n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count()
if n_events != keyword.n_events:
+ print("Updating event number for " + ... |
887597d31dec7fe1f49402e44691c1e745d22968 | cellcounter/wsgi.py | cellcounter/wsgi.py | """
WSGI config for cellcounter project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... | """
WSGI config for cellcounter project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... | Improve WSGI file for apache deployment/database configuration management | Improve WSGI file for apache deployment/database configuration management
| Python | mit | cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,oghm2/hackdayoxford,oghm2/hackdayoxford,haematologic/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter | ---
+++
@@ -14,14 +14,22 @@
"""
import os
+import site
+from distutils.sysconfig import get_python_lib
+
+#ensure the venv is being loaded correctly
+site.addsitedir(get_python_lib())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cellcounter.settings")
-# This application object is used by any WSGI server... |
25712b9c94062f41c50a8611c5b7069bde7e1c8f | ibmcnx/cnx/VersionStamp.py | ibmcnx/cnx/VersionStamp.py | ######
# Set the Version Stamp to actual time and date
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
print "\nSet Version Stamp in LotusConnec... | ######
# Set the Version Stamp to actual time and date
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
import ibmcnx.functions
print "\nSet Ver... | Add option to get temppath from properties file | Add option to get temppath from properties file
| Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -11,9 +11,15 @@
# License: Apache 2.0
#
+import ibmcnx.functions
+
print "\nSet Version Stamp in LotusConnections-config.xml to actual Date and Time\n"
-path = raw_input( "Path and Folder where config is temporarily stored: " )
+# Check properties if temppath is defined
+if ( ibmcnx.functions... |
e5656674eab83f7005c70d901187fd89027efeba | allaccess/management/commands/migrate_social_providers.py | allaccess/management/commands/migrate_social_providers.py | from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand, CommandError
from allaccess.models import Provider
class Command(NoArgsCommand):
"Convert existing providers from django-social-auth to django-all-access."
def handle_noargs(self, **options):
verbosity =... | from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand, CommandError
from allaccess.models import Provider
class Command(NoArgsCommand):
"Convert existing providers from django-social-auth to django-all-access."
def handle_noargs(self, **options):
verbosity =... | Remove force_load which was added in later versions. | Remove force_load which was added in later versions.
| Python | bsd-2-clause | iXioN/django-all-access,vyscond/django-all-access,dpoirier/django-all-access,dpoirier/django-all-access,mlavin/django-all-access,iXioN/django-all-access,vyscond/django-all-access,mlavin/django-all-access | ---
+++
@@ -14,7 +14,7 @@
from social_auth.backends import get_backends, BaseOAuth
except ImportError: # pragma: no cover
raise CommandError("django-social-auth is not installed.")
- for name, backend in get_backends(force_load=True).items():
+ for name, backend in get... |
3faf3a9debc0fad175ca032f3eb0880defbd0cdb | akaudit/clidriver.py | akaudit/clidriver.py | #!/usr/bin/env python
import sys
import argparse
from akaudit.audit import Auditer
def main(argv = sys.argv, log = sys.stderr):
parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log', default='info... | #!/usr/bin/env python
import sys
import argparse
from akaudit.audit import Auditer
def main(argv = sys.argv, log = sys.stderr):
parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log', default='info... | Add argument option for --interactive. | Add argument option for --interactive.
| Python | apache-2.0 | flaccid/akaudit | ---
+++
@@ -7,7 +7,9 @@
def main(argv = sys.argv, log = sys.stderr):
parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log', default='info', help='Log level')
+ parser.add_argument('-i', '--inte... |
766a2fa8a1256946af9bc3b20b98a9a6ac7e1080 | amaranth/__init__.py | amaranth/__init__.py | """This is the top-level amaranth module init file.
The only current use of this class is to define common constants.
"""
LOW_CALORIE_THRESHOLD = 100
HIGH_CALORIE_THRESHOLD = 500
| """This is the top-level amaranth module init file.
The only current use of this class is to define common constants.
"""
LOW_CALORIE_THRESHOLD = 100
HIGH_CALORIE_THRESHOLD = 300
| Change high calorie threshold to 300 | Change high calorie threshold to 300
| Python | apache-2.0 | googleinterns/amaranth,googleinterns/amaranth | ---
+++
@@ -4,4 +4,4 @@
"""
LOW_CALORIE_THRESHOLD = 100
-HIGH_CALORIE_THRESHOLD = 500
+HIGH_CALORIE_THRESHOLD = 300 |
572a84ae4fe7ce464fe66b6462a80b09b20f8f1c | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
| from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cos... | Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano | Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano
| Python | agpl-3.0 | NightKev/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Meerkov/fireplace,jleclanche/fireplace,amw2104/fireplace,butozerca/fireplace,Ragowit/fireplace,liujimj/fi... | ---
+++
@@ -9,3 +9,24 @@
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
+
+
+# Piloted Sky Golem
+class GVG_105:
+ def deathrattle(self):
+ return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))]
+
+
+# Junkbot
+class ... |
1d6984d31aaa87b5ed781e188b8b42221602cd3f | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
pytest_plugins = 'pytester'
| # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | Add warning on running repository's tests with pytest-testdox installed | Add warning on running repository's tests with pytest-testdox installed
Fix #13
| Python | mit | renanivo/pytest-testdox | ---
+++
@@ -1,2 +1,23 @@
# -*- coding: utf-8 -*-
+import os
+import warnings
+
+import pytest
+
pytest_plugins = 'pytester'
+
+
+@pytest.fixture(scope='session', autouse=True)
+def verify_target_path():
+ import pytest_testdox
+
+ current_path_root = os.path.dirname(
+ os.path.dirname(os.path.realpath(... |
dc1cedc1720886dcc3c3bd3da02c7aff58e5eb90 | tests/runTests.py | tests/runTests.py | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... | Make test runner work with blank mysql password | Make test runner work with blank mysql password
| Python | mit | HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite... | ---
+++
@@ -15,7 +15,8 @@
# Website tests
print("Beginning website backend tests")
-os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
+passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
+os.s... |
a69e8d0d179f12fd42eadd85eca8e0c968d67c91 | tests/runTests.py | tests/runTests.py | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website te... | Make test runner work with blank mysql password | Make test runner work with blank mysql password
| Python | mit | HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChal... | ---
+++
@@ -15,7 +15,8 @@
# Website tests
print("Beginning website backend tests")
-os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
+passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
+os.s... |
030de1eccb4819c175b2d8d43dc16c878bb689c9 | engines/empy_engine.py | engines/empy_engine.py | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import em
from . import Engine
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, **kwargs):
"""Initialize empy template."""
super(... | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, bas... | Add base directory capability to empy engine. | Add base directory capability to empy engine.
| Python | mit | blubberdiblub/eztemplate | ---
+++
@@ -3,10 +3,32 @@
from __future__ import print_function
+import os.path
import em
from . import Engine
+
+
+class SubsystemWrapper(em.Subsystem):
+
+ """Wrap EmPy's Subsystem class.
+
+ Allows to open files relative to a base directory.
+ """
+
+ def __init__(self, basedir=None, **kwarg... |
7172962abf0d5d5aad02c632944ed8cb33ca9bae | django/books/admin.py | django/books/admin.py | from django.contrib import admin
from .models import Author, Book, Note, Tag, Section
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ['name', 'goodreads_id']
prepopulated_fields = {'slug': ('name',), }
@admin.register(Section)
class SectionAdmin(admin.ModelAdmin):
list_disp... | from django.contrib import admin
from .models import Author, Book, Note, Tag, Section
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ['name', 'goodreads_id']
prepopulated_fields = {'slug': ('name',), }
search_fields = ['name']
@admin.register(Section)
class SectionAdmin(adm... | Allow searching by name in AuthorAdmin | Allow searching by name in AuthorAdmin
| Python | mit | dellsystem/bookmarker,dellsystem/bookmarker,dellsystem/bookmarker | ---
+++
@@ -7,6 +7,7 @@
class AuthorAdmin(admin.ModelAdmin):
list_display = ['name', 'goodreads_id']
prepopulated_fields = {'slug': ('name',), }
+ search_fields = ['name']
@admin.register(Section) |
23f404b61f2c9b89bb631ad0e60edf4416500f28 | django_split/utils.py | django_split/utils.py | def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
| from __future__ import division
import scipy
import scipy.stats
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return a... | Add utilities for computing metrics | Add utilities for computing metrics
| Python | mit | prophile/django_split | ---
+++
@@ -1,3 +1,8 @@
+from __future__ import division
+
+import scipy
+import scipy.stats
+
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
@@ -9,3 +14,19 @@
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
+
+def compute_no... |
dd269cea5623450c3c608d10b8ddce1ae6c9e84a | project_one/project_one.py | project_one/project_one.py | # System imports first
import sys
# Module (local) imports
from import_data import import_data
from process import process_data, normalize, rotate_data
from output import plot_data
def main(argv=None):
""" Main function, executed when running 'project_one'. """
# Read the data
data = import_data('data.tx... | # System imports first
import sys
import argparse
# Module (local) imports
from import_data import import_data
from process import process_data, normalize, rotate_data
from output import plot_data
def main(argv=None):
""" Main function, executed when running 'project_one'. """
# Parse command-line arguments,... | Use command-line argument to specify data. | Use command-line argument to specify data. | Python | bsd-3-clause | dokterbob/slf-project-one | ---
+++
@@ -1,5 +1,6 @@
# System imports first
import sys
+import argparse
# Module (local) imports
from import_data import import_data
@@ -9,8 +10,17 @@
def main(argv=None):
""" Main function, executed when running 'project_one'. """
+ # Parse command-line arguments, this allows the input to be
+ ... |
2c05dba69c838cfd3808d8e03dbea3cc56d4f6d2 | pyinfra_kubernetes/__init__.py | pyinfra_kubernetes/__init__.py | from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
def deploy_kubernetes_master(etcd_nodes):
# Install server components
install_kubernetes(components=(
'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',
))
# Configu... | from pyinfra.api import deploy
from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
@deploy('Deploy Kubernetes master')
def deploy_kubernetes_master(
state, host,
etcd_nodes,
):
# Install server components
install_kubernetes(components=(
... | Make helper functions full `@deploy`s so they support global pyinfra kwargs. | Make helper functions full `@deploy`s so they support global pyinfra kwargs.
| Python | mit | EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes | ---
+++
@@ -1,8 +1,14 @@
+from pyinfra.api import deploy
+
from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
-def deploy_kubernetes_master(etcd_nodes):
+@deploy('Deploy Kubernetes master')
+def deploy_kubernetes_master(
+ state, host,
+ etc... |
de3f84934d86e48bf89822828df3eb9c3bd8e1e1 | test/test_examples.py | test/test_examples.py | import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
... | import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
... | Test suite should pass even if example dependencies are not present | Test suite should pass even if example dependencies are not present
| Python | mit | ryoqun/mitmproxy,ryoqun/mitmproxy,xaxa89/mitmproxy,guiquanz/mitmproxy,ccccccccccc/mitmproxy,ADemonisis/mitmproxy,jpic/mitmproxy,pombredanne/mitmproxy,noikiy/mitmproxy,xaxa89/mitmproxy,fimad/mitmproxy,onlywade/mitmproxy,dxq-git/mitmproxy,inscriptionweb/mitmproxy,sethp-jive/mitmproxy,ParthGanatra/mitmproxy,cortesi/mitmpr... | ---
+++
@@ -2,6 +2,7 @@
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
+
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
@@ -16,5 +17,10 @@
f += " foo" # one argument required
if "modify_response_body" in f:
... |
92d7a3cf2ec3ae669fab17906b10b784525a134a | pyinduct/tests/__init__.py | pyinduct/tests/__init__.py | # -*- coding: utf-8 -*-
import sys
if any([arg in {'discover', 'setup.py', 'test'} for arg in sys.argv]):
test_examples = True
test_all_examples = False
show_plots = False
elif any(['sphinx-build' in arg for arg in sys.argv]):
test_examples = False
test_all_examples = False
show_plots = False
e... | # -*- coding: utf-8 -*-
import sys
if any([arg in {'discover', 'setup.py', 'test'} for arg in sys.argv]):
test_examples = True
test_all_examples = False
show_plots = False
elif any(['sphinx-build' in arg for arg in sys.argv]):
test_examples = False
test_all_examples = False
show_plots = False
e... | Revert commit of local changes | Revert commit of local changes
| Python | bsd-3-clause | cklb/pyinduct,riemarc/pyinduct,pyinduct/pyinduct | ---
+++
@@ -16,4 +16,4 @@
# Do not want to see plots or test all examples while test run?
# Then force it and uncomment the respective line:
# test_all_examples = False
- show_plots = False
+ # show_plots = False |
c55243d591793a9213d27126a3c240bb47c5f82b | cartoframes/core/cartodataframe.py | cartoframes/core/cartodataframe.py | from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
super(CartoDataFrame, self).__init__(*args, **kwargs)
@staticmethod
def from_carto(*args, **kwargs):
from ..io.car... | from geopandas import GeoDataFrame
from ..utils.geom_utils import generate_index, generate_geometry
class CartoDataFrame(GeoDataFrame):
def __init__(self, *args, **kwargs):
super(CartoDataFrame, self).__init__(*args, **kwargs)
@staticmethod
def from_carto(*args, **kwargs):
from ..io.car... | Rename visualize to viz in CDF | Rename visualize to viz in CDF
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | ---
+++
@@ -34,8 +34,6 @@
generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat)
return self
- def visualize(self, *args, **kwargs):
+ def viz(self, *args, **kwargs):
from ..viz import Map, Layer
return Map(Layer(self, *args, **kwargs))
-
- viz = vi... |
a0a98f374a66093ad3c35a2e185ac9b48d8b3f2d | lib/reinteract/__init__.py | lib/reinteract/__init__.py | import gobject
# https://bugzilla.gnome.org/show_bug.cgi?id=644039
def fixed_default_setter(self, instance, value):
setattr(instance, '_property_helper_'+self.name, value)
def fixed_default_getter(self, instance):
return getattr(instance, '_property_helper_'+self.name, self.default)
def monkey_patch_gobject... | Work around leak in older pygobject | Work around leak in older pygobject
With older pygobject, any use of the default getter/setters
generated by gobject.property() would leak. If we detect this
is the case, monkey patch in the fixed version of the default
getters/setters.
(See https://bugzilla.gnome.org/show_bug.cgi?id=644039)
| Python | bsd-2-clause | alexey4petrov/reinteract,alexey4petrov/reinteract,alexey4petrov/reinteract | ---
+++
@@ -0,0 +1,16 @@
+import gobject
+
+# https://bugzilla.gnome.org/show_bug.cgi?id=644039
+def fixed_default_setter(self, instance, value):
+ setattr(instance, '_property_helper_'+self.name, value)
+
+def fixed_default_getter(self, instance):
+ return getattr(instance, '_property_helper_'+self.name, self... | |
a2aa2ea452c7fb2f3a83a13f000a51223cb3d13f | client/sources/doctest/__init__.py | client/sources/doctest/__init__.py | from client.sources.common import importing
from client.sources.doctest import models
import logging
import os
log = logging.getLogger(__name__)
def load(file, name, args):
"""Loads doctests from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
... | from client.sources.common import importing
from client.sources.doctest import models
import logging
import os
log = logging.getLogger(__name__)
def load(file, name, args):
"""Loads doctests from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
... | Add a few exception strings | Add a few exception strings
| Python | apache-2.0 | jackzhao-mj/ok-client,Cal-CS-61A-Staff/ok-client,jathak/ok-client | ---
+++
@@ -18,12 +18,12 @@
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import doctests from {}'.format(file))
# TODO(albert): raise appropriate error
- raise Exception
+ raise Exception('Cannot import doctests from {}'.format(file))
module = i... |
fc5ae93998045f340e44e267f409a7bdf534c756 | website_slides/__init__.py | website_slides/__init__.py | # -*- coding: utf-8 -*-
# ##############################################################################
#
# Odoo, Open Source Management Solution
# Copyright (C) 2014-TODAY Odoo SA (<https://www.odoo.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import controllers
import models
| Use global LICENSE/COPYRIGHT files, remove boilerplate text | [LEGAL] Use global LICENSE/COPYRIGHT files, remove boilerplate text
- Preserved explicit 3rd-party copyright notices
- Explicit boilerplate should not be necessary - copyright law applies
automatically in all countries thanks to Berne Convention + WTO rules,
and a reference to the applicable license is clear enoug... | Python | agpl-3.0 | Endika/website,Yajo/website,kaerdsar/website,brain-tec/website,kaerdsar/website,gfcapalbo/website,pedrobaeza/website,Antiun/website,open-synergy/website,LasLabs/website,open-synergy/website,brain-tec/website,nuobit/website,acsone/website,nuobit/website,xpansa/website,acsone/website,Antiun/website,Antiun/website,pedroba... | ---
+++
@@ -1,23 +1,5 @@
# -*- coding: utf-8 -*-
-# ##############################################################################
-#
-# Odoo, Open Source Management Solution
-# Copyright (C) 2014-TODAY Odoo SA (<https://www.odoo.com>).
-#
-# This program is free software: you can redistribute it and/or mod... |
ee6f71ba0e548fdb08a3f1b065cd081b2431caa6 | lc0222_count_complete_tree_nodes.py | lc0222_count_complete_tree_nodes.py | """Leetcode 222. Count Complete Tree Nodes
Medium
URL: https://leetcode.com/problems/count-complete-tree-nodes/
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last,
is completely filled, a... | """Leetcode 222. Count Complete Tree Nodes
Medium
URL: https://leetcode.com/problems/count-complete-tree-nodes/
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last,
is completely filled, a... | Complete preorder recur sol w/ time/space complexity | Complete preorder recur sol w/ time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -30,17 +30,43 @@
self.right = None
-class Solution(object):
+class SolutionPreorderRecur(object):
+ def _preorder(self, root):
+ if not root:
+ return None
+
+ self.n_nodes += 1
+ self._preorder(root.left)
+ self._preorder(root.right)
+
de... |
8c819a1cb9df54c00b7246a07e2ba832b763876d | stream_django/templatetags/activity_tags.py | stream_django/templatetags/activity_tags.py | from django import template
from django.template import Context, loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_no... | from django import template
from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
logger = logging.getLogger(__name__)
register = template.Library()
LOG = 'warn'
IGNORE = 'ignore'
FAIL = 'fail'
missing_data_policies = [LOG, IGNORE, FAIL]
def handle_not_enriche... | Use dict as a context object for Django 1.11 compatibility | Use dict as a context object for Django 1.11 compatibility
Django’s template rendering in 1.11 needs a dictionary as the context
instead of the object Context, otherwise the following error is raised:
context must be a dict rather than Context.
| Python | bsd-3-clause | GetStream/stream-django,GetStream/stream-django | ---
+++
@@ -1,5 +1,5 @@
from django import template
-from django.template import Context, loader
+from django.template import loader
from stream_django.exceptions import MissingDataException
import logging
@@ -41,7 +41,6 @@
tmpl = loader.get_template(template_name)
context['activity'] = activity
- ... |
6727bb98c91f1185042d08f3ff2a4c5ef625cae4 | mjstat/languages/__init__.py | mjstat/languages/__init__.py | # -*- coding: utf-8 -*-
"""__init__.py: Language-dependent features.
"""
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a poor copy of the language framework of Docutils.
"""
if lang_code in module_cache:
return module_cache[lang_code]
... | # -*- coding: utf-8 -*-
"""__init__.py: Language-dependent features.
"""
from importlib import import_module
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a revamped version of function docutils.languages.get_language.
"""
if lang_code in modul... | Use importlib.import_module instead of built-in __import__. | Use importlib.import_module instead of built-in __import__.
| Python | mit | showa-yojyo/bin,showa-yojyo/bin | ---
+++
@@ -1,26 +1,25 @@
# -*- coding: utf-8 -*-
"""__init__.py: Language-dependent features.
"""
+
+from importlib import import_module
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
- This is a poor copy of the language framework of Docutils.
+ Th... |
030d425bb2b9b552516957277aebb22806bfc699 | bills/redis_queue.py | bills/redis_queue.py | # -*- coding: utf-8 -*-
import redis
class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.db = redis.Redis(**redis_kwargs)
self.ke... | # -*- coding: utf-8 -*-
import redis
class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.db = redis.Redis(**redis_kwargs)
self.ke... | Fix a bug in redis queue | Fix a bug in redis queue
| Python | agpl-3.0 | teampopong/crawlers,majorika/crawlers,majorika/crawlers,lexifdev/crawlers,lexifdev/crawlers,teampopong/crawlers | ---
+++
@@ -28,11 +28,11 @@
if necessary until an item is available."""
if block:
item = self.db.blpop(self.key, timeout=timeout)
+ if item:
+ item = item[1]
else:
item = self.db.lpop(self.key)
- if item:
- item = item[... |
6a1d9a327ebf64acba9bd02330bfa047e8137337 | bmi_live/__init__.py | bmi_live/__init__.py | """BMI Live clinic"""
import os
pkg_directory = os.path.dirname(__file__)
data_directory = os.path.join(pkg_directory, 'data')
| """BMI Live clinic"""
import os
from .diffusion import Diffusion
from .bmi_diffusion import BmiDiffusion
__all__ = ['Diffusion', 'BmiDiffusion']
pkg_directory = os.path.dirname(__file__)
data_directory = os.path.join(pkg_directory, 'data')
| Include classes in package definition | Include classes in package definition
| Python | mit | csdms/bmi-live,csdms/bmi-live | ---
+++
@@ -1,6 +1,10 @@
"""BMI Live clinic"""
import os
+from .diffusion import Diffusion
+from .bmi_diffusion import BmiDiffusion
+
+__all__ = ['Diffusion', 'BmiDiffusion']
pkg_directory = os.path.dirname(__file__)
data_directory = os.path.join(pkg_directory, 'data') |
1648e071fe69ba159261f27e4b2d0e2b977d6d83 | zou/app/models/working_file.py | zou/app/models/working_file.py | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(db.String(250))
description = db.Col... | from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class WorkingFile(db.Model, BaseMixin, SerializerMixin):
shotgun_id = db.Column(db.Integer())
name = db.Column(... | Add fields to working file model | Add fields to working file model
* Software
* List of output files generated
* Path used to store the working file
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -1,3 +1,4 @@
+from sqlalchemy.orm import relationship
from sqlalchemy_utils import UUIDType
from zou.app import db
@@ -14,11 +15,18 @@
revision = db.Column(db.Integer())
size = db.Column(db.Integer())
checksum = db.Column(db.Integer())
+ path = db.Column(db.String(400))
task_id... |
afb195b1ca647d776f29fbc1d68a495190caec59 | astropy/time/setup_package.py | astropy/time/setup_package.py | import os
import numpy
from distutils.extension import Extension
TIMEROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
time_ext = Extension(
name="astropy.time.sofa_time",
sources=[os.path.join(TIMEROOT, "sofa_time.pyx"), "cextern/sofa/sofa.c"],
include_dirs=[numpy.get_include()... | import os
from distutils.extension import Extension
TIMEROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
time_ext = Extension(
name="astropy.time.sofa_time",
sources=[os.path.join(TIMEROOT, "sofa_time.pyx"), "cextern/sofa/sofa.c"],
include_dirs=['numpy', 'cextern/sofa'],
la... | Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work. | Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work. | Python | bsd-3-clause | kelle/astropy,AustereCuriosity/astropy,joergdietrich/astropy,stargaser/astropy,astropy/astropy,bsipocz/astropy,bsipocz/astropy,kelle/astropy,larrybradley/astropy,StuartLittlefair/astropy,DougBurke/astropy,mhvk/astropy,stargaser/astropy,aleksandr-bakanov/astropy,tbabej/astropy,dhomeier/astropy,lpsinger/astropy,DougBurke... | ---
+++
@@ -1,5 +1,4 @@
import os
-import numpy
from distutils.extension import Extension
TIMEROOT = os.path.relpath(os.path.dirname(__file__))
@@ -9,6 +8,6 @@
time_ext = Extension(
name="astropy.time.sofa_time",
sources=[os.path.join(TIMEROOT, "sofa_time.pyx"), "cextern/sofa/sofa.c"],
- includ... |
55d22f95301c4c96c42e30fa037df5bc957dc7b4 | incunafein/module/page/extensions/prepared_date.py | incunafein/module/page/extensions/prepared_date.py | from django.db import models
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
| from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
| Add a get prepared date method | Add a get prepared date method
Child pages won't necessarily have a prepared date and it makes sense to
use the parent date to avoid repetition.
| Python | bsd-2-clause | incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms | ---
+++
@@ -1,5 +1,9 @@
from django.db import models
+
+def get_prepared_date(cls):
+ return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
+ cls.add_to_class('get_prepared_dat... |
0fdb33dc0da1aa953e91e71b0e0cfa75fca3d639 | skylines/views/__init__.py | skylines/views/__init__.py | from flask import redirect
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notifications ... | from flask import redirect, url_for
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notif... | Use url_for for base redirection | views: Use url_for for base redirection
| Python | agpl-3.0 | shadowoneau/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,RBE-Avionik/skylines,kerel-fs/skylines,Turbo87/skylines,snip/skylines,kerel-fs/skylines,skylines-project/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,skylines-project/skylines,RBE-... | ---
+++
@@ -1,4 +1,4 @@
-from flask import redirect
+from flask import redirect, url_for
from skylines import app
@@ -27,4 +27,4 @@
@app.route('/')
def index():
- return redirect('/flights/latest')
+ return redirect(url_for('flights.latest')) |
217829993e108fb4f5c17ae2bbc80151418cf733 | Mobiles_Stadtgedaechtnis/urls.py | Mobiles_Stadtgedaechtnis/urls.py | from django.conf.urls import patterns, include, url
import stadtgedaechtnis_backend.admin
import settings
from thread import start_new_thread
js_info_dict = {
'packages': ('stadtgedaechtnis_backend',),
}
urlpatterns = patterns(
'',
url(r'^', include('stadtgedaechtnis_backend.urls', namespace="stadtgedaec... | from django.conf.urls import patterns, include, url
import stadtgedaechtnis_backend.admin
import settings
from thread import start_new_thread
js_info_dict = {
'packages': ('stadtgedaechtnis_backend',),
}
urlpatterns = patterns(
'',
url(r'^', include('stadtgedaechtnis_backend.urls', namespace="stadtgedaec... | Replace list with tuple in start new thread | Replace list with tuple in start new thread
| Python | mit | fraunhoferfokus/mobile-city-memory,fraunhoferfokus/mobile-city-memory,jessepeng/coburg-city-memory,jessepeng/coburg-city-memory | ---
+++
@@ -34,4 +34,4 @@
schedule.run_pending()
time.sleep(1)
-start_new_thread(run_cronjobs, [])
+start_new_thread(run_cronjobs, ()) |
cc3ab3af17e30e7dd9991d68f01eaa4535b64e6b | djangae/models.py | djangae/models.py | from django.db import models
class CounterShard(models.Model):
count = models.PositiveIntegerField()
| from django.db import models
class CounterShard(models.Model):
count = models.PositiveIntegerField()
#Apply our django patches
from .patches import * | Patch update_contenttypes so that it's less likely to fail due to eventual consistency | Patch update_contenttypes so that it's less likely to fail due to eventual consistency
| Python | bsd-3-clause | nealedj/djangae,martinogden/djangae,grzes/djangae,stucox/djangae,asendecka/djangae,trik/djangae,trik/djangae,wangjun/djangae,armirusco/djangae,b-cannon/my_djae,jscissr/djangae,grzes/djangae,wangjun/djangae,chargrizzle/djangae,chargrizzle/djangae,leekchan/djangae,kirberich/djangae,martinogden/djangae,pablorecio/djangae,... | ---
+++
@@ -2,3 +2,7 @@
class CounterShard(models.Model):
count = models.PositiveIntegerField()
+
+
+#Apply our django patches
+from .patches import * |
776c3b0df6136606b8b7474418fd5d078457bd0a | test/persistence_test.py | test/persistence_test.py | from os.path import exists, join
import shutil
import tempfile
import time
from lwr.managers.queued import QueueManager
from lwr.managers.stateful import StatefulManagerProxy
from lwr.tools.authorization import get_authorizer
from .test_utils import TestDependencyManager
from galaxy.util.bunch import Bunch
def test... | from os.path import exists, join
import shutil
import tempfile
import time
from lwr.managers.queued import QueueManager
from lwr.managers.stateful import StatefulManagerProxy
from lwr.tools.authorization import get_authorizer
from .test_utils import TestDependencyManager
from galaxy.util.bunch import Bunch
from galax... | Fix another failing unit test (from metrics work). | Fix another failing unit test (from metrics work).
| Python | apache-2.0 | jmchilton/lwr,natefoo/pulsar,natefoo/pulsar,jmchilton/pulsar,galaxyproject/pulsar,jmchilton/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,ssorgatem/pulsar,jmchilton/lwr | ---
+++
@@ -9,6 +9,7 @@
from .test_utils import TestDependencyManager
from galaxy.util.bunch import Bunch
+from galaxy.jobs.metrics import NULL_JOB_INSTRUMENTER
def test_persistence():
@@ -21,6 +22,7 @@
persistence_directory=staging_directory,
authorizer=get_authoriz... |
3ee7d716f0eb3202ccf7ca213747eb903f9bb471 | __init__.py | __init__.py | from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string
from .Timer import Timer
from .UserInput import user_input
| from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string, time2levels, time2dir, time2fname
from .Timer import Timer
from .UserInput import user_input
| Add missing names to module namespace. | Add missing names to module namespace.
| Python | mit | vmlaker/coils | ---
+++
@@ -3,6 +3,6 @@
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
-from .String import string2time, time2string
+from .String import string2time, time2string, time2levels, time2dir, time2fname
from .Timer import Timer
from .UserInput import user_input |
c05fc3ae4d6ac0ed459150acf2c19fd892c2ea9f | bumblebee/modules/caffeine.py | bumblebee/modules/caffeine.py | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | Add some basic error handling in case the executables don't exist | Add some basic error handling in case the executables don't exist
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -30,11 +30,14 @@
def _toggle(self, event):
self._active = not self._active
- if self._active:
- bumblebee.util.execute("xdg-screensaver reset")
- bumblebee.util.execute("notify-send \"Consuming caffeine\"")
- else:
- bumblebee.util.execute("not... |
ffadde617db8ac3d0d5362b4a521dd4e9839710f | order/order_2_login_system_by_https.py | order/order_2_login_system_by_https.py | import json
import requests
""" Order 2: Login system by https
```
curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{
"credentials": {
"username": "admin",
"password": "a10"
}
}'
```
"""
class LoginSystemByHttps(object):
login_url = 'http://192.168.105... | import json
import requests
""" Order 2: Login system by https
This is the code which use curl to login system
```
curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{
"credentials": {
"username": "admin",
"password": "a10"
}
}'
```
"""
class LoginSystemByHt... | Order 2: Login system by https | [Order] Order 2: Login system by https
| Python | mit | flyingSprite/spinelle | ---
+++
@@ -3,6 +3,7 @@
""" Order 2: Login system by https
+This is the code which use curl to login system
```
curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{
"credentials": { |
646a248d59f835264729b48a0116d51089f6113e | oscar/templatetags/currency_filters.py | oscar/templatetags/currency_filters.py | from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value =... | from decimal import Decimal as D, InvalidOperation
from django import template
from django.conf import settings
from babel.numbers import format_currency
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
value =... | Replace broken babel documentation link | Replace broken babel documentation link
According to Babel's PyPI package page, http://babel.pocoo.org/docs/ is
the official documentation website.
| Python | bsd-3-clause | lijoantony/django-oscar,faratro/django-oscar,michaelkuty/django-oscar,MatthewWilkes/django-oscar,django-oscar/django-oscar,dongguangming/django-oscar,taedori81/django-oscar,pasqualguerrero/django-oscar,marcoantoniooliveira/labweb,faratro/django-oscar,Jannes123/django-oscar,binarydud/django-oscar,Jannes123/django-oscar,... | ---
+++
@@ -17,7 +17,7 @@
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
- # http://packages.python.org/Babel/api/babel.numbers-module.html#format_currency
+ # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency
kwargs = {
... |
315b581b9b0438389c7f4eb651d2893b805a2369 | translit.py | translit.py | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | Handle case when char is mapped to empty (removed) and table is inverted | Handle case when char is mapped to empty (removed) and table is inverted
| Python | mit | malexer/SublimeTranslit | ---
+++
@@ -15,11 +15,14 @@
@property
def rules(self):
for r in self._rules:
+ k, v = r
+ if len(k) == 0:
+ continue # for case when char is removed and mapping inverted
+
yield r
# Handle the case when one source upper char is repre... |
6f8f449316a71dd284d2661d206d88d35c01ea54 | TrevorNet/tests/test_idx.py | TrevorNet/tests/test_idx.py | from .. import idx
import os
def test__find_depth():
yield check__find_depth, 9, 0
yield check__find_depth, [1, 2], 1
yield check__find_depth, [[1, 2], [3, 6, 2]], 2
yield check__find_depth, [[[1,2], [2]]], 3
def check__find_depth(lst, i):
assert idx._find_dimensions(lst) == i
# these two are equ... | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dime... | Update for python 3 and new idx design | Update for python 3 and new idx design
idx no longer writes to files, it only processes bytes
| Python | mit | tmerr/trevornet | ---
+++
@@ -1,34 +1,23 @@
from .. import idx
import os
-def test__find_depth():
- yield check__find_depth, 9, 0
- yield check__find_depth, [1, 2], 1
- yield check__find_depth, [[1, 2], [3, 6, 2]], 2
- yield check__find_depth, [[[1,2], [2]]], 3
+def test__count_dimensions():
+ yield check__count_dim... |
c5b130444e2061ae1c6bdf16ebc14d08817a8aea | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.3.10 | Update dsub version to 0.3.10
PiperOrigin-RevId: 324884094
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.3.10.dev0'
+DSUB_VERSION = '0.3.10' |
564075cbb66c6e79a6225d7f678aea804075b966 | api/urls.py | api/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'fbxnano.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url('^status$', TemplateView.as_view(template_name='api/status.html'), name=... | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from .views import StatusView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'fbxnano.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url('^status$', StatusView.as_view(), name=... | Switch from generic TemplateView to new StatusView | Switch from generic TemplateView to new StatusView
| Python | mit | Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano | ---
+++
@@ -1,10 +1,14 @@
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
+
+
+from .views import StatusView
+
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'fbxnano.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
- ur... |
e615e2ebf3f364ba093c48d6fb0c988f0b97bc13 | nyuki/workflow/tasks/__init__.py | nyuki/workflow/tasks/__init__.py | from .factory import FactoryTask
from .report import ReportTask
from .sleep import SleepTask
# Generic schema to reference a task ID
TASKID_SCHEMA = {
'type': 'string',
'description': 'task_id'
}
| from .factory import FactoryTask
from .report import ReportTask
from .sleep import SleepTask
# Generic schema to reference a task ID
TASKID_SCHEMA = {
'type': 'string',
'description': 'task_id',
'maxLength': 128
}
| Add maxlength to taskid schema | Add maxlength to taskid schema
| Python | apache-2.0 | gdraynz/nyuki,optiflows/nyuki,gdraynz/nyuki,optiflows/nyuki | ---
+++
@@ -6,5 +6,6 @@
# Generic schema to reference a task ID
TASKID_SCHEMA = {
'type': 'string',
- 'description': 'task_id'
+ 'description': 'task_id',
+ 'maxLength': 128
} |
fe4ce6dfa26c60747b6024fa9f6d991aa3b95614 | scripts/codegen_driverwrappers/generate_driver_wrappers.py | scripts/codegen_driverwrappers/generate_driver_wrappers.py | #!/usr/bin/env python3
import sys
import json
import os
import jinja2
def render(tpl_path):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render()
n = len(sys.argv)
if ( n != 3 ):
sys.exit("The templat... | #!/usr/bin/env python3
import sys
import json
import os
import jinja2
def render(tpl_path):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './'),
keep_trailing_newline=True,
).get_template(filename).render()
n = len(sys.argv)
if ... | Fix trailing newline getting dropped | Fix trailing newline getting dropped
Signed-off-by: Gilles Peskine <f805f64266d288fc5467baa7be6cd0ff366f477b@arm.com>
| Python | apache-2.0 | Mbed-TLS/mbedtls,NXPmicro/mbedtls,NXPmicro/mbedtls,Mbed-TLS/mbedtls,NXPmicro/mbedtls,NXPmicro/mbedtls,ARMmbed/mbedtls,Mbed-TLS/mbedtls,ARMmbed/mbedtls,ARMmbed/mbedtls,Mbed-TLS/mbedtls,ARMmbed/mbedtls | ---
+++
@@ -8,7 +8,8 @@
def render(tpl_path):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
- loader=jinja2.FileSystemLoader(path or './')
+ loader=jinja2.FileSystemLoader(path or './'),
+ keep_trailing_newline=True,
).get_template(filename).render()
n = l... |
c264e4b19505bfb0ccebc1551c7b82e96b6a2882 | amqpy/tests/test_version.py | amqpy/tests/test_version.py | class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
readme = f.read().split('\n')
version_list = readme[3].split(':')[2].strip().split('.')
version_list = [int(i) for i in version_list]
readme_... | import re
def get_field(doc: str, name: str):
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
if match:
return match.group(1).strip()
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
with open('README.rst') as f:
... | Clean up test for version number | Clean up test for version number
A new function is implemented to cleanly extract the version field from the
README.rst field list.
| Python | mit | veegee/amqpy,gst/amqpy | ---
+++
@@ -1,11 +1,22 @@
+import re
+
+
+def get_field(doc: str, name: str):
+ match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)
+ if match:
+ return match.group(1).strip()
+
+
class TestVersion:
def test_version_is_consistent(self):
from .. import VERSION
... |
a7830d85c6966732e46da63903c04234d8d16c39 | admin/nodes/serializers.py | admin/nodes/serializers.py | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... | Add date_registered to node serializer | Add date_registered to node serializer
[#OSF-7230]
| Python | apache-2.0 | mattclark/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,mattclark/osf.io,caseyrollins/osf.io,chennan47/osf.io,adlius/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,chennan47/osf.io,hmoco/osf.io,caneruguz/osf.io,mfra... | ---
+++
@@ -24,6 +24,7 @@
'children': map(serialize_simple_node, node.nodes),
'deleted': node.is_deleted,
'pending_registration': node.is_pending_registration,
+ 'registered_date': node.registered_date,
'creator': node.creator._id,
'spam_status': node.spam_status,
... |
f625cac0a49bafc96403f5b34c2e138f8d2cfbea | dev/lint.py | dev/lint.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
from flake8.engine import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if ... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.pat... | Add support for flake8 3.0 | Add support for flake8 3.0
| Python | mit | wbond/asn1crypto | ---
+++
@@ -3,7 +3,11 @@
import os
-from flake8.engine import get_style_guide
+import flake8
+if flake8.__version_info__ < (3,):
+ from flake8.engine import get_style_guide
+else:
+ from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__) |
573718a17e5e2d3fe23b1c8cd128a9b46d6076e6 | example-theme.py | example-theme.py | # Supported 16 color values:
# 'h0' (color number 0) through 'h15' (color number 15)
# or
# 'default' (use the terminal's default foreground),
# 'black', 'dark red', 'dark green', 'brown', 'dark blue',
# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',
# 'light red', 'light green', 'yellow', 'light ... | # Supported 16 color values:
# 'h0' (color number 0) through 'h15' (color number 15)
# or
# 'default' (use the terminal's default foreground),
# 'black', 'dark red', 'dark green', 'brown', 'dark blue',
# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',
# 'light red', 'light green', 'yellow', 'light ... | Add link to defined colors to example theme | Add link to defined colors to example theme
| Python | mit | amigrave/pudb,albfan/pudb,amigrave/pudb,albfan/pudb | ---
+++
@@ -14,6 +14,9 @@
#
# "setting_name": (foreground_color, background_color),
+# See this URL to see what keys there are:
+# https://github.com/inducer/pudb/blob/master/pudb/theme.py
+
palette.update({
"source": (add_setting("black", "underline"), "dark green"),
"comment": ("h250", "default") |
a45f5ca2e92cfaa4478d632ada3889b81fef5f53 | features/urls.py | features/urls.py | from django.conf.urls import url, include
from django.views.generic import TemplateView
from rest_framework import routers
from .views import FeatureRequestViewSet, ClientViewSet, ProductAreaViewSet
router = routers.DefaultRouter()
router.register(r'features', FeatureRequestViewSet)
router.register(r'client', Client... | from django.conf.urls import url, include
from django.views.generic import TemplateView
from rest_framework import routers
from .views import FeatureRequestViewSet, ClientViewSet, ProductAreaViewSet
router = routers.DefaultRouter()
router.register(r'features', FeatureRequestViewSet)
router.register(r'client', Client... | Index route should only match on '/' | BUGFIX: Index route should only match on '/'
| Python | mit | wkevina/feature-requests-app,wkevina/feature-requests-app,wkevina/feature-requests-app | ---
+++
@@ -11,7 +11,7 @@
router.register(r'productarea', ProductAreaViewSet)
urlpatterns = [
- url(r'^', TemplateView.as_view(template_name='features/index.html')),
+ url(r'^$', TemplateView.as_view(template_name='features/index.html')),
url(r'^api/', include(router.urls)),
url(r'api-auth/', incl... |
72c122d8ff580a4c0c5fa4554844c73c657a6581 | apnsclient/__init__.py | apnsclient/__init__.py | # Copyright 2013 Getlogic BV, Sardar Yumatov
#
# 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 t... | # Copyright 2013 Getlogic BV, Sardar Yumatov
#
# 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 t... | Adjust the module __version__ to match the version advertised in PyPI. | Adjust the module __version__ to match the version advertised in PyPI.
--HG--
branch : intellectronica/adjust-the-module-__version__-to-match-t-1371450045566
| Python | apache-2.0 | marcinkaszynski/apnsclient | ---
+++
@@ -14,7 +14,7 @@
__title__ = 'APNS client'
-__version__ = "0.1.1"
+__version__ = "0.1.5"
__author__ = "Sardar Yumatov"
__contact__ = "ja.doma@gmail.com"
__license__ = "Apache 2.0" |
efd64433fab0cae0aaffbd30864c9271c0627502 | packages/fsharp-3.1.py | packages/fsharp-3.1.py |
class Fsharp31Package(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self,
'fsharp', 'fsharp',
'3.1.1.31',
'1f79c0455fb8b5ec816985f922413894ce19359a',
configure = '')
self.sources.extend ([
'fsharp-fix-net45-profile.patch')
def prep(self):
Package.prep (self)
for p ... |
class Fsharp31Package(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self,
'fsharp', 'fsharp',
'3.1.1.31',
'1f79c0455fb8b5ec816985f922413894ce19359a',
configure = '')
self.sources.extend ([
'patches/fsharp-fix-net45-profile.patch'])
def prep(self):
Package.prep (self)
... | Fix the typos, fix the build. | Fix the typos, fix the build.
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild | ---
+++
@@ -7,7 +7,7 @@
'1f79c0455fb8b5ec816985f922413894ce19359a',
configure = '')
self.sources.extend ([
- 'fsharp-fix-net45-profile.patch')
+ 'patches/fsharp-fix-net45-profile.patch'])
def prep(self):
Package.prep (self) |
b50b7143185131a81e84f0659ff6405317f7d36f | resolwe/flow/execution_engines/base.py | resolwe/flow/execution_engines/base.py | """Workflow execution engines."""
from resolwe.flow.engine import BaseEngine
class BaseExecutionEngine(BaseEngine):
"""A workflow execution engine."""
def evaluate(self, data):
"""Return the code needed to compute a given Data object."""
raise NotImplementedError
def get_expression_engin... | """Workflow execution engines."""
from resolwe.flow.engine import BaseEngine
class BaseExecutionEngine(BaseEngine):
"""A workflow execution engine."""
def evaluate(self, data):
"""Return the code needed to compute a given Data object."""
raise NotImplementedError
def get_expression_engin... | Return empty dictionary instead of None | Return empty dictionary instead of None
| Python | apache-2.0 | genialis/resolwe,genialis/resolwe | ---
+++
@@ -34,3 +34,4 @@
and values are paths under which these should be made available
to the executing program. All volumes will be read-only.
"""
+ return {} |
b62f52a30404901ff3ffa7af90a3f1bdd7d05401 | project/hhlcallback/utils.py | project/hhlcallback/utils.py | # -*- coding: utf-8 -*-
import environ
env = environ.Env()
HOLVI_CNC = False
def get_holvi_singleton():
global HOLVI_CNC
if HOLVI_CNC:
return HOLVI_CNC
holvi_pool = env('HOLVI_POOL', default=None)
holvi_key = env('HOLVI_APIKEY', default=None)
if not holvi_pool or not holvi_key:
retu... | # -*- coding: utf-8 -*-
import holviapi.utils
def get_nordea_payment_reference(member_id, number):
base = member_id + 1000
return holviapi.utils.int2fin_reference(int("%s%s" % (base, number)))
| Remove copy-pasted code, add helper for making legacy reference number for payments | Remove copy-pasted code, add helper for making legacy reference number for payments
| Python | mit | HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum | ---
+++
@@ -1,16 +1,6 @@
# -*- coding: utf-8 -*-
-import environ
-env = environ.Env()
-HOLVI_CNC = False
+import holviapi.utils
-def get_holvi_singleton():
- global HOLVI_CNC
- if HOLVI_CNC:
- return HOLVI_CNC
- holvi_pool = env('HOLVI_POOL', default=None)
- holvi_key = env('HOLVI_APIKEY', defau... |
6f30aed2b5f157bb22c8761a92464302ec5d8911 | DebianChangesBot/utils/__init__.py | DebianChangesBot/utils/__init__.py | # -*- coding: utf-8 -*-
import email.quoprimime
def quoted_printable(val):
try:
if type(val) is str:
return email.quoprimime.header_decode(val)
else:
return unicode(email.quoprimime.header_decode(str(val)), 'utf-8')
except Exception, e:
# We ignore errors here.... | # -*- coding: utf-8 -*-
import email
import re
def header_decode(s):
def unquote_match(match):
s = match.group(0)
return chr(int(s[1:3], 16))
s = s.replace('_', ' ')
return re.sub(r'=\w{2}', unquote_match, s)
def quoted_printable(val):
try:
if type(val) is str:
sa... | Update header_decode to handle bare and non-bare quoted-printable chars | Update header_decode to handle bare and non-bare quoted-printable chars
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | xtaran/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot | ---
+++
@@ -1,13 +1,28 @@
# -*- coding: utf-8 -*-
-import email.quoprimime
+import email
+import re
+
+def header_decode(s):
+ def unquote_match(match):
+ s = match.group(0)
+ return chr(int(s[1:3], 16))
+
+ s = s.replace('_', ' ')
+ return re.sub(r'=\w{2}', unquote_match, s)
def quoted_p... |
b5b17c5152e969ed4e629a5df8dd296cde164f9b | polymer_states/__init__.py | polymer_states/__init__.py | # 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/. | # 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/.
# Link states
UP, DOWN = (0, 1), (0, -1)
LEFT, RIGHT = (-1, 0), (1, 0)
SLACK = (0, 0) | Add link states to polymer_states | Add link states to polymer_states
| Python | mpl-2.0 | szabba/applied-sims | ---
+++
@@ -1,3 +1,8 @@
# 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/.
+
+# Link states
+UP, DOWN = (0, 1), (0, -1)
+LEFT, RIGHT = (-1, 0), (1, 0)
+SLACK = (0, ... |
656c0a9b91ee6f6f3f9811b16ab75dc8003402ad | altair/examples/line_chart_with_generator.py | altair/examples/line_chart_with_generator.py | """
Line Chart with Sequence Generator
----------------------------------
This examples shows how to create multiple lines using the sequence generator.
"""
# category: line charts
import altair as alt
source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')
alt.Chart(source).mark_line().transform_calculate(
... | """
Line Chart with Sequence Generator
----------------------------------
This examples shows how to create multiple lines using the sequence generator.
"""
# category: line charts
import altair as alt
source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')
alt.Chart(source).mark_line().transform_calculate(
... | Modify generator example to use single calculation transform | DOC: Modify generator example to use single calculation transform
| Python | bsd-3-clause | jakevdp/altair,altair-viz/altair | ---
+++
@@ -10,8 +10,7 @@
source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')
alt.Chart(source).mark_line().transform_calculate(
- sin='sin(datum.x)'
-).transform_calculate(
+ sin='sin(datum.x)',
cos='cos(datum.x)'
).transform_fold(
['sin', 'cos'] |
4d1dc36e7426a13906dd1b75eda2c8bff94c88b4 | pwm_server/__init__.py | pwm_server/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from logging import getLogger
import os
import pwm
db = SQLAlchemy()
_logger = getLogger('pwm_server')
class PWMApp(Flask):
def bootstrap(self):
""" Initialize database tables for both pwm_server and pwm. """
from .models import ... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from logging import getLogger
import os
import pwm
db = SQLAlchemy()
_logger = getLogger('pwm_server')
class PWMApp(Flask):
def bootstrap(self):
""" Initialize database tables for both pwm_server and pwm. """
from .models import ... | Resolve config from envvar relative to cwd | Resolve config from envvar relative to cwd
| Python | mit | thusoy/pwm-server,thusoy/pwm-server | ---
+++
@@ -23,10 +23,10 @@
if config_file:
config_path = os.path.join(os.getcwd(), config_file)
_logger.debug('Loading config from %s', config_path)
- app.config.from_pyfile(config_path)
else:
_logger.debug('Loading config from envvar, file %s', os.environ['PWM_SERVER_CONF... |
7319ac2eb5d31b14c731371a82102c90d8ec3979 | tests/test_reflection_views.py | tests/test_reflection_views.py | from sqlalchemy import MetaData, Table, inspect
from sqlalchemy.schema import CreateTable
from rs_sqla_test_utils.utils import clean, compile_query
def table_to_ddl(engine, table):
return str(CreateTable(table)
.compile(engine))
def test_view_reflection(redshift_engine):
table_ddl = "CREATE ... | from sqlalchemy import MetaData, Table, inspect
from sqlalchemy.schema import CreateTable
from rs_sqla_test_utils.utils import clean, compile_query
def table_to_ddl(engine, table):
return str(CreateTable(table)
.compile(engine))
def test_view_reflection(redshift_engine):
table_ddl = "CREATE ... | Add test for late-binding views | Add test for late-binding views
| Python | mit | sqlalchemy-redshift/sqlalchemy-redshift,sqlalchemy-redshift/sqlalchemy-redshift,graingert/redshift_sqlalchemy | ---
+++
@@ -22,3 +22,21 @@
view = Table('my_view', MetaData(),
autoload=True, autoload_with=redshift_engine)
assert(len(view.columns) == 2)
+
+
+def test_late_binding_view_reflection(redshift_engine):
+ table_ddl = "CREATE TABLE my_table (col1 INTEGER, col2 INTEGER)"
+ view_query = "... |
e051c915d72b76a189c16de6ff82bcebdab9f881 | caffe2/python/layers/__init__.py | caffe2/python/layers/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
import inspect
from . import layers
def import_recursive(package, clsmembers):
"""
Takes a package... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
from . import layers
def import_recursive(package):
"""
Takes a package and imports all modules un... | Allow to import subclasses of layers | Allow to import subclasses of layers
Summary:
We want it to be able to register children of layers who
are not direct children of ModelLayer.
This requires us to find subclasses of ModelLayer recursively.
Reviewed By: kittipatv, kennyhorror
Differential Revision: D5397120
fbshipit-source-id: cb1e03d72e3bedb960b1b86... | Python | apache-2.0 | Yangqing/caffe2,xzturn/caffe2,sf-wind/caffe2,pietern/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,davinwang/caffe2,sf-wind/caffe2,caffe2/caffe2,Yangqing/caffe2,bwasti/caffe2,Yangqing/caffe2,bwasti/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,bwasti/caffe2,bwasti/caffe2,sf-wind/caffe2,sf-wind/caffe2,bwa... | ---
+++
@@ -6,11 +6,10 @@
from importlib import import_module
import pkgutil
import sys
-import inspect
from . import layers
-def import_recursive(package, clsmembers):
+def import_recursive(package):
"""
Takes a package and imports all modules underneath it
"""
@@ -20,14 +19,21 @@
for (_m... |
b99770a7c55cd6951df872793a54bfa260b145f9 | basics/test/module-test.py | basics/test/module-test.py | from unittest import TestCase
from basics import BaseCharacter
from basics import BaseAttachment
class ModuleTest(TestCase):
def test_character_attach_attachment(self):
character = BaseCharacter().save()
attachment = BaseAttachment().save()
# Attachment should not be among the character... | from unittest import TestCase
from basics import BaseCharacter
from basics import BaseAttachment
from basics import BaseThing
class ModuleTest(TestCase):
def test_character_attach_attachment(self):
character = BaseCharacter().save()
attachment = BaseAttachment().save()
# Attachment shou... | Write test for container containment. | Write test for container containment.
| Python | apache-2.0 | JASchilz/RoverMUD | ---
+++
@@ -2,6 +2,7 @@
from basics import BaseCharacter
from basics import BaseAttachment
+from basics import BaseThing
class ModuleTest(TestCase):
@@ -20,4 +21,21 @@
self.assertIn(attachment.id, character.attachments())
def test_container_containment(self):
- self.fail("Test unwritte... |
b506b6796a8ed9e778f69ddc7718a8ea3b0f9e7a | flynn/__init__.py | flynn/__init__.py | # coding: utf-8
import flynn.decoder
import flynn.encoder
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def dumph(obj):
return "".join(hex(n)[2:].rjust(2, "0") for n in dumps(obj))
def load(s):
return flynn.decoder.decode(s)
def loads(s):
return ... | # coding: utf-8
import base64
import flynn.decoder
import flynn.encoder
__all__ = [
"decoder",
"encoder",
"dump",
"dumps",
"dumph",
"load",
"loads",
"loadh"
]
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def dumph(obj):
return base64.b16en... | Use base64 module to convert between bytes and base16 string | Use base64 module to convert between bytes and base16 string
| Python | mit | fritz0705/flynn | ---
+++
@@ -1,7 +1,20 @@
# coding: utf-8
+
+import base64
import flynn.decoder
import flynn.encoder
+
+__all__ = [
+ "decoder",
+ "encoder",
+ "dump",
+ "dumps",
+ "dumph",
+ "load",
+ "loads",
+ "loadh"
+]
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
@@ -10,7 +23,7 @@
return flynn.encoder.enco... |
7b71425a4434ac2544340d651f52c0d87ff37132 | web/impact/impact/v1/helpers/refund_code_helper.py | web/impact/impact/v1/helpers/refund_code_helper.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.models import RefundCode
from impact.v1.helpers.model_helper import(
INTEGER_ARRAY_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAMS_FIELD = {
"json-schema": {
"type": "array",
"items": {"ty... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.models import RefundCode
from impact.v1.helpers.model_helper import(
BOOLEAN_FIELD,
INTEGER_ARRAY_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAMS_FIELD = {
"json-schema": {
"type": "array",
... | Add Notes and Internal Fields | [AC-5291] Add Notes and Internal Fields
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -3,6 +3,7 @@
from impact.models import RefundCode
from impact.v1.helpers.model_helper import(
+ BOOLEAN_FIELD,
INTEGER_ARRAY_FIELD,
INTEGER_FIELD,
ModelHelper,
@@ -28,6 +29,8 @@
"discount": INTEGER_FIELD,
"maximum_uses": INTEGER_FIELD,
"programs": INTEGER_ARRAY_FIELD,
+... |
c1f71014218d9b6cdb6c45d9d1ce0cc0424f70f8 | doc/pyplots/stylesheet_gallery.py | doc/pyplots/stylesheet_gallery.py | # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
x = np.linspace(0, np.pi, 20)
fig, ax = plt... | # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
if stylename == 'typhon-dark':
# TODO: S... | Exclude dark-colored theme from stylesheet gallery. | Exclude dark-colored theme from stylesheet gallery.
| Python | mit | atmtools/typhon,atmtools/typhon | ---
+++
@@ -8,6 +8,10 @@
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
+ if stylename == 'typhon-dark':
+ # TODO: Sphinx build is broken for non-white figure facecolor.
+ return
+
x = np.linspace(0, np.pi, 20)
fig, ax = plt.subplots() |
41fbd5b92ac04c3a4ca0e33204bb08b12a533052 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -14,8 +14,10 @@
import ibmcnx.functions
-cell = AdminConfig.getid( '"/Cell:' + AdminControl.getCell() + '/"' )
-dbs = AdminConfig.list( 'DataSource', cell )
+cell = "'/Cell:" + AdminControl.getCell() + "/'"
+print cell
+cellid = AdminConfig.getid( )
+dbs = AdminConfig.list( 'DataSource', cellid )
... |
07c3c7e00a4c2733a3233ff483797c798451a87f | apps/predict/mixins.py | apps/predict/mixins.py | """
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
... | """
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
... | Improve prefetch speed in predict listing pages | Improve prefetch speed in predict listing pages
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site | ---
+++
@@ -18,9 +18,9 @@
def get_queryset(self):
"""Limit queryset to the user's own predictions only"""
- qs = PredictDataset.objects.all()
+ qset = PredictDataset.objects.all()
if 'slug' not in self.kwargs:
# Limit to my own predictions unless I have the md5
- ... |
324941bb4946cea19800fb1102035bd32e8028db | apps/profiles/views.py | apps/profiles/views.py | from django.views.generic import DetailView, UpdateView
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import User
class ProfileDetailView(DetailView):
'''
Dis... | from django.views.generic import DetailView, UpdateView
from django.contrib.auth.views import redirect_to_login
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import User
class ProfileDetailView(DetailView):
'''
Dis... | Use select_related in user profile detail view | Use select_related in user profile detail view
| Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas | ---
+++
@@ -12,7 +12,7 @@
'''
Displays the user profile information
'''
- model = User
+ queryset = User.objects.select_related('location', 'location__country')
slug_field = 'username'
slug_url_kwarg = 'username'
|
3e842228beba066000eac536635e7e9d4d87c8e2 | instruments/Instrument.py | instruments/Instrument.py | from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, value)
| from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class. | Add enabled to top-level instrument class.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,rmcgurrin/PyQLab,calebjordan/PyQLab,BBN-Q/PyQLab | ---
+++
@@ -1,4 +1,4 @@
-from traits.api import HasTraits
+from traits.api import HasTraits, Bool
import json
@@ -6,6 +6,7 @@
"""
Main super-class for all instruments.
"""
+ enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__() |
cfe594ec7576ba36e93762981067ad02176a585e | instruments/Instrument.py | instruments/Instrument.py | from traits.api import HasTraits
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items():
setattr(self, key, value)
| from traits.api import HasTraits, Bool
import json
class Instrument(HasTraits):
"""
Main super-class for all instruments.
"""
enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__()
def set_settings(self, settings):
for key,value in settings.items(... | Add enabled to top-level instrument class. | Add enabled to top-level instrument class.
| Python | apache-2.0 | Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab,calebjordan/PyQLab,rmcgurrin/PyQLab | ---
+++
@@ -1,4 +1,4 @@
-from traits.api import HasTraits
+from traits.api import HasTraits, Bool
import json
@@ -6,6 +6,7 @@
"""
Main super-class for all instruments.
"""
+ enabled = Bool(True, desc='Whether the unit is used/enabled.')
def get_settings(self):
return self.__getstate__() |
413413ac7b2f5a953443bdd08d625a55bd890938 | flaws/__init__.py | flaws/__init__.py | #!/usr/bin/env python
import sys
from funcy import split, map
from .analysis import global_usage, local_usage, FileSet
def main():
command = sys.argv[1]
opts, args = split(r'^--', sys.argv[2:])
opts = dict(map(r'^--(\w+)(?:=(.+))?', opts))
# Run ipdb on exception
if 'ipdb' in opts:
impo... | #!/usr/bin/env python
import sys
from funcy import split, map
from .analysis import global_usage, local_usage, FileSet
def main():
command = sys.argv[1]
opts, args = split(r'^--', sys.argv[2:])
opts = dict(map(r'^--(\w+)(?:=(.+))?', opts))
# Run ipdb on exception
if 'ipdb' in opts:
impo... | Insert look-around helpers into ipdb context | Insert look-around helpers into ipdb context
These are `ast` and `to_source`.
| Python | bsd-2-clause | Suor/flaws | ---
+++
@@ -18,6 +18,13 @@
def info(type, value, tb):
traceback.print_exception(type, value, tb)
print
+ # Insert look-around helpers into the frame
+ import inspect, ast
+ from .asttools import to_source
+ frame = inspect.getinnerframes(t... |
8beb6ddd2e58d6a3e54ab297d490c6650fb85a9d | logya/generate.py | logya/generate.py | # -*- coding: utf-8 -*-
import os
import shutil
from logya.core import Logya
from logya.fs import copytree
from logya.writer import DocWriter
class Generate(Logya):
"""Generate a Web site to deploy from current directory as source."""
def __init__(self, **kwargs):
super(self.__class__, self).__init... | # -*- coding: utf-8 -*-
import os
import shutil
from logya.core import Logya
from logya.fs import copytree
from logya.writer import DocWriter
class Generate(Logya):
"""Generate a Web site to deploy from current directory as source."""
def __init__(self, **kwargs):
super(self.__class__, self).__init_... | Add build and write function to make it easy to subclass Generate and overwrite build step | Add build and write function to make it easy to subclass Generate and overwrite build step
| Python | mit | elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya | ---
+++
@@ -11,26 +11,27 @@
"""Generate a Web site to deploy from current directory as source."""
def __init__(self, **kwargs):
-
super(self.__class__, self).__init__(**kwargs)
self.init_env()
-
- # Init writer before executing scripts, so they can use it.
self.writer = D... |
9971e5424b998f45e26b9da8288f20d641885043 | massa/__init__.py | massa/__init__.py | # -*- coding: utf-8 -*-
from flask import Flask, render_template, g
from flask.ext.appconfig import AppConfig
def create_app(configfile=None):
app = Flask('massa')
AppConfig(app, configfile)
@app.route('/')
def index():
return render_template('index.html')
from .container import build
... | # -*- coding: utf-8 -*-
from flask import Flask, render_template, g
from flask.ext.appconfig import AppConfig
from .container import build
from .api import bp as api
def create_app(configfile=None):
app = Flask('massa')
AppConfig(app, configfile)
@app.route('/')
def index():
return render_te... | Move import statements to the top. | Move import statements to the top. | Python | mit | jaapverloop/massa | ---
+++
@@ -2,6 +2,8 @@
from flask import Flask, render_template, g
from flask.ext.appconfig import AppConfig
+from .container import build
+from .api import bp as api
def create_app(configfile=None):
@@ -12,11 +14,9 @@
def index():
return render_template('index.html')
- from .container im... |
12c97be97a8816720899531b932be99743b6d90d | rest_framework_plist/__init__.py | rest_framework_plist/__init__.py | # -*- coding: utf-8 -*-
from distutils import version
__version__ = '0.2.0'
version_info = version.StrictVersion(__version__).version
| # -*- coding: utf-8 -*-
from distutils import version
__version__ = '0.2.0'
version_info = version.StrictVersion(__version__).version
from .parsers import PlistParser # NOQA
from .renderers import PlistRenderer # NOQA
| Make parser and renderer available at package root | Make parser and renderer available at package root
| Python | bsd-2-clause | lpomfrey/django-rest-framework-plist,pombredanne/django-rest-framework-plist | ---
+++
@@ -3,3 +3,6 @@
__version__ = '0.2.0'
version_info = version.StrictVersion(__version__).version
+
+from .parsers import PlistParser # NOQA
+from .renderers import PlistRenderer # NOQA |
3f7371c796a420cc077cf79b210d401c77b77815 | rest_framework/response.py | rest_framework/response.py | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... | Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing | Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing
| Python | bsd-2-clause | kylefox/django-rest-framework,cyberj/django-rest-framework,vstoykov/django-rest-framework,wedaly/django-rest-framework,canassa/django-rest-framework,tomchristie/django-rest-framework,linovia/django-rest-framework,cheif/django-rest-framework,nhorelik/django-rest-framework,jpulec/django-rest-framework,James1345/django-re... | ---
+++
@@ -21,6 +21,14 @@
self.data = data
self.headers = headers and headers[:] or []
self.renderer = renderer
+
+ # Accepted media type is the portion of the request Accept header
+ # that the renderer satisfied. It could be '*/*', or somthing like
+ # 'application/... |
7a1254fa530b02d32f39e2210ec864f78dd9504a | groundstation/transfer/response_handlers/describeobjects.py | groundstation/transfer/response_handlers/describeobjects.py | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | Remove hook that snuck in | Remove hook that snuck in
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | ---
+++
@@ -7,7 +7,7 @@
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
- if obj not in self.station or True:
+ if obj not in self.station:
request = self._Request("FETCHOBJEC... |
b11a0197bbecbbdb6e5f3c82285f6b749596947d | api/oauth2_urls.py | api/oauth2_urls.py | from django.conf.urls import url
from oauth2_provider import views
urlpatterns = (
url(r'^authorize/$', views.AuthorizationView.as_view(
template_name='accounts/authorize_client.html',
), name="authorize"),
url(r'^token/$', views.TokenView.as_view(), name="token"),
url(r'^revoke_token/$', views... | from django.conf.urls import url
from oauth2_provider import views
urlpatterns = (
url(r'^authorize/?$', views.AuthorizationView.as_view(
template_name='accounts/authorize_client.html',
), name="authorize"),
url(r'^token/?$', views.TokenView.as_view(), name="token"),
url(r'^revoke_token/?$', vi... | Make trailing slash optional in API oauth URL patterns | Make trailing slash optional in API oauth URL patterns
https://github.com/AudioCommons/ac-mediator/issues/19
| Python | apache-2.0 | AudioCommons/ac-mediator,AudioCommons/ac-mediator,AudioCommons/ac-mediator | ---
+++
@@ -2,9 +2,9 @@
from oauth2_provider import views
urlpatterns = (
- url(r'^authorize/$', views.AuthorizationView.as_view(
+ url(r'^authorize/?$', views.AuthorizationView.as_view(
template_name='accounts/authorize_client.html',
), name="authorize"),
- url(r'^token/$', views.TokenView... |
eb763a7c7048b857d408825241ed3de6b68b88f6 | 1/sumofmultiplesof3and5.py | 1/sumofmultiplesof3and5.py | # Project Euler - Problem 1
sum = 0
for i in xrange(1, 1001):
if i % 3 == 0 or i % 5 == 0:
sum = sum + i
print "The sum is: {}".format(sum)
| # Project Euler - Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def main(limit):
sum = 0
for i in xrange(1, limit):
if i % 3 == 0 or i % 5 == 0:
... | Clean up problem 1 solution a bit. | Clean up problem 1 solution a bit.
| Python | mit | gregmojonnier/ProjectEuler | ---
+++
@@ -1,7 +1,16 @@
# Project Euler - Problem 1
-sum = 0
-for i in xrange(1, 1001):
- if i % 3 == 0 or i % 5 == 0:
- sum = sum + i
+# If we list all the natural numbers below 10 that are multiples of 3 or 5,
+# we get 3, 5, 6 and 9. The sum of these multiples is 23.
+# Find the sum of all the multipl... |
1179d825cafb512119906894527de801e43ed906 | metatlas/tests/test_query.py | metatlas/tests/test_query.py | from __future__ import print_function
from metatlas.mzml_loader import mzml_to_hdf, get_test_data
from metatlas.h5_query import get_XICof, get_data
def rmse(target, predictions):
target = target / target.max()
predictions = predictions / predictions.max()
return np.sqrt(((predictions - targets) ** 2).me... | from __future__ import print_function
from metatlas.mzml_loader import mzml_to_hdf, get_test_data
from metatlas.h5_query import get_XIC, get_data
def rmse(target, predictions):
target = target / target.max()
predictions = predictions / predictions.max()
return np.sqrt(((predictions - targets) ** 2).mean... | Fix another import in test | Fix another import in test
| Python | bsd-3-clause | biorack/metatlas,biorack/metatlas,metabolite-atlas/metatlas,aitatanit/metatlas,metabolite-atlas/metatlas,aitatanit/metatlas,aitatanit/metatlas,metabolite-atlas/metatlas | ---
+++
@@ -1,7 +1,7 @@
from __future__ import print_function
from metatlas.mzml_loader import mzml_to_hdf, get_test_data
-from metatlas.h5_query import get_XICof, get_data
+from metatlas.h5_query import get_XIC, get_data
def rmse(target, predictions): |
d05c68b110e4adf5f411816196cf1f457e51951e | nbrmd/__init__.py | nbrmd/__init__.py | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | Allow import in case of missing notebook package | Allow import in case of missing notebook package | Python | mit | mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext | ---
+++
@@ -10,4 +10,7 @@
from .nbrmd import read, reads, readf, write, writes, writef
from .hooks import update_rmd, update_ipynb, update_rmd_and_ipynb, update_selected_formats
-from .cm import RmdFileContentsManager
+try:
+ from .cm import RmdFileContentsManager
+except ImportError as e:
+ RmdFileContentsMana... |
a918dbdb18f579543916da8dfc14e7d3d06237ae | logtacts/prod_settings/__init__.py | logtacts/prod_settings/__init__.py | from logtacts.settings import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))
SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY")
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'.pebble.ink',
'.logtacts.com... | from logtacts.settings import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))
SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY")
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'.pebble.ink',
'.logtacts.com... | Make sure heroku is in accepted hosts | Make sure heroku is in accepted hosts
| Python | mit | phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts | ---
+++
@@ -14,6 +14,7 @@
'.pebble.ink',
'.logtacts.com',
'.contactotter.com',
+ '.herokuapp.com',
]
SECURE_SSL_REDIRECT = True |
802626461779e4de34e7994c88ab698495dfca59 | docs/source/conf.py | docs/source/conf.py | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
# general config
extensions = ['sphinx.ext.autodoc... | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
# general config
extensions = ['sphinx.ext.autodoc... | Enable intersphinx and add mapping for py2.7 + numpy | [doc] Enable intersphinx and add mapping for py2.7 + numpy
| Python | bsd-3-clause | stoewer/nixpy,stoewer/nixpy | ---
+++
@@ -7,7 +7,7 @@
# LICENSE file in the root of the Project.
# general config
-extensions = ['sphinx.ext.autodoc']
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
source_suffix = '.rst'
master_doc = 'index'
project = 'NIX Python bindings'
@@ -18,3 +18,9 @@
# html options
html_theme = 'de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.