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 |
|---|---|---|---|---|---|---|---|---|---|---|
0bb36aebdf0766c9244c6e317df89ddda86361b0 | polls/admin.py | polls/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Ko... | Allow Questions to be copied | Allow Questions to be copied
| Python | apache-2.0 | gerard-/votingapp,gerard-/votingapp | ---
+++
@@ -8,10 +8,21 @@
class ChoiceInline(admin.TabularInline):
model = Choice
+def copy_question(modeladmin, request, queryset):
+ for orig in queryset:
+ q = Question(question_text="Kopie van "+orig.question_text)
+ q.save()
+ for orig_choice in orig.choice_set.all():
+ ... |
6ca27fba516ddc63ad6bae98b20e5f9a42b37451 | examples/plotting/file/image.py | examples/plotting/file/image.py |
import numpy as np
from bokeh.plotting import *
from bokeh.objects import Range1d
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spe... |
import numpy as np
from bokeh.plotting import *
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y... | Fix example and remove extraneous import. | Fix example and remove extraneous import.
| Python | bsd-3-clause | birdsarah/bokeh,srinathv/bokeh,justacec/bokeh,eteq/bokeh,saifrahmed/bokeh,eteq/bokeh,rothnic/bokeh,dennisobrien/bokeh,deeplook/bokeh,draperjames/bokeh,tacaswell/bokeh,daodaoliang/bokeh,abele/bokeh,abele/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,ericdill/bokeh,timsnyder/bokeh,CrazyGuo/bokeh,ptitjano... | ---
+++
@@ -1,7 +1,6 @@
import numpy as np
from bokeh.plotting import *
-from bokeh.objects import Range1d
N = 1000
@@ -18,6 +17,4 @@
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
-curplot().x_range = [5, 10]
-
show() # open a browser |
ce846bf4eb3eb60c0e91a34d434ae5307e194c3a | axes/apps.py | axes/apps.py | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | Fix GitHub code editor whitespaces | Fix GitHub code editor whitespaces | Python | mit | jazzband/django-axes | ---
+++
@@ -22,7 +22,7 @@
if cls.initialized:
return
cls.initialized = True
-
+
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa |
5d8b217659fdd4a7248a60b430a24fe909bca805 | test/test_acoustics.py | test/test_acoustics.py | import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
| import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
def test_acoustic1d_create_matrices():
fld = fds.Acoustic1D(t_delta=1, t_sampl... | Add test case for Acoustic1D.create_matrices(). | Add test case for Acoustic1D.create_matrices().
| Python | bsd-3-clause | emtpb/pyfds | ---
+++
@@ -7,3 +7,13 @@
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
+
+
+def test_acoustic1d_create_matrices():
+ fld = fds.Acoustic1D(t_delta=1, t_samples=1,
+ x_delta=1, x_samples=3,
+ ... |
ebd9949177db3e2db51b47b74254908e300edc13 | process_test.py | process_test.py | """
Copyright 2016 EMBL-European Bioinformatics Institute
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... | """
Copyright 2016 EMBL-European Bioinformatics Institute
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... | Test script to work out the method for creating tasks | Test script to work out the method for creating tasks
| Python | apache-2.0 | Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq | ---
+++
@@ -14,20 +14,24 @@
limitations under the License.
"""
-import argparse, time
+from pycompss.api.parameter import *
from pycompss.api.task import task
-from pycompss.api.parameter import *
-#class process_test:
-#
-# def __init__(self):
-# self.ready = True
-
-@task(x = IN)
def main(... |
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6 | pombola/south_africa/templatetags/za_people_display.py | pombola/south_africa/templatetags/za_people_display.py | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def sh... | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_P... | Fix display of people on constituency office page | [ZA] Fix display of people on constituency office page
This template tag was being called without an organisation, so in
production it was just silently failing, but in development it was
raising an exception.
This adds an extra check so that if there is no organisation then we
just short circuit and return `True`.
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -8,6 +8,8 @@
@register.assignment_tag()
def should_display_place(organisation):
+ if not organisation:
+ return True
return organisation.slug not in NO_PLACE_ORGS
|
e44dc4d68845845f601803f31e10833a24cdb27c | prosite_app.py | prosite_app.py | #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
prositeMatcher = prosite_mat... | #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
if sequence != None and sequ... | Add check for empty sequence or regex. | Add check for empty sequence or regex.
| Python | mit | stack-overflow/py_finite_state | ---
+++
@@ -12,35 +12,41 @@
sequence = input("Sequence: ")
regex = input("Regular expression: ")
- prositeMatcher = prosite_matcher.PrositeMatcher()
- prositeMatcher.compile(regex)
- matches, ranges = prositeMatcher.get_matches(sequence)
+ if sequence != None and sequence != "" and regex != None and regex != ""... |
017aa00a7b1f7a4a8a95f9c41576d4595d4085af | src/python/SparkSQLTwitter.py | src/python/SparkSQLTwitter.py | # A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row, IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc = SparkContext()
hiveCtx =... | # A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext, Row
from pyspark.sql.types import IntegerType
import json
import sys
if __name__ == "__main__":
inputFile = sys.argv[1]
conf = SparkConf().setAppName("SparkSQLTwitter")
sc =... | Fix IntegerType import for Spark SQL | Fix IntegerType import for Spark SQL
| Python | mit | DINESHKUMARMURUGAN/learning-spark,mohitsh/learning-spark,shimizust/learning-spark,JerryTseng/learning-spark,databricks/learning-spark,qingkaikong/learning-spark-examples,huixiang/learning-spark,qingkaikong/learning-spark-examples,obinsanni/learning-spark,bhagatsingh/learning-spark,holdenk/learning-spark-examples,NBSW/l... | ---
+++
@@ -1,6 +1,7 @@
# A simple demo for working with SparkSQL and Tweets
from pyspark import SparkContext, SparkConf
-from pyspark.sql import HiveContext, Row, IntegerType
+from pyspark.sql import HiveContext, Row
+from pyspark.sql.types import IntegerType
import json
import sys
|
4b172a9b2b9a9a70843bd41ad858d6f3120769b0 | tests/test_funcargs.py | tests/test_funcargs.py | from django.test.client import Client
from pytest_django.client import RequestFactory
pytest_plugins = ['pytester']
def test_params(testdir):
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__fil... | from django.test.client import Client
from pytest_django.client import RequestFactory
import py
pytest_plugins = ['pytester']
def test_params(testdir):
# Setting up the path isn't working - plugin.__file__ points to the wrong place
return
testdir.makeconftest("""
import os, sys
import... | Disable params test for now | Disable params test for now
| Python | bsd-3-clause | ojake/pytest-django,pelme/pytest-django,hoh/pytest-django,thedrow/pytest-django,pombredanne/pytest_django,felixonmars/pytest-django,ktosiek/pytest-django,RonnyPfannschmidt/pytest_django,aptivate/pytest-django,davidszotten/pytest-django,reincubate/pytest-django,bforchhammer/pytest-django,tomviner/pytest-django,bfirsh/py... | ---
+++
@@ -1,9 +1,13 @@
from django.test.client import Client
from pytest_django.client import RequestFactory
+import py
pytest_plugins = ['pytester']
def test_params(testdir):
+ # Setting up the path isn't working - plugin.__file__ points to the wrong place
+ return
+
testdir.makeconftest("""... |
849552b1a2afdd89552e7c0395fc7be1786d5cbc | pybossa/auth/user.py | pybossa/auth/user.py | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | Exclude it from coverage as these permissions are not used yet. | Exclude it from coverage as these permissions are not used yet.
| Python | agpl-3.0 | PyBossa/pybossa,PyBossa/pybossa,CulturePlex/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,stefanhahmann/pybossa,geotagx/pybossa,geotagx/pybossa,CulturePlex/pybossa,OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,proyectos-analizo-info/pybossa-analizo... | ---
+++
@@ -19,7 +19,7 @@
from flask.ext.login import current_user
-def create(user=None):
+def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
@@ -29,13 +29,13 @@
return False
-def read(user=None):
+def read(use... |
5c9bdb1260562f0623807ce9a5751d33c806374a | pyfr/nputil.py | pyfr/nputil.py | # -*- coding: utf-8 -*-
import numpy as np
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'ab... | # -*- coding: utf-8 -*-
import numpy as np
def npaligned(shape, dtype, alignb=32):
nbytes = np.prod(shape)*np.dtype(dtype).itemsize
buf = np.zeros(nbytes + alignb, dtype=np.uint8)
off = -buf.ctypes.data % alignb
return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__'... | Add support for allocating aligned NumPy arrays. | Add support for allocating aligned NumPy arrays.
| Python | bsd-3-clause | tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR,tjcorona/PyFR | ---
+++
@@ -1,6 +1,14 @@
# -*- coding: utf-8 -*-
import numpy as np
+
+
+def npaligned(shape, dtype, alignb=32):
+ nbytes = np.prod(shape)*np.dtype(dtype).itemsize
+ buf = np.zeros(nbytes + alignb, dtype=np.uint8)
+ off = -buf.ctypes.data % alignb
+
+ return buf[off:nbytes + off].view(dtype).reshape(s... |
b77d078d096bb18cb02b6da0f7f00da33859bd88 | byceps/util/templatefunctions.py | byceps/util/templatefunctions.py | """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make f... | """
byceps.util.templatefunctions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template global functions.
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import babel
from flask_babel import get_locale, get_timezone
def register(app):
"""Make f... | Use Babel's `format_decimal` instead of deprecated `format_number` | Use Babel's `format_decimal` instead of deprecated `format_number`
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -42,4 +42,4 @@
def _format_number(*args) -> str:
- return babel.numbers.format_number(*args, locale=get_locale())
+ return babel.numbers.format_decimal(*args, locale=get_locale()) |
126c58d78360e69c2d16a40f9396a8158844e2b1 | tests/test_creators.py | tests/test_creators.py | """
Test the post methods.
"""
def test_matrix_creation_endpoint(client):
response = client.post('/matrix', {
'bibliography': '12312312',
'fields': 'title,description',
})
print(response.json())
assert response.status_code == 200
| """
Test the post methods.
"""
from condor.models import Bibliography
def test_matrix_creation_endpoint(client, session):
bib = Bibliography(eid='123', description='lorem')
session.add(bib)
session.flush()
response = client.post('/matrix', {
'bibliography': '123',
'fields': 'title,des... | Create test for matrix post endpoint | Create test for matrix post endpoint
| Python | mit | odarbelaeze/condor-api | ---
+++
@@ -1,12 +1,20 @@
"""
Test the post methods.
"""
+from condor.models import Bibliography
-def test_matrix_creation_endpoint(client):
+def test_matrix_creation_endpoint(client, session):
+ bib = Bibliography(eid='123', description='lorem')
+ session.add(bib)
+ session.flush()
+
response = ... |
e94d39bf330312dc46697a689b56f7518ebd501c | footer/magic/images.py | footer/magic/images.py | #import PIL
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ n... | #import PIL
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ n... | Add some color to SVG key/values | Add some color to SVG key/values
| Python | mit | mihow/footer,mihow/footer,mihow/footer,mihow/footer | ---
+++
@@ -19,12 +19,12 @@
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
- {{ kk }}: {{ vv }}
+ {{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfo... |
ebdafecea8c5b6597a7b2e2822afc98b9c47bb05 | toast/math/__init__.py | toast/math/__init__.py | def lerp(fromValue, toValue, step):
return fromValue + (toValue - fromValue) * step | def lerp(fromValue, toValue, percent):
return fromValue + (toValue - fromValue) * percent | Refactor to lerp param names. | Refactor to lerp param names.
| Python | mit | JoshuaSkelly/Toast,JSkelly/Toast | ---
+++
@@ -1,2 +1,2 @@
-def lerp(fromValue, toValue, step):
- return fromValue + (toValue - fromValue) * step
+def lerp(fromValue, toValue, percent):
+ return fromValue + (toValue - fromValue) * percent |
b2e743a19f13c898b2d95595a7a7175eca4bdb2c | results/urls.py | results/urls.py | __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
)
| __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
url(r'^recent/$', views.recent_re... | Update URLs to include recent results | Update URLs to include recent results
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -6,5 +6,6 @@
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
+ url(r'^recent/$', views.recent_results, name='recentResults'),
)
|
7e3dfe47598401f4d5b96a377927473bb8adc244 | bush/aws/base.py | bush/aws/base.py | from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
self.resource = self.session.resource(resource_na... | from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
@property
def resource(self):
if not has... | Set resource and client when it is needed | Set resource and client when it is needed
| Python | mit | okamos/bush | ---
+++
@@ -9,5 +9,21 @@
self.name = resource_name
self.options = options
self.session = create_session(options)
- self.resource = self.session.resource(resource_name)
- self.client = self.session.client(resource_name)
+
+ @property
+ def resource(self):
+ if not ... |
a014cd2184d4c9634c02d1cac9d1fd41fb3c6c37 | eduid_IdP_html/tests/test_translation.py | eduid_IdP_html/tests/test_translation.py | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None) | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None)
| Add newline at end of file. | Add newline at end of file.
| Python | bsd-3-clause | SUNET/eduid-IdP-html,SUNET/eduid-IdP-html,SUNET/eduid-IdP-html | |
2425f5a3b0b3f465eec86de9873696611dfda04a | example_project/users/social_pipeline.py | example_project/users/social_pipeline.py | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name... | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name... | Fix error message in example project | Fix error message in example project
| Python | mit | st4lk/django-rest-social-auth,st4lk/django-rest-social-auth,st4lk/django-rest-social-auth | ---
+++
@@ -33,4 +33,4 @@
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
- return Response({'error': "Email wasn't provided by facebook"}, status=400)
+ return Response({'error': "Email wasn't provided by oauth provider"}, status=400) |
ab83c8a51cb2950226a5ccf341ad4bd9774a6df4 | client.py | client.py | # encoding=utf-8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.e... | # encoding=utf_8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.e... | Change encoding name for no reason | Change encoding name for no reason
| Python | mit | drkitty/arise | ---
+++
@@ -1,4 +1,4 @@
-# encoding=utf-8
+# encoding=utf_8
from __future__ import unicode_literals
import socket |
20f6df95d302ea79d11208ada6218a2c99d397e3 | common.py | common.py | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
... | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:... | Make a copy of dicts before deleting things from them when printing. | Make a copy of dicts before deleting things from them when printing.
| Python | bsd-2-clause | brendanlong/mpeg-ts-inspector,brendanlong/mpeg-ts-inspector | ---
+++
@@ -11,9 +11,9 @@
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
- d = o
+ d = o.copy()
else:
- d = o.__dict__
+ d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
... |
038d33aa57a89d17a075109dd01eb682591e36ff | config.py | config.py | from config_secret import SecretConfig
class Config:
SECRET_KEY = SecretConfig.SECRET_KEY
# MongoDB config
MONGO_DBNAME = SecretConfig.MONGO_DBNAME
MONGO_HOST = SecretConfig.MONGO_HOST
MONGO_PORT = SecretConfig.MONGO_PORT
# Cloning config
CLONE_TMP_DIR = 'tmp'
CLONE_TIMEOUT = 15
| from config_secret import SecretConfig
class Config:
SECRET_KEY = SecretConfig.SECRET_KEY
# MongoDB config
MONGO_DBNAME = SecretConfig.MONGO_DBNAME
MONGO_HOST = SecretConfig.MONGO_HOST
MONGO_PORT = SecretConfig.MONGO_PORT
# Cloning config
CLONE_TMP_DIR = 'tmp'
CLONE_TIMEOUT = 30
| Increase the cloning timeout limit | Increase the cloning timeout limit
| Python | mit | mingrammer/pyreportcard,mingrammer/pyreportcard | ---
+++
@@ -11,4 +11,4 @@
# Cloning config
CLONE_TMP_DIR = 'tmp'
- CLONE_TIMEOUT = 15
+ CLONE_TIMEOUT = 30 |
fd7027ae889d61949998ea02fbb56dbc8e6005a4 | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/... | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/... | Fix to CHT station name | Fix to CHT station name
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -25,3 +25,8 @@
return None
return super().address_record_to_dict(record)
+
+ def station_record_to_dict(self, record):
+ if record.pollingstationnumber == "191":
+ record = record._replace(pollingstationaddress_1="")
+ return super().station_record_to_dic... |
f2cdd8eb42afb9db5465e062544631684cabd24f | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | wagtail/contrib/wagtailfrontendcache/signal_handlers.py | from django.db import models
from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
pur... | from django.db import models
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published, page_unpublished
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
... | Use page_unpublished signal in frontend cache invalidator | Use page_unpublished signal in frontend cache invalidator
| Python | bsd-3-clause | Pennebaker/wagtail,chrxr/wagtail,jorge-marques/wagtail,jnns/wagtail,kurtw/wagtail,jorge-marques/wagtail,kaedroho/wagtail,WQuanfeng/wagtail,willcodefortea/wagtail,chimeno/wagtail,JoshBarr/wagtail,nimasmi/wagtail,zerolab/wagtail,torchbox/wagtail,kaedroho/wagtail,nutztherookie/wagtail,jorge-marques/wagtail,Klaudit/wagtail... | ---
+++
@@ -1,8 +1,7 @@
from django.db import models
-from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
-from wagtail.wagtailcore.signals import page_published
+from wagtail.wagtailcore.signals import page_published, page_unpublished
from wagtail.contrib.wagtailfronte... |
add50f0356756469c1ee1e52f13faee7df85f280 | tests/rest/rest_test_suite.py | tests/rest/rest_test_suite.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
c... | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
import importlib
class RestTestDict(DotDict):
@property
def __dict__(self):
... | Fix import path for rest plugins | Fix import path for rest plugins
| Python | mpl-2.0 | mozilla/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef | ---
+++
@@ -8,6 +8,7 @@
import mock
from configlib import OptionParser
+import importlib
class RestTestDict(DotDict):
@@ -23,6 +24,10 @@
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
+... |
5b516cd3e6363c4c995022c358fabeb0cc543115 | tests/test_route_requester.py | tests/test_route_requester.py | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
class TestOptionalParameters(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def tes... | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test... | Fix bug in unit tests | Fix bug in unit tests
| Python | apache-2.0 | apranav19/pydirections | ---
+++
@@ -2,9 +2,9 @@
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
+requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
+
class TestOptionalParameters(unittest.Test... |
9b720026722ce92a8c0e05aa041d6e861c5e4e82 | changes/api/jobstep_deallocate.py | changes/api/jobstep_deallocate.py | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(sel... | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(sel... | Allow running jobsteps to be deallocated | Allow running jobsteps to be deallocated
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -15,9 +15,9 @@
if to_deallocate is None:
return '', 404
- if to_deallocate.status != Status.allocated:
+ if to_deallocate.status not in (Status.in_progress, Status.allocated):
return {
- "error": "Only {0} job steps may be deallocated.",
+ ... |
b0f47f2d9b75ac777c3cf4a45c1930de9a42c6bc | heutagogy/heutagogy.py | heutagogy/heutagogy.py | from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DEL... | from heutagogy import app
import heutagogy.persistence
import os
from datetime import timedelta
app.config.from_object(__name__)
app.config.update(dict(
USERS={
'myuser': {'password': 'mypassword'},
'user2': {'password': 'pass2'},
},
JWT_AUTH_URL_RULE='/api/v1/login',
JWT_EXPIRATION_DEL... | Initialize database if it does not exist | Initialize database if it does not exist
| Python | agpl-3.0 | heutagogy/heutagogy-backend,heutagogy/heutagogy-backend | ---
+++
@@ -23,3 +23,8 @@
def initdb_command():
"""Creates the database tables."""
heutagogy.persistence.initialize()
+
+
+with app.app_context():
+ if not os.path.isfile(app.config['DATABASE']):
+ heutagogy.persistence.initialize() |
df739ec121beede945d1bcc43cc239b5e7045c5a | nuxeo-drive-client/nxdrive/tests/test_integration_copy.py | nuxeo-drive-client/nxdrive/tests/test_integration_copy.py | import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
... | import os
from nxdrive.tests.common import IntegrationTestCase
from nxdrive.client import LocalClient
class TestIntegrationCopy(IntegrationTestCase):
def test_synchronize_remote_copy(self):
# Get local and remote clients
local = LocalClient(os.path.join(self.local_nxdrive_folder_1,
... | Remove long timeout to make file blacklisting bug appear, waiting for the fix | NXDRIVE-170: Remove long timeout to make file blacklisting bug appear, waiting for the fix
| Python | lgpl-2.1 | arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,loopingz/nuxeo-drive,ssdi-drive/nuxeo-drive,IsaacYangSLA/nuxeo-drive,arameshkumar/nuxeo-drive,loopingz/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,DirkHoffmann/nuxeo-drive,IsaacYangSLA/nuxeo-drive,IsaacYangSLA/nuxeo-dr... | ---
+++
@@ -25,7 +25,7 @@
remote.copy('/test.odt', '/Test folder')
# Launch ndrive, expecting 4 synchronized items
- self.ndrive(self.ndrive_1, quit_timeout=300)
+ self.ndrive(self.ndrive_1)
self.assertTrue(local.exists('/'))
self.assertTrue(local.exists('/Test fold... |
e50892a1155b9bd35e7b7cbf90646bac1b1724f6 | importkit/languages.py | importkit/languages.py | ##
# Copyright (c) 2013 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
# Import languages to register them
from metamagic.utils.lang import yaml, python, javascript
| ##
# Copyright (c) 2013 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
# Import languages to register them
from metamagic.utils.lang import yaml, python, javascript, jplus
| Switch class system to use JPlus types machinery | utils.lang.js: Switch class system to use JPlus types machinery
| Python | mit | sprymix/importkit | ---
+++
@@ -7,4 +7,4 @@
# Import languages to register them
-from metamagic.utils.lang import yaml, python, javascript
+from metamagic.utils.lang import yaml, python, javascript, jplus |
64cd71fd171cd1b76b111aedc94423006176f811 | src/tldt/cli.py | src/tldt/cli.py | import argparse
import tldt
def main():
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
... | import argparse
import os.path
import tldt
def main():
user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
parser.add_arg... | Add configuration file option with default to ~/tldt.ini | Add configuration file option with default to ~/tldt.ini
| Python | unlicense | rciorba/tldt,rciorba/tldt | ---
+++
@@ -1,20 +1,23 @@
import argparse
+import os.path
import tldt
def main():
+ user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.ad... |
2c825d111125a630a96f0ee739d091a531547be5 | sbc_compassion/model/country_compassion.py | sbc_compassion/model/country_compassion.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the fi... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the fi... | Rename ResCountry class to CompassionCountry | Rename ResCountry class to CompassionCountry
| Python | agpl-3.0 | Secheron/compassion-modules,Secheron/compassion-modules,Secheron/compassion-modules | ---
+++
@@ -12,7 +12,7 @@
from openerp import fields, models
-class ResCountry(models.Model):
+class CompassionCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs. |
775aecd0a39e5112a704ec30657d3e46e3621bdd | django_auth_kerberos/backends.py | django_auth_kerberos/backends.py | import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
... | import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
... | Make user query case insensitive | Make user query case insensitive | Python | mit | 02strich/django-auth-kerberos,mkesper/django-auth-kerberos | ---
+++
@@ -23,7 +23,8 @@
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
- UserModel.USERNAME_FIELD: username
+ UserModel.USERNAME_FIELD+"__iexact": username,
+ defaults: { UserModel.USERNAME_FIELD: username }
... |
45e04697303eb85330bd61f1b386e483fc42f49b | src/oscar/templatetags/currency_filters.py | src/oscar/templatetags/currency_filters.py | from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value... | from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value... | Fix for missing default in currency filter | Fix for missing default in currency filter
| Python | bsd-3-clause | solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar | ---
+++
@@ -14,6 +14,9 @@
"""
Format decimal value as currency
"""
+ if currency is None:
+ currency = settings.OSCAR_DEFAULT_CURRENCY
+
try:
value = D(value)
except (TypeError, InvalidOperation):
@@ -22,7 +25,7 @@
# http://babel.pocoo.org/en/latest/api/numbers.html#ba... |
6cf42d661facf1c11de545959b91c073709eac8e | webapp_tests.py | webapp_tests.py | #!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link(... | #!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link(... | Add a test for extracting service domain from a link | Add a test for extracting service domain from a link
| Python | mit | alphagov/service-domain-checker | ---
+++
@@ -13,9 +13,23 @@
assert True == status
assert "foo.service.gov.uk" == domain
+
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
+
+class WebappTestEx... |
2f6dc1d43bd402152c7807e905cc808899a640d2 | mail/views.py | mail/views.py | import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_c... | import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_c... | Change bulk order email address to Tory | Change bulk order email address to Tory
| Python | agpl-3.0 | openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms | ---
+++
@@ -21,7 +21,7 @@
# Add subject: to_address to this dict to add a new email address.
# Subject will map to the email being sent to to prevent misuse of our email server.
emails = {
- 'Bulk Order': 'rej2@rice.edu',
+ 'Bulk Order': 'Tory.Watterson@rice.edu',
... |
c12a1b53166c34c074e018fcc149a0aa2db56b43 | helpscout/models/folder.py | helpscout/models/folder.py | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The typ... | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The typ... | Add 'team' to Folder type options | [ADD] Add 'team' to Folder type options
| Python | mit | LasLabs/python-helpscout | ---
+++
@@ -22,6 +22,7 @@
'closed',
'spam',
'mine',
+ 'team',
],
default='drafts',
required=True, |
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f | kokki/cookbooks/mdadm/recipes/default.py | kokki/cookbooks/mdadm/recipes/default.py |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
en... |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
fs... | Fix to mounting mdadm raid arrays | Fix to mounting mdadm raid arrays
| Python | bsd-3-clause | samuel/kokki | ---
+++
@@ -13,17 +13,21 @@
))
for array in env.config.mdadm.arrays:
+ fstype = array.pop('fstype', None)
+ fsoptions = array.pop('fsoptions', None)
+ mount_point = array.pop('mount_point', None)
+
env.cookbooks.mdadm.Array(**array)
- if array.get('fstype'):
- if array['fstype'] == "... |
4f2e23fe260e5f061d7d57821908492f14a2c56a | withtool/subprocess.py | withtool/subprocess.py | import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except:
pass
| import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except Exception:
pass
| Set expected exception class in "except" block | Set expected exception class in "except" block
Fix issue E722 of flake8
| Python | mit | renanivo/with | ---
+++
@@ -4,5 +4,5 @@
def run(command):
try:
subprocess.check_call(command, shell=True)
- except:
+ except Exception:
pass |
ff308a17c79fe2c27dcb2a1f888ee1332f6fdc11 | events.py | events.py | # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
... | # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
... | Add a ruler to column 72 | Add a ruler to column 72
| Python | mit | andref/Unnatural-Sublime-Package | ---
+++
@@ -19,3 +19,17 @@
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
+
+
+class AddRulerToColumn72Listener(sublime_plugin.EventListener):
+ """Add a ruler to column 72 when a Natural file is ope... |
5a2f848badcdf9bf968e23cfb55f53eb023d18a4 | tests/helper.py | tests/helper.py | import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'... | import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEM... | Add authentication to base TestCase | Add authentication to base TestCase
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api | ---
+++
@@ -2,8 +2,9 @@
import os
import yaml
from functools import wraps
+from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
-from models import db
+from models import db, Student
from scuevals_api import create_app
@@ -15,9 +16,30 @@
self.appx = app
self.app = app.te... |
ee3aac7a285cf5b80e8c836b9f825173bad2eb59 | doc/development/source/orange-demo/setup.py | doc/development/source/orange-demo/setup.py | from setuptools import setup
setup(name="Demo",
packages=["orangedemo"],
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
entry_points={"orange.widgets": ("Demo = orangedemo")},
... | from setuptools import setup
setup(name="Demo",
packages=["orangedemo"],
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
entry_points={"orange.widgets": "Demo = orangedemo"},
)
| Remove tuple, since string is sufficient here | Remove tuple, since string is sufficient here
As discovered in [discussion around issue #1184](https://github.com/biolab/orange3/issues/1184#issuecomment-214215811), the tuple is not necessary here. Only a single string is necessary, as is documented in the setuptools official [entry_points example](https://pythonhost... | Python | bsd-2-clause | cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3 | ---
+++
@@ -5,5 +5,5 @@
package_data={"orangedemo": ["icons/*.svg"]},
classifiers=["Example :: Invalid"],
# Declare orangedemo package to contain widgets for the "Demo" category
- entry_points={"orange.widgets": ("Demo = orangedemo")},
+ entry_points={"orange.widgets": "Demo = orangedem... |
9ed0848a869fc3a4e16890af609259d18b622056 | ideascaly/utils.py | ideascaly/utils.py | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
from datetime import datetime
def parse_datetime(str_date):
date_is = dateutil.parser.parse(str_date)
return date_is
def parse_html_value(html):
return html[html.find('>')+1:html.rfind('<')]
def ... | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
from datetime import datetime
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
print("Invalid date: %s" % str_date)
retu... | Add try except to the method that parse idea datetime | Add try except to the method that parse idea datetime
| Python | mit | joausaga/ideascaly | ---
+++
@@ -9,9 +9,12 @@
def parse_datetime(str_date):
- date_is = dateutil.parser.parse(str_date)
- return date_is
-
+ try:
+ date_is = dateutil.parser.parse(str_date)
+ return date_is
+ except:
+ print("Invalid date: %s" % str_date)
+ return None
def parse_html_value(... |
811421407379dedc217795000f6f2cbe54510f96 | kolibri/core/utils/urls.py | kolibri/core/utils/urls.py | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, k... | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, k... | Truncate rather than replace to prevent erroneous substitutions. | Truncate rather than replace to prevent erroneous substitutions.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | ---
+++
@@ -12,7 +12,8 @@
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
- reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
+ prefix_length = le... |
fe873844448d4123520e9bd6afe3231d4c952850 | job_runner/wsgi.py | job_runner/wsgi.py | """
WSGI config for job_runner 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_APPLICATION... | """
WSGI config for job_runner 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_APPLICATION... | Update default settings to development. | Update default settings to development.
| Python | bsd-3-clause | spilgames/job-runner,spilgames/job-runner | ---
+++
@@ -15,7 +15,8 @@
"""
import os
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "job_runner.settings")
+os.environ.setdefault(
+ "DJANGO_SETTINGS_MODULE", "job_runner.settings.env.development")
# This application object is used by any WSGI server configured to use this
# file. This includes Django... |
741133b4fa502fc585c771abef96b6213d3f5214 | pyheufybot/modules/nickservidentify.py | pyheufybot/modules/nickservidentify.py | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickSer... | from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attemp... | Fix the syntax for NickServ logins | Fix the syntax for NickServ logins
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -1,5 +1,5 @@
-from module_interface import Module, ModuleType
-from message import IRCResponse, ResponseType
+from pyheufybot.module_interface import Module, ModuleType
+from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
@@ -14,6 +... |
34bd55b33e865c65386f934c7ac0b89f3cc76485 | edgedb/lang/common/shell/reqs.py | edgedb/lang/common/shell/reqs.py | ##
# Copyright (c) 2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from metamagic import app
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
class ValidApplication(CommandRequirement):
def... | ##
# Copyright (c) 2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
| Drop 'metamagic.app' package. Long live Node. | app: Drop 'metamagic.app' package. Long live Node.
| Python | apache-2.0 | edgedb/edgedb,edgedb/edgedb,edgedb/edgedb | ---
+++
@@ -6,7 +6,6 @@
##
-from metamagic import app
from metamagic.exceptions import MetamagicError
@@ -16,9 +15,3 @@
class CommandRequirement:
pass
-
-
-class ValidApplication(CommandRequirement):
- def __init__(self, args):
- if not app.Application.active:
- raise Unsatisfie... |
63a7b11d3ae51a944bf2e70637dea503e455c2f5 | fontdump/cli.py | fontdump/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
from collections import OrderedDict
import requests
import cssutils
USER_AGENTS = OrderedDict()
USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
USER_AGENTS['eot'] = ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
import requests
import cssutils
USER_AGENTS = {
'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
'svg': 'Mozilla/4.0 (iPad; CPU... | Revert "The order of the formats matters. Use OrderedDict instead of dict" | Revert "The order of the formats matters. Use OrderedDict instead of dict"
I can't rely on the order of dict. The control flow is more complex.
This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
| Python | mit | glasslion/fontdump | ---
+++
@@ -1,16 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
-from collections import OrderedDict
-
import requests
import cssutils
-USER_AGENTS = OrderedDict()
-USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
-USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-updat... |
ff9d613897774f3125f2b28905528962b1761deb | core/timeline.py | core/timeline.py | from collections import Counter
from matplotlib import pyplot as plt
import datetime
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_data )
y_axis = []... | from collections import Counter
from matplotlib import pyplot as plt
import datetime
import data_loader
def create_timeline( data ):
if len(data) == 0:
print "Dataset empty."
return
dates = map( lambda d: d['date'], data )
timeline_data = Counter( dates )
x_axis = sorted( timeline_dat... | Add standalone method for using from command line | Add standalone method for using from command line
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | ---
+++
@@ -1,6 +1,7 @@
from collections import Counter
from matplotlib import pyplot as plt
import datetime
+import data_loader
def create_timeline( data ):
if len(data) == 0:
@@ -18,3 +19,8 @@
plt.plot_date( x = x_axis, y = y_axis, fmt = "r-" )
ymin, ymax = plt.ylim()
plt.ylim( 0, ymax + 1... |
18b89f719fd8d870448a5914e82b0364c5b9a1f5 | docs/tutorials/polls/mysite/settings.py | docs/tutorials/polls/mysite/settings.py | from lino.projects.std.settings import *
class Site(Site):
title = "Cool Polls"
def get_installed_apps(self):
yield super(Site, self).get_installed_apps()
yield 'polls'
def setup_menu(self, profile, main):
m = main.add_menu("polls", "Polls")
m.add_action('polls.Questions... | from lino.projects.std.settings import *
class Site(Site):
title = "Cool Polls"
demo_fixtures = ['demo', 'demo1']
def get_installed_apps(self):
yield super(Site, self).get_installed_apps()
yield 'polls'
def setup_menu(self, profile, main):
m = main.add_menu("polls", "Polls"... | Use the available fixtures for demo_fixtures. | Use the available fixtures for demo_fixtures.
| Python | unknown | khchine5/book,khchine5/book,lino-framework/book,khchine5/book,lsaffre/lino_book,lsaffre/lino_book,lsaffre/lino_book,lino-framework/book,lino-framework/book,lino-framework/book | ---
+++
@@ -4,6 +4,8 @@
class Site(Site):
title = "Cool Polls"
+
+ demo_fixtures = ['demo', 'demo1']
def get_installed_apps(self):
yield super(Site, self).get_installed_apps() |
62f9608d50898d0a82e013d54454ed1edb004cff | fab_deploy/joyent/setup.py | fab_deploy/joyent/setup.py | from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDS... | from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDS... | Add environ vars for joyent | Add environ vars for joyent | Python | mit | ff0000/red-fab-deploy2,ff0000/red-fab-deploy2,ff0000/red-fab-deploy2 | ---
+++
@@ -16,6 +16,10 @@
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
+
+ def _set_profile(self):
+ JoyentMixin._set_profile(self)
+ base_setup.AppSetup._set_profile(self)
def _install_packages(s... |
678054b5c890456b903eb43b08855091288d12cc | osfoffline/settings/defaults.py | osfoffline/settings/defaults.py | # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'... | # Just to insure requirement
import colorlog # noqa
# Development mode: use a local OSF dev version and more granular logging
DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests`
# General settings
PROJECT_NAME = 'osf-offline'
PROJECT_AUTHOR = 'cos'
APPLICATION_SCOPES = 'osf.full_write'... | Use max poll delay to avoid OSErrors | Use max poll delay to avoid OSErrors
| Python | apache-2.0 | chennan47/OSF-Offline,chennan47/OSF-Offline | ---
+++
@@ -14,8 +14,7 @@
FILE_BASE = 'https://files.osf.io'
# Interval (in seconds) to poll the OSF for server-side file changes
-# YEARS * DAYS * HOURS * MIN * SECONDS
-POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds
+POLL_DELAY = 24 * 60 * 60 # Once per day
# Time to keep alert messages on scre... |
fc3cf6966f66f0929c48b1f24bede295fb3aec35 | Wahji-dev/setup/removeWahji.py | Wahji-dev/setup/removeWahji.py | #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
print "deleting content"
"""delete them folder and its contents"""
shutil.rmtree("themes")
"""delete .wahji file"""
os.remove(".wahji")
"""delete 4040.html file"""
os.remove("404.html")
"""delete content folder"""
shutil.... | #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
site = raw_input("Input site folder: ")
print "Are you sure you want to delete", site, "Y/N: "
confirm = raw_input()
if confirm == "Y" or confirm == "y":
"""delete site folder"""
shutil.rmtree(site)
print "Deleting site"
... | Remove now asks for site file to be deleted | Remove now asks for site file to be deleted
| Python | mit | mborn319/Wahji,mborn319/Wahji,mborn319/Wahji | ---
+++
@@ -5,17 +5,16 @@
os.chdir(loc)
- print "deleting content"
-
- """delete them folder and its contents"""
- shutil.rmtree("themes")
+ site = raw_input("Input site folder: ")
- """delete .wahji file"""
- os.remove(".wahji")
+ print "Are you sure you want to delete", site, "Y/N: "
+ confirm = raw_inpu... |
bff72be24e44cec1d819de630afb91868fadeaa5 | luminoso_api/compat.py | luminoso_api/compat.py | import sys
# Detect Python 3
PY3 = (sys.hexversion >= 0x03000000)
if PY3:
types_not_to_encode = (int, str)
string_type = str
from urllib.parse import urlparse
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
from urllib2 import urlparse
| import sys
# Detect Python 3
PY3 = (sys.hexversion >= 0x03000000)
if PY3:
types_not_to_encode = (int, str)
string_type = str
from urllib.parse import urlparse
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
from urlparse import urlparse
| Fix the urlparse import in Python 2. (This is used for saving/loading tokens in files.) The urlparse that you can import from urllib2 is actually the urlparse module, but what we want is the urlparse function inside that module. | Fix the urlparse import in Python 2. (This is used for saving/loading tokens in files.) The urlparse that you can import from urllib2 is actually the urlparse module, but what we want is the urlparse function inside that module.
| Python | mit | LuminosoInsight/luminoso-api-client-python | ---
+++
@@ -10,4 +10,4 @@
else:
types_not_to_encode = (int, long, basestring)
string_type = basestring
- from urllib2 import urlparse
+ from urlparse import urlparse |
6b55f079d595700cd84d12d4f351e52614d291c5 | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields,models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
inst... | # -*- coding: utf-8 -*-
from openerp import fields,models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
ins... | Add domain ir and ilike | [REF] openacademy: Add domain ir and ilike
| Python | apache-2.0 | arogel/openacademy-project | ---
+++
@@ -8,7 +8,11 @@
start_date = fields.Date()
duration = fields.Float(digits=(6,2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
- instructor_id = fields.Many2one('res.partner', string="Instructor")
+
+ instructor_id = fields.Many2one('res.partner', string="Inst... |
429716ef6d15e0c7e49174409b8195eb8ef14b26 | back-end/BAA/settings/prod.py | back-end/BAA/settings/prod.py | from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/projec... | from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/projec... | Change to a secret secret key | Change to a secret secret key
| Python | mit | jumbocodespring2017/bostonathleticsassociation,jumbocodespring2017/bostonathleticsassociation,jumbocodespring2017/bostonathleticsassociation | ---
+++
@@ -39,3 +39,5 @@
EMAIL_USE_TLS = True
FROM_EMAIL = 'ian@ianluo.com'
DOMAIN = 'http://floating-castle-71814.herokuapp.com/'
+
+SECRET_KEY = os.getenv('DJANGO_SECRETKEY') |
91d104a25db499ccef54878dcbfce42dbb4aa932 | taskin/task.py | taskin/task.py | import abc
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class MapTask(object):
def __init__(self, args, task):
self.args = args
self.task = task
self.pool = Pool(cpu_count())
def iter_input(self, i... | from multiprocessing import Pool as ProcessPool
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class PoolAPI(object):
def map(self, *args,... | Add totally untested pools ;) | Add totally untested pools ;)
| Python | bsd-3-clause | ionrock/taskin | ---
+++
@@ -1,4 +1,6 @@
-import abc
+from multiprocessing import Pool as ProcessPool
+from multiprocessing.dummy import Pool as ThreadPool
+from multiprocessing import cpu_count
def do_flow(flow, result=None):
@@ -8,19 +10,41 @@
return result
+class PoolAPI(object):
+ def map(self, *args, **kw):
+ ... |
247c4dcaf3e1c1f9c069ab8a2fc06cfcd75f8ea9 | UM/Util.py | UM/Util.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Convert a value to a boolean
#
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
return value in [True, "True", "true", 1]
| # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Convert a value to a boolean
#
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
return value in [True, "True", "true", "Yes", "yes", 1]
| Add "Yes" as an option for parsing bools | Add "Yes" as an option for parsing bools
CURA-2204
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -6,4 +6,4 @@
# \param \type{bool|str|int} any value.
# \return \type{bool}
def parseBool(value):
- return value in [True, "True", "true", 1]
+ return value in [True, "True", "true", "Yes", "yes", 1] |
6e3ddfc47487a8841a79d6265c96ba63005fccec | bnw_handlers/command_onoff.py | bnw_handlers/command_onoff.py | # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},s... | # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},s... | Fix on/off if there is no 'off' field. | Fix on/off if there is no 'off' field.
| Python | bsd-2-clause | un-def/bnw,stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw | ---
+++
@@ -11,7 +11,7 @@
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
- if request.user['off']:
+ if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Wel... |
bbef6c5f235fc3320c9c748a32cb3af04d3903d1 | list_all_users_in_group.py | list_all_users_in_group.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Origin in https://github.com/vazhnov/list... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Ori... | Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens) | Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens)
| Python | cc0-1.0 | vazhnov/list_all_users_in_group | ---
+++
@@ -1,6 +1,7 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
+from __future__ import print_function
import grp
import pwd
import inspect
@@ -18,7 +19,7 @@
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
- except (KeyError):
+ ex... |
82e82805eae5b070aec49816977d2f50ff274d30 | controllers/api/api_match_controller.py | controllers/api/api_match_controller.py | import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CAC... | import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args... | Move cache key out of base class | Move cache key out of base class
| Python | mit | josephbisch/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-l... | ---
+++
@@ -10,14 +10,9 @@
class ApiMatchControllerBase(ApiBaseController):
- CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
- CACHE_VERSION = 2
- CACHE_HEADER_LENGTH = 60 * 60
-
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
... |
b2771e6b33bd889c971b77e1b30c1cc5a0b9eb24 | platform.py | platform.py | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Use appropriate package for mxchip_az3166 | Use appropriate package for mxchip_az3166
| Python | apache-2.0 | platformio/platform-ststm32,platformio/platform-ststm32 | ---
+++
@@ -26,6 +26,8 @@
if board == "mxchip_az3166":
self.frameworks['arduino'][
+ 'package'] = "framework-arduinostm32mxchip"
+ self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openoc... |
1096d0f13ebbc5900c21626a5caf6276b36229d8 | Lib/test/test_coding.py | Lib/test/test_coding.py |
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def veri... |
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def veri... | Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8. | Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded
in utf-8.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -16,7 +16,7 @@
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
- fp = open(filename)
+ fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, '... |
37588d466928e9f25b55d627772120f16df095ec | model_presenter.py | model_presenter.py | import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
... | import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
... | Compress the images to be sent | Compress the images to be sent
| Python | mit | cjluo/money-monkey | ---
+++
@@ -23,13 +23,13 @@
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2)
- png_file = NamedTemporaryFile(delete=False, suffix='.png')
- png_file.close()
+ jpg_file = NamedTemporaryFile(delete=False, suffix='.jpg')
+ jpg_file.close()
fig.set_dpi(100)
fig.set... |
9901044b2b3218714a3c807e982db518aa97a446 | djangoautoconf/features/bae_settings.py | djangoautoconf/features/bae_settings.py | ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
fro... | ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
fr... | Move BAE secret into try catch block | Move BAE secret into try catch block
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -1,6 +1,7 @@
##################################
# Added for BAE
##################################
+
try:
CACHES = {
@@ -14,6 +15,7 @@
pass
try:
from bae.core import const
+ import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql... |
3ed807b44289c00d6a82b0c253f7ff8072336fdd | changes/jobs/cleanup_tasks.py | changes/jobs/cleanup_tasks.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't... | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# N... | Make periodic expired task deletion more efficient | Make periodic expired task deletion more efficient
Summary: Also adds tracking for the number of tasks deleted at each run.
Test Plan: None
Reviewers: paulruan
Reviewed By: paulruan
Subscribers: changesbot, anupc
Differential Revision: https://tails.corp.dropbox.com/D232735
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -2,7 +2,7 @@
from datetime import datetime, timedelta
-from changes.config import queue
+from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
@@ -12,6 +12,7 @@
# NOTE: This isn't its... |
dd8c85a49a31693f43e6f6877a0657d63cbc1b01 | auth0/v2/device_credentials.py | auth0/v2/device_credentials.py | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in ... | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in ... | Remove default arguments for user_id, client_id and type | Remove default arguments for user_id, client_id and type
| Python | mit | auth0/auth0-python,auth0/auth0-python | ---
+++
@@ -23,8 +23,7 @@
return url + '/' + id
return url
- def get(self, user_id=None, client_id=None, type=None,
- fields=[], include_fields=True):
+ def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join... |
24ea32f71faab214a6f350d2d48b2f5715d8262d | manage.py | manage.py | from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app
from app import db
from app.auth import Register, Login
from app.bucketlist_api import BucketList, BucketListEntry
from app.bucketlist_items import BucketListItems, BucketListItemSingle
... | from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app, db
from app.auth import Register, Login
from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Mig... | Set urls for bucketlist items endpoints | Set urls for bucketlist items endpoints
| Python | mit | andela-bmwenda/cp2-bucketlist-api | ---
+++
@@ -1,10 +1,9 @@
from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
-from app import app
-from app import db
+from app import app, db
from app.auth import Register, Login
-from app.bucketlist_api import BucketList, BucketListEntry
+from app.buc... |
8a6c678c18bb112caf89b7b7c9968215e9e0eff5 | begotemp/models/watercourse.py | begotemp/models/watercourse.py | # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
... | # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
... | Correct the geographic field name | Correct the geographic field name | Python | mit | miniwark/begotemp | ---
+++
@@ -12,7 +12,7 @@
watercourse_id = Column(Integer, primary_key=True)
watercourse_name = Column(Unicode, unique=True)
- geo_polygon = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
+ geo_linestring = GeometryColumn(LineString(2, srid=2154, spatial_index=False))
GeometryDDL... |
b6e57269b8bd57420fb856daba75452dbf37cfa2 | tests/scoring_engine/engine/checks/test_https.py | tests/scoring_engine/engine/checks/test_https.py | from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestHTTPSCheck(CheckTest):
check_name = 'HTTPSCheck'
required_properties = ['useragent', 'vhost', 'uri']
properties = {
'useragent': 'testagent',
'vhost': 'www.example.com',
'uri': '/index.html'
}
cmd... | from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestHTTPSCheck(CheckTest):
check_name = 'HTTPSCheck'
required_properties = ['useragent', 'vhost', 'uri']
properties = {
'useragent': 'testagent',
'vhost': 'www.example.com',
'uri': '/index.html'
}
cmd... | Fix pep8 new line in test https check | Fix pep8 new line in test https check
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | |
638a1c434ef8202774675581c3659511fa9d1cd3 | vehicles/management/commands/import_edinburgh.py | vehicles/management/commands/import_edinburgh.py | from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
... | from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
... | Fix null Edinburgh journey code or destination | Fix null Edinburgh journey code or destination
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | ---
+++
@@ -11,8 +11,8 @@
def get_journey(self, item):
journey = VehicleJourney(
- code=item['journey_id'],
- destination=item['destination']
+ code=item['journey_id'] or '',
+ destination=item['destination'] or ''
)
vehicle_defaults = {} |
8523576286a45318f654ad5ab462e9a6f65b69e2 | canary/app.py | canary/app.py | import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_check(function):
start_time = time.time()
ret = function()
total_time = time.time() - start_time
return json.dumps({
'status': r... | import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_decorator(func):
def actual_check():
start_time = time.time()
try:
ret = func()
except:
# FIXME... | Use a decorator to wrap the actual checks | Use a decorator to wrap the actual checks
| Python | mit | yuvipanda/tools-canary | ---
+++
@@ -8,16 +8,23 @@
app = Flask(__name__)
app.debug = True
+
def check(endpoint):
- def actual_check(function):
- start_time = time.time()
- ret = function()
- total_time = time.time() - start_time
- return json.dumps({
- 'status': ret,
- 'time': total_t... |
c9da64ac1c90abdee8fc72488a4bef58a95aa7c6 | biwako/bin/fields/compounds.py | biwako/bin/fields/compounds.py | import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
... | import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
... | Fix List to use the new decoding system | Fix List to use the new decoding system
| Python | bsd-3-clause | gulopine/steel | ---
+++
@@ -34,13 +34,13 @@
value_bytes = b''
values = []
if self.instance:
- instance_field = field.for_instance(self.instance)
+ instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.r... |
b8eb19e56682bc7546ad4ba12db46cd4fa48dfa1 | etc/ci/check_dynamic_symbols.py | etc/ci/check_dynamic_symbols.py | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | Add Python 3 compatibility to Android symbol checker | Add Python 3 compatibility to Android symbol checker
Make the script that checks for undefined Android symbols compatible
with both Python 2 and Python 3, to allow for future updates to the
default system Python on our build machines.
I'd like to land this before https://github.com/servo/saltfs/pull/249.
We currentl... | Python | mpl-2.0 | dsandeephegde/servo,thiagopnts/servo,notriddle/servo,dati91/servo,splav/servo,szeged/servo,mbrubeck/servo,splav/servo,dati91/servo,mattnenterprise/servo,mbrubeck/servo,eddyb/servo,avadacatavra/servo,ConnorGBrewster/servo,avadacatavra/servo,paulrouget/servo,cbrewster/servo,szeged/servo,larsbergstrom/servo,emilio/servo,p... | ---
+++
@@ -11,15 +11,15 @@
import re
import subprocess
-symbol_regex = re.compile("D \*UND\*\t(.*) (.*)$")
-allowed_symbols = frozenset(['unshare', 'malloc_usable_size'])
+symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$")
+allowed_symbols = frozenset([b'unshare', b'malloc_usable_size'])
actual_symbols = set... |
1f8b19d3baa2970adc008d5b7903730b51edad58 | example_site/settings/travis.py | example_site/settings/travis.py | from .base import *
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_DIR, '..', 'data', 'db.sqlite3')),
}
}
ALLOWED_HOSTS = [
'127.0.0.1'
]
# email settings
EMAIL_HOST = 'localhost'
EMAIL_... | from .base import *
DEBUG = False
# Make data dir
DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data'))
not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.abspath(os.path.join(
BASE_D... | Add the creation of the data dir for the sqlite file. | Add the creation of the data dir for the sqlite file.
| Python | mit | cnobile2012/dcolumn,cnobile2012/dcolumn,cnobile2012/dcolumn,cnobile2012/dcolumn | ---
+++
@@ -1,6 +1,10 @@
from .base import *
DEBUG = False
+
+# Make data dir
+DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'data'))
+not os.path.isdir(DATA_DIR) and os.mkdir(DATA_DIR, 0o0775)
DATABASES = {
'default': { |
1e5e2a236277dc9ba11f9fe4aff3279f692da3f7 | ploy/tests/conftest.py | ploy/tests/conftest.py | from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('.... | from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('.... | Add convenience function to read tempdir files. | Add convenience function to read tempdir files.
| Python | bsd-3-clause | fschulze/ploy,ployground/ploy | ---
+++
@@ -28,6 +28,10 @@
content = '\n'.join(content)
f.write(content)
+ def content(self):
+ with open(self.path) as f:
+ return f.read()
+
@pytest.yield_fixture
def tempdir(): |
1965b1db79758a53eb45f81bb25e83c4d09b95af | pupa/scrape/helpers.py | pupa/scrape/helpers.py | """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_det... | """ these are helper classes for object creation during the scrape """
from pupa.models.person import Person
from pupa.models.organization import Organization
from pupa.models.membership import Membership
class Legislator(Person):
_is_legislator = True
__slots__ = ('post_id', 'party', 'chamber', '_contact_det... | Add a slot for legislator role | Add a slot for legislator role
| Python | bsd-3-clause | rshorey/pupa,rshorey/pupa,influence-usa/pupa,influence-usa/pupa,mileswwatkins/pupa,datamade/pupa,opencivicdata/pupa,mileswwatkins/pupa,datamade/pupa,opencivicdata/pupa | ---
+++
@@ -6,7 +6,7 @@
class Legislator(Person):
_is_legislator = True
- __slots__ = ('post_id', 'party', 'chamber', '_contact_details')
+ __slots__ = ('post_id', 'party', 'chamber', '_contact_details', 'role')
def __init__(self, name, post_id, party=None, chamber=None, **kwargs):
super... |
854709e1c2f5351c8e7af49e238fe54632f23ff5 | takeyourmeds/settings/defaults/apps.py | takeyourmeds/settings/defaults/apps.py | INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyou... | INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyour... | Return .sites to INSTALLED_APPS until we drop allauth | Return .sites to INSTALLED_APPS until we drop allauth
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | ---
+++
@@ -3,6 +3,7 @@
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
+ 'django.contrib.sites',
'django.contrib.staticfiles',
'allauth', |
bf142af653dec7eb781faf6a45385a411bdfeee2 | scripts/lib/paths.py | scripts/lib/paths.py | details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
info_path = './courses/info.json'
term_dest = './courses/terms/'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid ... | details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
info_path = './build/info.json'
term_dest = './build/terms/'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid = st... | Put the build stuff back in /build | Put the build stuff back in /build
| Python | mit | StoDevX/course-data-tools,StoDevX/course-data-tools | ---
+++
@@ -1,8 +1,8 @@
details_source = './source/details/'
xml_source = './source/raw_xml/'
course_dest = './source/courses/'
-info_path = './courses/info.json'
-term_dest = './courses/terms/'
+info_path = './build/info.json'
+term_dest = './build/terms/'
mappings_path = './related-d... |
a1cf7353917bbcee569cb8b6bb0d6277ee41face | dependency_injector/__init__.py | dependency_injector/__init__.py | """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Ob... | """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Ob... | Add Injection into __all__ list of top level package | Add Injection into __all__ list of top level package
| Python | bsd-3-clause | rmk135/dependency_injector,ets-labs/dependency_injector,rmk135/objects,ets-labs/python-dependency-injector | ---
+++
@@ -51,6 +51,7 @@
'Config',
# Injections
+ 'Injection',
'KwArg',
'Attribute',
'Method', |
6a8295baf32c80ea447d92fd3c7a01a2ad2e0df8 | openquake/risklib/__init__.py | openquake/risklib/__init__.py | # coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
... | # coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
... | Upgrade release number to 0.6.0 (oq-engine 1.3.0) | Upgrade release number to 0.6.0 (oq-engine 1.3.0)
| Python | agpl-3.0 | g-weatherill/oq-risklib,vup1120/oq-risklib,raoanirudh/oq-risklib,gem/oq-engine,gem/oq-engine,g-weatherill/oq-risklib,gem/oq-engine,gem/oq-engine,raoanirudh/oq-risklib,g-weatherill/oq-risklib,gem/oq-engine,vup1120/oq-risklib | ---
+++
@@ -25,7 +25,7 @@
__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]
# the version is managed by packager.sh with a sed
-__version__ = '0.5.1'
+__version__ = '0.6.0'
__version__ += git_suffix(__file__)
path = search_module('openquake.commonlib.general') |
43ee2b8cfde4d0276cfd561063554705462001cf | openmm/run_test.py | openmm/run_test.py | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.ver... | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '9567ddb304c48d336e82927adf2761e8780e9270', "openmm.ver... | Update git hash in test | Update git hash in test
| Python | mit | peastman/conda-recipes,cwehmeyer/conda-recipes,jchodera/conda-recipes,peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,... | ---
+++
@@ -6,4 +6,4 @@
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
-assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_rev... |
37f08dab37601b7621743467d6b78fb0306b5054 | lcapy/config.py | lcapy/config.py | # SymPy symbols to exclude
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {... | # SymPy symbols to exclude
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's s... | Exclude beta, gamma, zeta functions | Exclude beta, gamma, zeta functions
| Python | lgpl-2.1 | mph-/lcapy | ---
+++
@@ -1,5 +1,5 @@
# SymPy symbols to exclude
-exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
+exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
@@ -12,6 +12,6 @@
import sympy as sym... |
b278cf74b6ac57daee8e4ead6044f43ffd89a1f1 | importer/importer/__init__.py | importer/importer/__init__.py | import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
async def initialize():
elastic = Elasticsearch(ELASTIC_E... | import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
# commands
async def initialize():
elastic = Elasticsear... | Remove all previous aliases when initializing | Remove all previous aliases when initializing
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | ---
+++
@@ -12,17 +12,12 @@
ELASTIC_ALIAS = 'theatrics'
+# commands
+
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
- module_path = os.path.dirname(__file__)
- config_filename = os.path.join(module_path, 'configuration', 'index.json')
- index_configuration = read_json_file(con... |
3dd205a9dad39abb12e7a05c178117545402c2e1 | reinforcement-learning/train.py | reinforcement-learning/train.py | """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("... | """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("... | Update to newest version of rl.py. | Update to newest version of rl.py.
| Python | mit | danieloconell/Louis | ---
+++
@@ -35,7 +35,7 @@
if env.done:
pbar.update(1)
break
- action = rl.choose_action(rl.table[env.object[0]])
+ action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)... |
f88c2135ddc197283bbfb8b481774deb613571cf | python/raindrops/raindrops.py | python/raindrops/raindrops.py | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
| def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
| Handle 5 as a factor | Handle 5 as a factor
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -1,7 +1,12 @@
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
+ if is_five_a_factor(number):
+ return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
+
+def is_five_a_factor(number):
+ return number % 5 ==... |
2f10aa07422c8132218d8af336406629b336550c | docs/src/conf.py | docs/src/conf.py | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'... | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'... | Replace execfile with py3-compatible equivalent | Replace execfile with py3-compatible equivalent
| Python | bsd-3-clause | fpoirotte/XRL | ---
+++
@@ -29,6 +29,6 @@
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
- execfile(conf, globs, locs)
+ exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals... |
5e5a6a55d43bf66c7f71d054b92a66528bf2a571 | driver/driver.py | driver/driver.py | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
... | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self, requirements):
pass
@abstractmethod
def _set_quota(self, id, quota):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(sel... | Fix inconsistency in parameters with base class | Fix inconsistency in parameters with base class
| Python | apache-2.0 | PressLabs/cobalt,PressLabs/cobalt | ---
+++
@@ -3,7 +3,11 @@
class Driver(metaclass=ABCMeta):
@abstractmethod
- def create(self):
+ def create(self, requirements):
+ pass
+
+ @abstractmethod
+ def _set_quota(self, id, quota):
pass
@abstractmethod
@@ -19,5 +23,5 @@
pass
@abstractmethod
- def ... |
1fe377ec1957d570a1dcc860c2bda415088bf6be | dwight_chroot/platform_utils.py | dwight_chroot/platform_utils.py | import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} fail... | import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} fail... | Fix execute_command_assert_success return code logging | Fix execute_command_assert_success return code logging
| Python | bsd-3-clause | vmalloc/dwight,vmalloc/dwight,vmalloc/dwight | ---
+++
@@ -9,7 +9,7 @@
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
- raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
+ raise CommandFailed("Command {0!r} failed with exit code {1}".form... |
b1c5f75c266f5f5b9976ce2ca7c2b9065ef41bb1 | groupmestats/generatestats.py | groupmestats/generatestats.py | import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
... | import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
... | Print args when generating stats | Print args when generating stats
| Python | mit | kjteske/groupmestats,kjteske/groupmestats | ---
+++
@@ -22,6 +22,8 @@
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
+
+ print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeE... |
7b7f33439b16faeef67022374cf88ba9a275ce8a | flocker/filesystems/interfaces.py | flocker/filesystems/interfaces.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Interfaces that filesystem APIs need to expose.
"""
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
""... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Interfaces that filesystem APIs need to expose.
"""
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
""... | Address review comment: Don't state the obvious. | Address review comment: Don't state the obvious.
| Python | apache-2.0 | LaynePeng/flocker,agonzalezro/flocker,AndyHuu/flocker,achanda/flocker,jml/flocker,AndyHuu/flocker,lukemarsden/flocker,mbrukman/flocker,runcom/flocker,Azulinho/flocker,jml/flocker,mbrukman/flocker,w4ngyi/flocker,hackday-profilers/flocker,achanda/flocker,lukemarsden/flocker,achanda/flocker,beni55/flocker,lukemarsden/floc... | ---
+++
@@ -31,6 +31,5 @@
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
- :py:class:`flocker.snapshots.SnapshotName`. This will likely be
- improved in later iterations.
+ :py:class:`flocker.snapshots.SnapshotName`.
... |
df51d042bf1958f48fc39f1f3870285c87491243 | lemon/templatetags/main_menu.py | lemon/templatetags/main_menu.py | from django.template import Library, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(URLNode):
def __init__(self, content_ty... | from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
cla... | Fix main menu url reversing in admin | Fix main menu url reversing in admin
| Python | bsd-3-clause | trilan/lemon,trilan/lemon,trilan/lemon | ---
+++
@@ -1,4 +1,5 @@
-from django.template import Library, Variable
+from django.core.urlresolvers import reverse, NoReverseMatch
+from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
@@ -9,26 +... |
e548713f5192d125b1313fa955240965a1136de8 | plugin/__init__.py | plugin/__init__.py | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... | # -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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/license... | UPDATE init; add utf-8 encoding | UPDATE init; add utf-8 encoding
| Python | apache-2.0 | fastconnect/cloudify-azure-plugin | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
# |
28786f30be37bb43a175262f96b618fc440d5ace | send-email.py | send-email.py | #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credent... | #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credent... | Change email subject. Not much of an ALERT if it happens every day. | Change email subject. Not much of an ALERT if it happens every day.
| Python | unlicense | nerflad/mds-new-products,nerflad/mds-new-products,nerflad/mds-new-products | ---
+++
@@ -39,7 +39,7 @@
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
- msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
+ msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(tim... |
400c506627deca5d85454928254b1968e09dc33e | scrape.py | scrape.py | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query... | import re
import requests
import scholarly
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
class Papers(object):
"""Wrapper around scholarly._search_scholar_soup that allows one to get the
number of papers found in the search with len()"""
def __init__(self, query, s... | Allow getting number of results found with len() | Allow getting number of results found with len()
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | ---
+++
@@ -1,28 +1,48 @@
+import re
+import requests
import scholarly
-import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
-def search(query, exact=True, start_year=None, end_year=None):
- """Search by scholar query and return a generator of Publication obje... |
ce2ea43a9ca49caa50e26bc7d7e11ba97edea929 | src/zeit/content/article/edit/browser/tests/test_header.py | src/zeit/content/article/edit/browser/tests/test_header.py | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
block = 'quiz'
# copy&paste from self.create_block()
s.cl... | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
# Select header that allows header module
s.click('css=#edit-form... | Fix test, needs to select proper header for header-module to be enabled (belongs to commit:eb1b6fa) | ZON-3167: Fix test, needs to select proper header for header-module to be enabled (belongs to commit:eb1b6fa)
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article | ---
+++
@@ -6,6 +6,14 @@
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
+ # Select header that allows header module
+ s.click('css=#edit-form-misc .edit-bar .fold-link')
+ s.select('id=options-template.template', 'Kolumne')
+ ... |
2e9cb250d58474354bdfff1edb4fc9e71ee95d60 | lightbus/utilities/importing.py | lightbus/utilities/importing.py | import importlib
import logging
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
... | import importlib
import logging
import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
if name in sys.modules:
return sys.modules[name]
else:
return importlib.import_module(name)
def import_from... | Fix to import_module_from_string() to prevent multiple imports | Fix to import_module_from_string() to prevent multiple imports
| Python | apache-2.0 | adamcharnock/lightbus | ---
+++
@@ -1,5 +1,6 @@
import importlib
import logging
+import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
@@ -8,7 +9,10 @@
def import_module_from_string(name):
- return importlib.import_module(name)
+ if name in sys.modules:
+ return sys.modules[name]
+ else:
+ ... |
0c18e83248a752a3191da1d9c8369fafc2b61674 | purepython/urls.py | purepython/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'purepython.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
from fb.views import index
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', index),
url(r'^admin/', include(admin.site.urls)),
)
| Add url to access the index view. | Add url to access the index view.
| Python | apache-2.0 | pure-python/brainmate | ---
+++
@@ -1,12 +1,11 @@
from django.conf.urls import patterns, include, url
+from django.contrib import admin
-from django.contrib import admin
+from fb.views import index
+
admin.autodiscover()
urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'purepython.views.home', name='home'),
- # url(r'... |
8b9065b99c8bcbb401f12e9e10b23d6ea4b976f0 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
def main():
import warnings
warnings.filterwarnings('error', category=DeprecationWarning)
if not settings.configured:
# Dynamically configure the Django settings with the minimum necessary to
# get... | #!/usr/bin/env python
import sys
import django
from django.conf import settings
def main():
import warnings
warnings.filterwarnings('error', category=DeprecationWarning)
if not settings.configured:
# Dynamically configure the Django settings with the minimum necessary to
# get Django ru... | Remove ':memory:' as that is default | Remove ':memory:' as that is default
| Python | bsd-3-clause | willandskill/django-parse-push | ---
+++
@@ -1,6 +1,5 @@
#!/usr/bin/env python
-import os
import sys
import django
@@ -22,18 +21,13 @@
'django.contrib.sessions',
'parse_push',
],
- # Django still complains? :(
- DATABASE_ENGINE='django.db.backends.sqlite3',
- DATA... |
d2716cf8a5d605098b296ab835c1f4115dd45a5b | test/integration/ggrc/models/__init__.py | test/integration/ggrc/models/__init__.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
| Create mixins package for testing | Create mixins package for testing
| Python | apache-2.0 | VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,AleksNeStu/gg... | ---
+++
@@ -1,3 +1,2 @@
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.